[fuchsia] Delete obsolete GFX-specific source files (#44594)
This change removes
- GFX source files removed from the BUILD in #44401
- Extraneous unused Scenic includes in the same directory
(`//shell/platform/fuchsia/flutter/`)
- All remaining uses of the Scenic library from the Fuchsia SDK
- All remaining uses of fuchsia.ui.scenic.*
diff --git a/ci/licenses_golden/excluded_files b/ci/licenses_golden/excluded_files
index 65bba4a..e104b08 100644
--- a/ci/licenses_golden/excluded_files
+++ b/ci/licenses_golden/excluded_files
@@ -304,7 +304,6 @@
../../../flutter/shell/platform/fuchsia/flutter/kernel/libraries.yaml
../../../flutter/shell/platform/fuchsia/flutter/kernel/pubspec.yaml
../../../flutter/shell/platform/fuchsia/flutter/keyboard_unittest.cc
-../../../flutter/shell/platform/fuchsia/flutter/platform_view_unittest.cc
../../../flutter/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc
../../../flutter/shell/platform/fuchsia/flutter/pointer_injector_delegate_unittest.cc
../../../flutter/shell/platform/fuchsia/flutter/rtree_unittests.cc
diff --git a/ci/licenses_golden/licenses_flutter b/ci/licenses_golden/licenses_flutter
index 0a1366d..fbd02b5 100644
--- a/ci/licenses_golden/licenses_flutter
+++ b/ci/licenses_golden/licenses_flutter
@@ -2959,12 +2959,6 @@
ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/focus_delegate.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/fuchsia_intl.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/fuchsia_intl.h + ../../../flutter/LICENSE
-ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/gfx_external_view_embedder.cc + ../../../flutter/LICENSE
-ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/gfx_external_view_embedder.h + ../../../flutter/LICENSE
-ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/gfx_platform_view.cc + ../../../flutter/LICENSE
-ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/gfx_platform_view.h + ../../../flutter/LICENSE
-ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/gfx_session_connection.cc + ../../../flutter/LICENSE
-ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/gfx_session_connection.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/isolate_configurator.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/isolate_configurator.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/fuchsia/flutter/kernel/framework_shim.dart + ../../../flutter/LICENSE
@@ -5711,12 +5705,6 @@
FILE: ../../../flutter/shell/platform/fuchsia/flutter/focus_delegate.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/fuchsia_intl.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/fuchsia_intl.h
-FILE: ../../../flutter/shell/platform/fuchsia/flutter/gfx_external_view_embedder.cc
-FILE: ../../../flutter/shell/platform/fuchsia/flutter/gfx_external_view_embedder.h
-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/isolate_configurator.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/isolate_configurator.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/kernel/framework_shim.dart
diff --git a/ci/licenses_golden/licenses_fuchsia b/ci/licenses_golden/licenses_fuchsia
index 167190a..36eafb9 100644
--- a/ci/licenses_golden/licenses_fuchsia
+++ b/ci/licenses_golden/licenses_fuchsia
@@ -1085,14 +1085,6 @@
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.modular/surface.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.net.mdns/mdns.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.sys/flat_namespace.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/commands.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/display_info.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/events.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/nodes.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/renderer.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/resources.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/shapes.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/types.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/ime_service.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/input_device_registry.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/input_reports.fidl + ../../../fuchsia/sdk/linux/LICENSE
@@ -1132,12 +1124,6 @@
ORIGIN: ../../../fuchsia/sdk/linux/pkg/fidl_cpp_wire/include/lib/fidl/cpp/wire/vector_view.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/fit/include/lib/fit/function.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/fit/include/lib/fit/internal/function.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/commands.cc + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/commands.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/resources.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/session.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/resources.cc + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/session.cc + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/trace-engine/include/lib/trace-engine/context.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/trace-engine/include/lib/trace-engine/fields.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/trace-engine/include/lib/trace-engine/handler.h + ../../../fuchsia/sdk/linux/LICENSE
@@ -1213,14 +1199,6 @@
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.modular/surface.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.net.mdns/mdns.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.sys/flat_namespace.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/commands.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/display_info.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/events.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/nodes.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/renderer.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/resources.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/shapes.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/types.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/ime_service.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/input_device_registry.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/input_reports.fidl
@@ -1260,12 +1238,6 @@
FILE: ../../../fuchsia/sdk/linux/pkg/fidl_cpp_wire/include/lib/fidl/cpp/wire/vector_view.h
FILE: ../../../fuchsia/sdk/linux/pkg/fit/include/lib/fit/function.h
FILE: ../../../fuchsia/sdk/linux/pkg/fit/include/lib/fit/internal/function.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/commands.cc
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/commands.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/resources.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/session.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/resources.cc
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/session.cc
FILE: ../../../fuchsia/sdk/linux/pkg/trace-engine/include/lib/trace-engine/context.h
FILE: ../../../fuchsia/sdk/linux/pkg/trace-engine/include/lib/trace-engine/fields.h
FILE: ../../../fuchsia/sdk/linux/pkg/trace-engine/include/lib/trace-engine/handler.h
@@ -1387,14 +1359,8 @@
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.sysmem/image_formats_deprecated.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.sysmem/usages.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.app/view_provider.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/pose_buffer_provider.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/commands.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.policy/display_usage.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/commands.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/events.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/scenic.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/session.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/snapshot.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.views/commands.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/async-cpp/include/lib/async/cpp/time.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/async-cpp/include/lib/async/cpp/trap.h + ../../../fuchsia/sdk/linux/LICENSE
@@ -1491,8 +1457,6 @@
ORIGIN: ../../../fuchsia/sdk/linux/pkg/inspect/vmo/types.cc + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/media_cpp/include/lib/media/cpp/type_converters.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/media_cpp/type_converters.cc + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/id.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/view_token_pair.cc + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/optional.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/queue.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/type_traits.h + ../../../fuchsia/sdk/linux/LICENSE
@@ -1601,14 +1565,8 @@
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.sysmem/image_formats_deprecated.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.sysmem/usages.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.app/view_provider.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/pose_buffer_provider.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/commands.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.policy/display_usage.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/commands.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/events.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/scenic.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/session.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/snapshot.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.views/commands.fidl
FILE: ../../../fuchsia/sdk/linux/pkg/async-cpp/include/lib/async/cpp/time.h
FILE: ../../../fuchsia/sdk/linux/pkg/async-cpp/include/lib/async/cpp/trap.h
@@ -1705,8 +1663,6 @@
FILE: ../../../fuchsia/sdk/linux/pkg/inspect/vmo/types.cc
FILE: ../../../fuchsia/sdk/linux/pkg/media_cpp/include/lib/media/cpp/type_converters.h
FILE: ../../../fuchsia/sdk/linux/pkg/media_cpp/type_converters.cc
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/id.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/view_token_pair.cc
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/optional.h
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/queue.h
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/type_traits.h
@@ -2417,7 +2373,6 @@
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/inspect.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/modular.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/performance.dart + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/scenic.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/setui.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/sl4f_client.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/ssh.dart + ../../../fuchsia/sdk/linux/LICENSE
@@ -2428,7 +2383,6 @@
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/flutter_frame_stats.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/input_latency.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/memory_metrics.dart + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/scenic_frame_stats.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/temperature_metrics.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics_results.dart + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics_spec.dart + ../../../fuchsia/sdk/linux/LICENSE
@@ -2554,7 +2508,6 @@
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.app/view_config.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.brightness/brightness.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.brightness/color_adjustment.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/tokens.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/pointer_capture.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.policy/device_listener.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.types/types.fidl + ../../../fuchsia/sdk/linux/LICENSE
@@ -2624,9 +2577,6 @@
ORIGIN: ../../../fuchsia/sdk/linux/pkg/inspect_service_cpp/reader.cc + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/inspect_service_cpp/service.cc + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/magma_client/include/lib/magma/magma_sysmem.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/view_ref_pair.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/view_token_pair.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/view_ref_pair.cc + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/internal/constructors.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/internal/storage.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/internal/utility.h + ../../../fuchsia/sdk/linux/LICENSE
@@ -2715,7 +2665,6 @@
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/inspect.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/modular.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/performance.dart
-FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/scenic.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/setui.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/sl4f_client.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/ssh.dart
@@ -2726,7 +2675,6 @@
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/flutter_frame_stats.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/input_latency.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/memory_metrics.dart
-FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/scenic_frame_stats.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics/temperature_metrics.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics_results.dart
FILE: ../../../fuchsia/sdk/linux/dart/sl4f/lib/src/trace_processing/metrics_spec.dart
@@ -2852,7 +2800,6 @@
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.app/view_config.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.brightness/brightness.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.brightness/color_adjustment.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/tokens.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/pointer_capture.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.policy/device_listener.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.types/types.fidl
@@ -2922,9 +2869,6 @@
FILE: ../../../fuchsia/sdk/linux/pkg/inspect_service_cpp/reader.cc
FILE: ../../../fuchsia/sdk/linux/pkg/inspect_service_cpp/service.cc
FILE: ../../../fuchsia/sdk/linux/pkg/magma_client/include/lib/magma/magma_sysmem.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/view_ref_pair.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/view_token_pair.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/view_ref_pair.cc
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/internal/constructors.h
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/internal/storage.h
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/internal/utility.h
@@ -3169,8 +3113,6 @@
ORIGIN: ../../../fuchsia/sdk/linux/pkg/fit/include/lib/fit/internal/result.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/fit/include/lib/fit/result.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/input_report_reader/include/lib/input_report_reader/reader.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/commands_sizing.cc + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/commands_sizing.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/array.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/bit.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/internal/array.h + ../../../fuchsia/sdk/linux/LICENSE
@@ -3343,8 +3285,6 @@
FILE: ../../../fuchsia/sdk/linux/pkg/fit/include/lib/fit/internal/result.h
FILE: ../../../fuchsia/sdk/linux/pkg/fit/include/lib/fit/result.h
FILE: ../../../fuchsia/sdk/linux/pkg/input_report_reader/include/lib/input_report_reader/reader.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/commands_sizing.cc
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/commands_sizing.h
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/array.h
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/bit.h
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/internal/array.h
@@ -3503,10 +3443,6 @@
ORIGIN: ../../../fuchsia/sdk/linux/pkg/fidl_driver/include/lib/fidl_driver/cpp/wire_types.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/fidl_driver_transport/include/lib/fidl_driver/cpp/transport.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/fidl_driver_transport/transport.cc + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/view_creation_tokens.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/view_identity.h + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/view_creation_tokens.cc + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/view_identity.cc + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/algorithm.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/atomic.h + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/cstddef.h + ../../../fuchsia/sdk/linux/LICENSE
@@ -3651,10 +3587,6 @@
FILE: ../../../fuchsia/sdk/linux/pkg/fidl_driver/include/lib/fidl_driver/cpp/wire_types.h
FILE: ../../../fuchsia/sdk/linux/pkg/fidl_driver_transport/include/lib/fidl_driver/cpp/transport.h
FILE: ../../../fuchsia/sdk/linux/pkg/fidl_driver_transport/transport.cc
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/view_creation_tokens.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/include/lib/ui/scenic/cpp/view_identity.h
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/view_creation_tokens.cc
-FILE: ../../../fuchsia/sdk/linux/pkg/scenic_cpp/view_identity.cc
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/algorithm.h
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/atomic.h
FILE: ../../../fuchsia/sdk/linux/pkg/stdcompat/include/lib/stdcompat/cstddef.h
@@ -3808,14 +3740,12 @@
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.composition/screen_capture.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.composition/screenshot.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.display.singleton/info.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/overview.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/overview.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input3/overview.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.observation.geometry/overview.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.pointer/overview.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.pointerinjector/overview.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.policy/overview.fidl + ../../../fuchsia/sdk/linux/LICENSE
-ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/overview.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.test.input/media_buttons.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.test.input/mouse.fidl + ../../../fuchsia/sdk/linux/LICENSE
ORIGIN: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.test.input/overview.fidl + ../../../fuchsia/sdk/linux/LICENSE
@@ -4055,14 +3985,12 @@
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.composition/screen_capture.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.composition/screenshot.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.display.singleton/info.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.gfx/overview.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input/overview.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.input3/overview.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.observation.geometry/overview.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.pointer/overview.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.pointerinjector/overview.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.policy/overview.fidl
-FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.scenic/overview.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.test.input/media_buttons.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.test.input/mouse.fidl
FILE: ../../../fuchsia/sdk/linux/fidl/fuchsia.ui.test.input/overview.fidl
diff --git a/shell/platform/fuchsia/flutter/BUILD.gn b/shell/platform/fuchsia/flutter/BUILD.gn
index 8e952c8..09dad6f 100644
--- a/shell/platform/fuchsia/flutter/BUILD.gn
+++ b/shell/platform/fuchsia/flutter/BUILD.gn
@@ -140,7 +140,6 @@
public_deps = [
"$fuchsia_sdk_root/pkg:inspect",
- "$fuchsia_sdk_root/pkg:scenic_cpp",
"$fuchsia_sdk_root/pkg:sys_cpp",
"$fuchsia_sdk_root/pkg:sys_inspect_cpp",
"//flutter/shell/platform/fuchsia/runtime/dart/utils",
@@ -157,6 +156,8 @@
"$fuchsia_sdk_root/fidl:fuchsia.memorypressure",
"$fuchsia_sdk_root/fidl:fuchsia.ui.app",
"$fuchsia_sdk_root/fidl:fuchsia.ui.composition",
+ "$fuchsia_sdk_root/fidl:fuchsia.ui.input",
+ "$fuchsia_sdk_root/fidl:fuchsia.ui.input3",
"$fuchsia_sdk_root/fidl:fuchsia.ui.pointer",
"$fuchsia_sdk_root/fidl:fuchsia.ui.pointerinjector",
"$fuchsia_sdk_root/fidl:fuchsia.ui.test.input",
diff --git a/shell/platform/fuchsia/flutter/accessibility_bridge_unittest.cc b/shell/platform/fuchsia/flutter/accessibility_bridge_unittest.cc
index 0afa31e..5ac2dd4 100644
--- a/shell/platform/fuchsia/flutter/accessibility_bridge_unittest.cc
+++ b/shell/platform/fuchsia/flutter/accessibility_bridge_unittest.cc
@@ -4,6 +4,7 @@
#include "accessibility_bridge.h"
+#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/async/cpp/executor.h>
@@ -13,7 +14,7 @@
#include <lib/inspect/cpp/inspector.h>
#include <lib/inspect/cpp/reader.h>
#include <lib/sys/cpp/testing/service_directory_provider.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
+#include <lib/zx/eventpair.h>
#include <zircon/status.h>
#include <zircon/types.h>
@@ -112,7 +113,16 @@
[this](int32_t node_id, flutter::SemanticsAction action) {
accessibility_delegate_.DispatchSemanticsAction(node_id, action);
};
- auto [view_ref_control, view_ref] = scenic::ViewRefPair::New();
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
accessibility_bridge_ =
std::make_unique<flutter_runner::AccessibilityBridge>(
std::move(set_semantics_enabled_callback),
diff --git a/shell/platform/fuchsia/flutter/component_v2.cc b/shell/platform/fuchsia/flutter/component_v2.cc
index e32ccf9..05788f6 100644
--- a/shell/platform/fuchsia/flutter/component_v2.cc
+++ b/shell/platform/fuchsia/flutter/component_v2.cc
@@ -12,8 +12,6 @@
#include <lib/fdio/directory.h>
#include <lib/fdio/io.h>
#include <lib/fdio/namespace.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
-#include <lib/ui/scenic/cpp/view_token_pair.h>
#include <lib/vfs/cpp/composed_service_dir.h>
#include <lib/vfs/cpp/remote_dir.h>
#include <lib/vfs/cpp/service.h>
@@ -635,6 +633,18 @@
return;
}
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ auto view_ref_pair =
+ std::make_pair(std::move(view_ref_control), std::move(view_ref));
+
shell_holders_.emplace(std::make_unique<Engine>(
*this, // delegate
debug_label_, // thread label
@@ -643,7 +653,7 @@
settings_, // settings
std::move(
*view_args.mutable_view_creation_token()), // view creation token
- scenic::ViewRefPair::New(), // view ref pair
+ std::move(view_ref_pair), // view ref pair
std::move(fdio_ns_), // FDIO namespace
std::move(directory_request_), // outgoing request
product_config_, // product configuration
diff --git a/shell/platform/fuchsia/flutter/engine.cc b/shell/platform/fuchsia/flutter/engine.cc
index f02dcc1..b0612ac 100644
--- a/shell/platform/fuchsia/flutter/engine.cc
+++ b/shell/platform/fuchsia/flutter/engine.cc
@@ -7,6 +7,7 @@
#include <fuchsia/accessibility/semantics/cpp/fidl.h>
#include <fuchsia/media/cpp/fidl.h>
#include <lib/async/cpp/task.h>
+#include <lib/zx/eventpair.h>
#include <lib/zx/thread.h>
#include <zircon/rights.h>
#include <zircon/status.h>
@@ -203,7 +204,8 @@
std::shared_ptr<sys::ServiceDirectory> runner_services,
flutter::Settings settings,
fuchsia::ui::views::ViewCreationToken view_creation_token,
- scenic::ViewRefPair view_ref_pair,
+ std::pair<fuchsia::ui::views::ViewRefControl,
+ fuchsia::ui::views::ViewRef> view_ref_pair,
UniqueFDIONS fdio_ns,
fidl::InterfaceRequest<fuchsia::io::Directory> directory_request,
FlutterRunnerProductConfiguration product_config,
@@ -223,7 +225,8 @@
}
void Engine::Initialize(
- scenic::ViewRefPair view_ref_pair,
+ std::pair<fuchsia::ui::views::ViewRefControl, fuchsia::ui::views::ViewRef>
+ view_ref_pair,
std::shared_ptr<sys::ServiceDirectory> svc,
std::shared_ptr<sys::ServiceDirectory> runner_services,
flutter::Settings settings,
@@ -313,11 +316,11 @@
// Make clones of the `ViewRef` before sending it to various places.
fuchsia::ui::views::ViewRef platform_view_ref;
- view_ref_pair.view_ref.Clone(&platform_view_ref);
+ view_ref_pair.second.Clone(&platform_view_ref);
fuchsia::ui::views::ViewRef accessibility_view_ref;
- view_ref_pair.view_ref.Clone(&accessibility_view_ref);
+ view_ref_pair.second.Clone(&accessibility_view_ref);
fuchsia::ui::views::ViewRef isolate_view_ref;
- view_ref_pair.view_ref.Clone(&isolate_view_ref);
+ view_ref_pair.second.Clone(&isolate_view_ref);
// Session is terminated on the raster thread, but we must terminate ourselves
// on the platform thread.
@@ -366,8 +369,8 @@
max_frames_in_flight, vsync_offset);
fuchsia::ui::views::ViewIdentityOnCreation view_identity = {
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref)};
+ .view_ref = std::move(view_ref_pair.second),
+ .view_ref_control = std::move(view_ref_pair.first)};
view_embedder_ = std::make_shared<ExternalViewEmbedder>(
std::move(view_creation_token), std::move(view_identity),
std::move(view_protocols), std::move(request), flatland_connection_,
diff --git a/shell/platform/fuchsia/flutter/engine.h b/shell/platform/fuchsia/flutter/engine.h
index d4a00c9..dab4dc1 100644
--- a/shell/platform/fuchsia/flutter/engine.h
+++ b/shell/platform/fuchsia/flutter/engine.h
@@ -14,8 +14,6 @@
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/sys/cpp/service_directory.h>
-#include <lib/ui/scenic/cpp/id.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
#include "flutter/flow/embedded_views.h"
#include "flutter/flow/surface.h"
@@ -55,7 +53,8 @@
std::shared_ptr<sys::ServiceDirectory> runner_services,
flutter::Settings settings,
fuchsia::ui::views::ViewCreationToken view_creation_token,
- scenic::ViewRefPair view_ref_pair,
+ std::pair<fuchsia::ui::views::ViewRefControl,
+ fuchsia::ui::views::ViewRef> view_ref_pair,
UniqueFDIONS fdio_ns,
fidl::InterfaceRequest<fuchsia::io::Directory> directory_request,
FlutterRunnerProductConfiguration product_config,
@@ -73,7 +72,8 @@
private:
void Initialize(
- scenic::ViewRefPair view_ref_pair,
+ std::pair<fuchsia::ui::views::ViewRefControl, fuchsia::ui::views::ViewRef>
+ view_ref_pair,
std::shared_ptr<sys::ServiceDirectory> svc,
std::shared_ptr<sys::ServiceDirectory> runner_services,
flutter::Settings settings,
diff --git a/shell/platform/fuchsia/flutter/external_view_embedder.h b/shell/platform/fuchsia/flutter/external_view_embedder.h
index 7c489da..a5771a9 100644
--- a/shell/platform/fuchsia/flutter/external_view_embedder.h
+++ b/shell/platform/fuchsia/flutter/external_view_embedder.h
@@ -8,7 +8,6 @@
#include <fuchsia/ui/composition/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/fit/function.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
#include <cstdint> // For uint32_t & uint64_t
#include <memory>
diff --git a/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc b/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc
index 62f8a7b..5ded2a6 100644
--- a/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc
+++ b/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc
@@ -7,7 +7,7 @@
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fidl/cpp/binding_set.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
+#include <lib/zx/eventpair.h>
#include "focus_delegate.h"
#include "tests/fakes/focuser.h"
@@ -131,14 +131,22 @@
// with a non-error status code.
TEST_F(FocusDelegateTest, RequestFocusTest) {
// This "Mock" ViewRef serves as the target for the RequestFocus operation.
- auto mock_view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+
// Create the platform message request.
std::ostringstream message;
message << "{"
<< " \"method\":\"View.focus.request\","
<< " \"args\": {"
- << " \"viewRef\":"
- << mock_view_ref_pair.view_ref.reference.get() << " }"
+ << " \"viewRef\":" << view_ref.reference.get() << " }"
<< "}";
// Dispatch the plaform message request with an expected completion response.
@@ -155,7 +163,15 @@
// with a Error::DENIED status code.
TEST_F(FocusDelegateTest, RequestFocusFailTest) {
// This "Mock" ViewRef serves as the target for the RequestFocus operation.
- auto mock_view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
// We're testing the focus failure case.
focuser_->fail_request_focus();
// Create the platform message request.
@@ -163,8 +179,7 @@
message << "{"
<< " \"method\":\"View.focus.request\","
<< " \"args\": {"
- << " \"viewRef\":"
- << mock_view_ref_pair.view_ref.reference.get() << " }"
+ << " \"viewRef\":" << view_ref.reference.get() << " }"
<< "}";
// Dispatch the plaform message request with an expected completion response.
diff --git a/shell/platform/fuchsia/flutter/gfx_external_view_embedder.cc b/shell/platform/fuchsia/flutter/gfx_external_view_embedder.cc
deleted file mode 100644
index e30c8f7..0000000
--- a/shell/platform/fuchsia/flutter/gfx_external_view_embedder.cc
+++ /dev/null
@@ -1,719 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "gfx_external_view_embedder.h"
-
-#include <lib/ui/scenic/cpp/commands.h>
-#include <lib/ui/scenic/cpp/view_token_pair.h>
-#include <zircon/types.h>
-
-#include <algorithm> // For std::clamp
-
-#include "flutter/fml/logging.h"
-#include "flutter/fml/trace_event.h"
-#include "third_party/skia/include/core/SkPicture.h"
-#include "third_party/skia/include/core/SkSurface.h"
-#include "third_party/skia/include/gpu/GrDirectContext.h"
-#include "third_party/skia/include/gpu/GrRecordingContext.h"
-
-namespace flutter_runner {
-namespace {
-
-ViewMutators ParseMutatorStack(const flutter::MutatorsStack& mutators_stack) {
- ViewMutators mutators;
- SkMatrix total_transform = SkMatrix::I();
- SkMatrix transform_accumulator = SkMatrix::I();
-
- for (auto i = mutators_stack.Begin(); i != mutators_stack.End(); ++i) {
- const auto& mutator = *i;
- switch (mutator->GetType()) {
- case flutter::MutatorType::kOpacity: {
- mutators.opacity *= std::clamp(mutator->GetAlphaFloat(), 0.f, 1.f);
- } break;
- case flutter::MutatorType::kTransform: {
- total_transform.preConcat(mutator->GetMatrix());
- transform_accumulator.preConcat(mutator->GetMatrix());
- } break;
- case flutter::MutatorType::kClipRect: {
- mutators.clips.emplace_back(TransformedClip{
- .transform = transform_accumulator,
- .rect = mutator->GetRect(),
- });
- transform_accumulator = SkMatrix::I();
- } break;
- case flutter::MutatorType::kClipRRect: {
- mutators.clips.emplace_back(TransformedClip{
- .transform = transform_accumulator,
- .rect = mutator->GetRRect().getBounds(),
- });
- transform_accumulator = SkMatrix::I();
- } break;
- case flutter::MutatorType::kClipPath: {
- mutators.clips.emplace_back(TransformedClip{
- .transform = transform_accumulator,
- .rect = mutator->GetPath().getBounds(),
- });
- transform_accumulator = SkMatrix::I();
- } break;
- default: {
- break;
- }
- }
- }
- mutators.total_transform = total_transform;
- mutators.transform = transform_accumulator;
- mutators.opacity = std::clamp(mutators.opacity, 0.f, 1.f);
-
- return mutators;
-}
-
-std::vector<fuchsia::ui::gfx::Plane3> ClipPlanesFromRect(SkRect rect) {
- // We will generate 4 oriented planes, one for each edge of the bounding rect.
- std::vector<fuchsia::ui::gfx::Plane3> clip_planes;
- clip_planes.resize(4);
-
- // Top plane.
- clip_planes[0].dist = rect.top();
- clip_planes[0].dir.x = 0.f;
- clip_planes[0].dir.y = 1.f;
- clip_planes[0].dir.z = 0.f;
-
- // Bottom plane.
- clip_planes[1].dist = -rect.bottom();
- clip_planes[1].dir.x = 0.f;
- clip_planes[1].dir.y = -1.f;
- clip_planes[1].dir.z = 0.f;
-
- // Left plane.
- clip_planes[2].dist = rect.left();
- clip_planes[2].dir.x = 1.f;
- clip_planes[2].dir.y = 0.f;
- clip_planes[2].dir.z = 0.f;
-
- // Right plane.
- clip_planes[3].dist = -rect.right();
- clip_planes[3].dir.x = -1.f;
- clip_planes[3].dir.y = 0.f;
- clip_planes[3].dir.z = 0.f;
-
- return clip_planes;
-}
-
-} // namespace
-
-GfxExternalViewEmbedder::GfxExternalViewEmbedder(
- std::string debug_label,
- fuchsia::ui::views::ViewToken view_token,
- scenic::ViewRefPair view_ref_pair,
- std::shared_ptr<GfxSessionConnection> session,
- std::shared_ptr<SurfaceProducer> surface_producer,
- bool intercept_all_input)
- : session_(session),
- surface_producer_(surface_producer),
- root_view_(session_->get(),
- std::move(view_token),
- std::move(view_ref_pair.control_ref),
- std::move(view_ref_pair.view_ref),
- debug_label),
- metrics_node_(session_->get()),
- layer_tree_node_(session_->get()) {
- layer_tree_node_.SetLabel("Flutter::LayerTree");
- metrics_node_.SetLabel("Flutter::MetricsWatcher");
- metrics_node_.SetEventMask(fuchsia::ui::gfx::kMetricsEventMask);
- metrics_node_.AddChild(layer_tree_node_);
- root_view_.AddChild(metrics_node_);
-
- // Set up the input interceptor at the top of the scene, if applicable. It
- // will capture all input, and any unwanted input will be reinjected into
- // embedded views.
- if (intercept_all_input) {
- input_interceptor_node_.emplace(session_->get());
- input_interceptor_node_->SetLabel("Flutter::InputInterceptor");
- input_interceptor_node_->SetHitTestBehavior(
- fuchsia::ui::gfx::HitTestBehavior::kDefault);
- input_interceptor_node_->SetSemanticVisibility(false);
-
- metrics_node_.AddChild(input_interceptor_node_.value());
- }
-
- session_->Present();
-}
-
-GfxExternalViewEmbedder::~GfxExternalViewEmbedder() = default;
-
-flutter::DlCanvas* GfxExternalViewEmbedder::GetRootCanvas() {
- auto found = frame_layers_.find(kRootLayerId);
- if (found == frame_layers_.end()) {
- FML_LOG(WARNING)
- << "No root canvas could be found. This is extremely unlikely and "
- "indicates that the external view embedder did not receive the "
- "notification to begin the frame.";
- return nullptr;
- }
-
- return found->second.canvas_spy->GetSpyingCanvas();
-}
-
-void GfxExternalViewEmbedder::PrerollCompositeEmbeddedView(
- int64_t view_id,
- std::unique_ptr<flutter::EmbeddedViewParams> params) {
- zx_handle_t handle = static_cast<zx_handle_t>(view_id);
- FML_CHECK(frame_layers_.count(handle) == 0);
-
- frame_layers_.emplace(std::make_pair(
- EmbedderLayerId{handle},
- EmbedderLayer(frame_size_, *params, flutter::RTreeFactory())));
- frame_composition_order_.push_back(handle);
-}
-
-flutter::DlCanvas* GfxExternalViewEmbedder::CompositeEmbeddedView(
- int64_t view_id) {
- zx_handle_t handle = static_cast<zx_handle_t>(view_id);
- auto found = frame_layers_.find(handle);
- FML_CHECK(found != frame_layers_.end());
-
- return found->second.canvas_spy->GetSpyingCanvas();
-}
-
-flutter::PostPrerollResult GfxExternalViewEmbedder::PostPrerollAction(
- fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger) {
- return flutter::PostPrerollResult::kSuccess;
-}
-
-void GfxExternalViewEmbedder::BeginFrame(
- SkISize frame_size,
- GrDirectContext* context,
- double device_pixel_ratio,
- fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger) {
- TRACE_EVENT0("flutter", "GfxExternalViewEmbedder::BeginFrame");
-
- // Reset for new frame.
- Reset();
- frame_size_ = frame_size;
- frame_dpr_ = device_pixel_ratio;
-
- // Create the root layer.
- frame_layers_.emplace(std::make_pair(
- kRootLayerId,
- EmbedderLayer(frame_size, std::nullopt, flutter::RTreeFactory())));
- frame_composition_order_.push_back(kRootLayerId);
-
- // Set up the input interceptor at the top of the scene, if applicable.
- if (input_interceptor_node_.has_value()) {
- const uint64_t rect_hash =
- (static_cast<uint64_t>(frame_size_.width()) << 32) +
- frame_size_.height();
-
- // Create a new rect if needed for the interceptor.
- auto found_rect = scenic_interceptor_rects_.find(rect_hash);
- if (found_rect == scenic_interceptor_rects_.end()) {
- auto [emplaced_rect, success] =
- scenic_interceptor_rects_.emplace(std::make_pair(
- rect_hash, scenic::Rectangle(session_->get(), frame_size_.width(),
- frame_size_.height())));
- FML_CHECK(success);
-
- found_rect = std::move(emplaced_rect);
- }
-
- // TODO(fxb/): Don't hardcode elevation.
- input_interceptor_node_->SetTranslation(
- frame_size.width() * 0.5f, frame_size.height() * 0.5f,
- -kScenicElevationForInputInterceptor);
- input_interceptor_node_->SetShape(found_rect->second);
- }
-}
-
-void GfxExternalViewEmbedder::EndFrame(
- bool should_resubmit_frame,
- fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger) {
- TRACE_EVENT0("flutter", "GfxExternalViewEmbedder::EndFrame");
-}
-
-void GfxExternalViewEmbedder::SubmitFrame(
- GrDirectContext* context,
- const std::shared_ptr<impeller::AiksContext>& aiks_context,
- std::unique_ptr<flutter::SurfaceFrame> frame) {
- TRACE_EVENT0("flutter", "GfxExternalViewEmbedder::SubmitFrame");
- std::vector<std::unique_ptr<SurfaceProducerSurface>> frame_surfaces;
- std::unordered_map<EmbedderLayerId, size_t> frame_surface_indices;
-
- // Create surfaces for the frame and associate them with layer IDs.
- {
- TRACE_EVENT0("flutter", "CreateSurfaces");
-
- for (const auto& layer : frame_layers_) {
- if (!layer.second.canvas_spy->DidDrawIntoCanvas()) {
- continue;
- }
-
- auto surface =
- surface_producer_->ProduceSurface(layer.second.surface_size);
- if (!surface) {
- const std::string layer_id_str =
- layer.first.has_value() ? std::to_string(layer.first.value())
- : "Background";
- FML_LOG(ERROR) << "Failed to create surface for layer " << layer_id_str
- << "; size (" << layer.second.surface_size.width()
- << ", " << layer.second.surface_size.height() << ")";
- FML_DCHECK(false);
- continue;
- }
-
- frame_surface_indices.emplace(
- std::make_pair(layer.first, frame_surfaces.size()));
- frame_surfaces.emplace_back(std::move(surface));
- }
- }
-
- // Finish recording SkPictures.
- {
- TRACE_EVENT0("flutter", "FinishRecordingPictures");
-
- for (const auto& surface_index : frame_surface_indices) {
- const auto& layer = frame_layers_.find(surface_index.first);
- FML_CHECK(layer != frame_layers_.end());
- layer->second.picture =
- layer->second.recorder->finishRecordingAsPicture();
- FML_CHECK(layer->second.picture != nullptr);
- }
- }
-
- // Submit layers and platform views to Scenic in composition order.
- {
- TRACE_EVENT0("flutter", "SubmitLayers");
-
- std::unordered_map<uint64_t, size_t> scenic_rect_indices;
- size_t scenic_layer_index = 0;
- float embedded_views_height = 0.0f;
-
- // First re-scale everything according to the DPR.
- const float inv_dpr = 1.0f / frame_dpr_;
- layer_tree_node_.SetScale(inv_dpr, inv_dpr, 1.0f);
-
- bool first_layer = true;
- for (const auto& layer_id : frame_composition_order_) {
- const auto& layer = frame_layers_.find(layer_id);
- FML_CHECK(layer != frame_layers_.end());
-
- // Draw the PlatformView associated with each layer first.
- if (layer_id.has_value()) {
- FML_CHECK(layer->second.embedded_view_params.has_value());
- auto& view_params = layer->second.embedded_view_params.value();
-
- // Get the ScenicView structure corresponding to the platform view.
- auto found = scenic_views_.find(layer_id.value());
- FML_CHECK(found != scenic_views_.end());
- auto& view_holder = found->second;
-
- // Compute mutators, size, and elevation for the platform view.
- const ViewMutators view_mutators =
- ParseMutatorStack(view_params.mutatorsStack());
- const SkSize view_size = view_params.sizePoints();
- const float view_elevation =
- kScenicZElevationBetweenLayers * scenic_layer_index +
- embedded_views_height;
-
- // Verify that we're unpacking the mutators' transform matrix correctly
- // on debug builds Use built-in get method for SkMatrix to get values
- // See:
- // https://source.corp.google.com/piper///depot/google3/third_party/skia/HEAD/include/core/SkMatrix.h;l=391
-#ifdef NDEBUG
- for (int index = 0; index < 9; index++) {
- const SkScalar mutators_transform_value =
- view_mutators.total_transform.get(index);
- const SkScalar params_transform_value =
- view_params.transformMatrix().get(index);
- if (!SkScalarNearlyEqual(mutators_transform_value,
- params_transform_value, 0.0005f)) {
- FML_LOG(FATAL)
- << "Assertion failed: view_mutators.total_transform[" << index
- << "] (" << mutators_transform_value
- << ") != view_params.transformMatrix()[" << index << "] ("
- << params_transform_value
- << "). This likely means there is a bug with the "
- << "logic for parsing embedded views' transform matrices.";
- }
- }
-#endif
-
- // Set clips for the platform view.
- if (view_mutators.clips != view_holder.mutators.clips) {
- // Expand the clip_nodes array to fit any new nodes.
- while (view_holder.clip_nodes.size() < view_mutators.clips.size()) {
- view_holder.clip_nodes.emplace_back(
- scenic::EntityNode(session_->get()));
- }
- FML_CHECK(view_holder.clip_nodes.size() >=
- view_mutators.clips.size());
-
- // Adjust and re-parent all clip rects.
- for (auto& clip_node : view_holder.clip_nodes) {
- clip_node.DetachChildren();
- }
- for (size_t c = 0; c < view_mutators.clips.size(); c++) {
- const SkMatrix& clip_transform = view_mutators.clips[c].transform;
- const SkRect& clip_rect = view_mutators.clips[c].rect;
-
- view_holder.clip_nodes[c].SetTranslation(
- clip_transform.getTranslateX(), clip_transform.getTranslateY(),
- 0.f);
- view_holder.clip_nodes[c].SetScale(clip_transform.getScaleX(),
- clip_transform.getScaleY(), 1.f);
- view_holder.clip_nodes[c].SetClipPlanes(
- ClipPlanesFromRect(clip_rect));
-
- if (c != (view_mutators.clips.size() - 1)) {
- view_holder.clip_nodes[c].AddChild(view_holder.clip_nodes[c + 1]);
- } else {
- view_holder.clip_nodes[c].AddChild(view_holder.opacity_node);
- }
- }
-
- view_holder.mutators.clips = view_mutators.clips;
- }
-
- // Set transform and elevation for the platform view.
- if (view_mutators.transform != view_holder.mutators.transform ||
- view_elevation != view_holder.elevation) {
- view_holder.transform_node.SetTranslation(
- view_mutators.transform.getTranslateX(),
- view_mutators.transform.getTranslateY(), -view_elevation);
- view_holder.transform_node.SetScale(
- view_mutators.transform.getScaleX(),
- view_mutators.transform.getScaleY(), 1.f);
-
- view_holder.mutators.transform = view_mutators.transform;
- view_holder.elevation = view_elevation;
- }
-
- // Set HitTestBehavior for the platform view.
- if (view_holder.pending_hit_testable != view_holder.hit_testable) {
- view_holder.transform_node.SetHitTestBehavior(
- view_holder.pending_hit_testable
- ? fuchsia::ui::gfx::HitTestBehavior::kDefault
- : fuchsia::ui::gfx::HitTestBehavior::kSuppress);
-
- view_holder.hit_testable = view_holder.pending_hit_testable;
- }
-
- // Set opacity for the platform view.
- if (view_mutators.opacity != view_holder.mutators.opacity) {
- view_holder.opacity_node.SetOpacity(view_mutators.opacity);
-
- view_holder.mutators.opacity = view_mutators.opacity;
- }
-
- // Set size, occlusion hint, and focusable.
- if (view_size != view_holder.size ||
- view_holder.pending_occlusion_hint != view_holder.occlusion_hint ||
- view_holder.pending_focusable != view_holder.focusable) {
- view_holder.view_holder.SetViewProperties({
- .bounding_box =
- {
- .min = {.x = 0.f, .y = 0.f, .z = -1000.f},
- .max = {.x = view_size.fWidth,
- .y = view_size.fHeight,
- .z = 0.f},
- },
- .inset_from_min = {.x = view_holder.pending_occlusion_hint.fLeft,
- .y = view_holder.pending_occlusion_hint.fTop,
- .z = 0.f},
- .inset_from_max = {.x = view_holder.pending_occlusion_hint.fRight,
- .y =
- view_holder.pending_occlusion_hint.fBottom,
- .z = 0.f},
- .focus_change = view_holder.pending_focusable,
- });
-
- view_holder.size = view_size;
- view_holder.occlusion_hint = view_holder.pending_occlusion_hint;
- view_holder.focusable = view_holder.pending_focusable;
- }
-
- // Attach the ScenicView to the main scene graph.
- if (view_holder.mutators.clips.empty()) {
- layer_tree_node_.AddChild(view_holder.opacity_node);
- } else {
- layer_tree_node_.AddChild(view_holder.clip_nodes[0]);
- }
-
- // Account for the ScenicView's height when positioning the next layer.
- embedded_views_height += kScenicZElevationForPlatformView;
- }
-
- // Acquire the surface associated with the layer.
- SurfaceProducerSurface* surface_for_layer = nullptr;
- if (layer->second.canvas_spy->DidDrawIntoCanvas()) {
- const auto& surface_index = frame_surface_indices.find(layer_id);
- if (surface_index != frame_surface_indices.end()) {
- FML_CHECK(surface_index->second < frame_surfaces.size());
- surface_for_layer = frame_surfaces[surface_index->second].get();
- FML_CHECK(surface_for_layer != nullptr);
- } else {
- const std::string layer_id_str =
- layer_id.has_value() ? std::to_string(layer_id.value())
- : "Background";
- FML_LOG(ERROR) << "Missing surface for layer " << layer_id_str
- << "; skipping scene graph add of layer.";
- FML_DCHECK(false);
- }
- }
-
- // Draw the layer if we acquired a surface for it successfully.
- if (surface_for_layer != nullptr) {
- // Create a new layer if needed for the surface.
- FML_CHECK(scenic_layer_index <= scenic_layers_.size());
- if (scenic_layer_index == scenic_layers_.size()) {
- ScenicLayer new_layer{
- .layer_node = scenic::EntityNode(session_->get()),
- .image =
- ScenicImage{
- .shape_node = scenic::ShapeNode(session_->get()),
- .material = scenic::Material(session_->get()),
- },
- // We'll set hit regions later.
- .hit_regions = {},
- };
- new_layer.layer_node.SetLabel("Flutter::Layer");
- new_layer.layer_node.AddChild(new_layer.image.shape_node);
- new_layer.image.shape_node.SetMaterial(new_layer.image.material);
- scenic_layers_.emplace_back(std::move(new_layer));
- }
-
- // Compute a hash and index for the rect.
- const uint64_t rect_hash =
- (static_cast<uint64_t>(layer->second.surface_size.width()) << 32) +
- layer->second.surface_size.height();
- size_t rect_index = 0;
- auto found_index = scenic_rect_indices.find(rect_hash);
- if (found_index == scenic_rect_indices.end()) {
- scenic_rect_indices.emplace(std::make_pair(rect_hash, 0));
- } else {
- rect_index = found_index->second + 1;
- scenic_rect_indices[rect_hash] = rect_index;
- }
-
- // Create a new rect if needed for the surface.
- auto found_rects = scenic_rects_.find(rect_hash);
- if (found_rects == scenic_rects_.end()) {
- auto [emplaced_rects, success] = scenic_rects_.emplace(
- std::make_pair(rect_hash, std::vector<scenic::Rectangle>()));
- FML_CHECK(success);
-
- found_rects = std::move(emplaced_rects);
- }
- FML_CHECK(rect_index <= found_rects->second.size());
- if (rect_index == found_rects->second.size()) {
- found_rects->second.emplace_back(scenic::Rectangle(
- session_->get(), layer->second.surface_size.width(),
- layer->second.surface_size.height()));
- }
-
- // Set layer shape and texture.
- // Scenic currently lacks an API to enable rendering of alpha channel;
- // Flutter Embedder also lacks an API to detect if a layer has alpha or
- // not. Alpha channels are only rendered if there is a OpacityNode
- // higher in the tree with opacity != 1. For now, assume any layer
- // beyond the first has alpha and clamp to a infinitesimally smaller
- // value than 1. The first layer retains an opacity of 1 to avoid
- // blending with anything underneath.
- //
- // This does not cause visual problems in practice, but probably has
- // performance implications.
- const SkAlpha layer_opacity =
- first_layer ? kBackgroundLayerOpacity : kOverlayLayerOpacity;
- const float layer_elevation =
- kScenicZElevationBetweenLayers * scenic_layer_index +
- embedded_views_height;
- auto& scenic_layer = scenic_layers_[scenic_layer_index];
- auto& scenic_rect = found_rects->second[rect_index];
- auto& image = scenic_layer.image;
- image.shape_node.SetLabel("Flutter::Layer::Image");
- image.shape_node.SetShape(scenic_rect);
- image.shape_node.SetTranslation(
- layer->second.surface_size.width() * 0.5f,
- layer->second.surface_size.height() * 0.5f, -layer_elevation);
- image.material.SetColor(SK_AlphaOPAQUE, SK_AlphaOPAQUE, SK_AlphaOPAQUE,
- layer_opacity);
- image.material.SetTexture(surface_for_layer->GetImageId());
-
- // We'll set hit regions expliclty on a separate ShapeNode, so the image
- // itself should be unhittable and semantically invisible.
- image.shape_node.SetHitTestBehavior(
- fuchsia::ui::gfx::HitTestBehavior::kSuppress);
- image.shape_node.SetSemanticVisibility(false);
-
- // Attach the ScenicLayer to the main scene graph.
- layer_tree_node_.AddChild(scenic_layer.layer_node);
-
- // Compute the set of non-overlapping set of bounding boxes for the
- // painted content in this layer.
- {
- FML_CHECK(layer->second.rtree);
- std::list<SkRect> intersection_rects =
- layer->second.rtree->searchNonOverlappingDrawnRects(
- SkRect::Make(layer->second.surface_size));
-
- // SkRect joined_rect = SkRect::MakeEmpty();
- for (const SkRect& rect : intersection_rects) {
- auto paint_bounds =
- scenic::Rectangle(session_->get(), rect.width(), rect.height());
- auto hit_region = scenic::ShapeNode(session_->get());
- hit_region.SetLabel("Flutter::Layer::HitRegion");
- hit_region.SetShape(paint_bounds);
- hit_region.SetTranslation(rect.centerX(), rect.centerY(),
- -layer_elevation);
- hit_region.SetHitTestBehavior(
- fuchsia::ui::gfx::HitTestBehavior::kDefault);
- hit_region.SetSemanticVisibility(true);
-
- scenic_layer.layer_node.AddChild(hit_region);
- scenic_layer.hit_regions.push_back(std::move(hit_region));
- }
- }
- }
-
- // Reset for the next pass:
- // +The next layer will not be the first layer.
- // +Account for the current layer's height when positioning the next.
- first_layer = false;
- scenic_layer_index++;
- }
- }
-
- // Present the session to Scenic, along with surface acquire/release fencess.
- {
- TRACE_EVENT0("flutter", "SessionPresent");
-
- session_->Present();
- }
-
- // Flush pending skia operations.
- // NOTE: This operation MUST occur AFTER the `Present() ` call above. We
- // pipeline the Skia rendering work with scenic IPC, and scenic will delay
- // internally until Skia is finished. So, doing this work before calling
- // `Present()` would adversely affect performance.
- {
- TRACE_EVENT0("flutter", "RasterizeSurfaces");
-
- for (const auto& surface_index : frame_surface_indices) {
- TRACE_EVENT0("flutter", "RasterizeSurface");
-
- FML_CHECK(surface_index.second < frame_surfaces.size());
- SurfaceProducerSurface* surface =
- frame_surfaces[surface_index.second].get();
- FML_CHECK(surface != nullptr);
-
- sk_sp<SkSurface> sk_surface = surface->GetSkiaSurface();
- FML_CHECK(sk_surface != nullptr);
- FML_CHECK(SkISize::Make(sk_surface->width(), sk_surface->height()) ==
- frame_size_);
- SkCanvas* canvas = sk_surface->getCanvas();
- FML_CHECK(canvas != nullptr);
-
- const auto& layer = frame_layers_.find(surface_index.first);
- FML_CHECK(layer != frame_layers_.end());
-
- canvas->setMatrix(SkMatrix::I());
- canvas->clear(SK_ColorTRANSPARENT);
- canvas->drawPicture(layer->second.picture);
- if (GrDirectContext* direct_context =
- GrAsDirectContext(canvas->recordingContext())) {
- direct_context->flushAndSubmit();
- }
- }
- }
-
- // Flush deferred Skia work and inform Scenic that render targets are ready.
- {
- TRACE_EVENT0("flutter", "PresentSurfaces");
-
- surface_producer_->SubmitSurfaces(std::move(frame_surfaces));
- }
-
- // Submit the underlying render-backend-specific frame for processing.
- frame->Submit();
-}
-
-void GfxExternalViewEmbedder::EnableWireframe(bool enable) {
- session_->get()->Enqueue(
- scenic::NewSetEnableDebugViewBoundsCmd(root_view_.id(), enable));
- session_->Present();
-}
-
-void GfxExternalViewEmbedder::CreateView(int64_t view_id,
- ViewCallback on_view_created,
- GfxViewIdCallback on_view_bound) {
- FML_CHECK(scenic_views_.find(view_id) == scenic_views_.end());
-
- ScenicView new_view = {
- .opacity_node = scenic::OpacityNodeHACK(session_->get()),
- .transform_node = scenic::EntityNode(session_->get()),
- .view_holder = scenic::ViewHolder(
- session_->get(),
- scenic::ToViewHolderToken(zx::eventpair((zx_handle_t)view_id)),
- "Flutter::PlatformView"),
- };
- on_view_created();
- on_view_bound(new_view.view_holder.id());
-
- new_view.opacity_node.SetLabel("Flutter::PlatformView::OpacityMutator");
- new_view.opacity_node.AddChild(new_view.transform_node);
- new_view.transform_node.SetLabel("Flutter::PlatformView::TransformMutator");
- new_view.transform_node.SetTranslation(0.f, 0.f,
- -kScenicZElevationBetweenLayers);
- new_view.transform_node.Attach(new_view.view_holder);
-
- scenic_views_.emplace(std::make_pair(view_id, std::move(new_view)));
-}
-
-void GfxExternalViewEmbedder::DestroyView(int64_t view_id,
- GfxViewIdCallback on_view_unbound) {
- auto scenic_view = scenic_views_.find(view_id);
- FML_CHECK(scenic_view != scenic_views_.end());
- scenic::ResourceId resource_id = scenic_view->second.view_holder.id();
-
- scenic_views_.erase(scenic_view);
- on_view_unbound(resource_id);
-}
-
-void GfxExternalViewEmbedder::SetViewProperties(int64_t view_id,
- const SkRect& occlusion_hint,
- bool hit_testable,
- bool focusable) {
- auto found = scenic_views_.find(view_id);
- FML_CHECK(found != scenic_views_.end());
- auto& view_holder = found->second;
-
- view_holder.pending_occlusion_hint = occlusion_hint;
- view_holder.pending_hit_testable = hit_testable;
- view_holder.pending_focusable = focusable;
-}
-
-void GfxExternalViewEmbedder::Reset() {
- frame_layers_.clear();
- frame_composition_order_.clear();
- frame_size_ = SkISize::Make(0, 0);
- frame_dpr_ = 1.f;
-
- // Detach the root node to prepare for the next frame.
- layer_tree_node_.DetachChildren();
-
- // Clear images on all layers so they aren't cached unnecessarily.
- for (auto& layer : scenic_layers_) {
- layer.image.material.SetTexture(0);
-
- // Detach hit regions; otherwise, they may persist across frames
- // incorrectly.
- for (auto& hit_region : layer.hit_regions) {
- hit_region.Detach();
- }
-
- // Remove cached hit regions so that we don't recreate stale ones.
- layer.hit_regions.clear();
- }
-}
-
-} // namespace flutter_runner
diff --git a/shell/platform/fuchsia/flutter/gfx_external_view_embedder.h b/shell/platform/fuchsia/flutter/gfx_external_view_embedder.h
deleted file mode 100644
index 378fdf2..0000000
--- a/shell/platform/fuchsia/flutter/gfx_external_view_embedder.h
+++ /dev/null
@@ -1,238 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_GFX_EXTERNAL_VIEW_EMBEDDER_H_
-#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_GFX_EXTERNAL_VIEW_EMBEDDER_H_
-
-#include <fuchsia/ui/views/cpp/fidl.h>
-#include <lib/ui/scenic/cpp/id.h>
-#include <lib/ui/scenic/cpp/resources.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
-
-#include <cstdint> // For uint32_t & uint64_t
-#include <memory>
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-#include "flutter/flow/embedded_views.h"
-#include "flutter/fml/logging.h"
-#include "flutter/fml/macros.h"
-#include "flutter/shell/platform/fuchsia/flutter/canvas_spy.h"
-#include "flutter/shell/platform/fuchsia/flutter/rtree.h"
-#include "third_party/skia/include/core/SkCanvas.h"
-#include "third_party/skia/include/core/SkPictureRecorder.h"
-#include "third_party/skia/include/core/SkPoint.h"
-#include "third_party/skia/include/core/SkRect.h"
-#include "third_party/skia/include/core/SkSize.h"
-#include "third_party/skia/include/gpu/GrDirectContext.h"
-
-#include "gfx_session_connection.h"
-#include "surface_producer.h"
-
-namespace flutter_runner {
-
-using ViewCallback = std::function<void()>;
-using GfxViewIdCallback = std::function<void(scenic::ResourceId)>;
-
-// This struct represents a transformed clip rect.
-struct TransformedClip {
- SkMatrix transform = SkMatrix::I();
- SkRect rect = SkRect::MakeEmpty();
-
- bool operator==(const TransformedClip& other) const {
- return transform == other.transform && rect == other.rect;
- }
-};
-
-// This struct represents all the mutators that can be applied to a
-// PlatformView, unpacked from the `MutatorStack`.
-struct ViewMutators {
- std::vector<TransformedClip> clips;
- SkMatrix total_transform = SkMatrix::I();
- SkMatrix transform = SkMatrix::I();
- SkScalar opacity = 1.f;
-
- bool operator==(const ViewMutators& other) const {
- return clips == other.clips && total_transform == other.total_transform &&
- transform == other.transform && opacity == other.opacity;
- }
-};
-
-// This class orchestrates interaction with the Scenic compositor on Fuchsia. It
-// ensures that flutter content and platform view content are both rendered
-// correctly in a unified scene.
-class GfxExternalViewEmbedder final : public flutter::ExternalViewEmbedder {
- public:
- // Layer separation is as infinitesimal as possible without introducing
- // Z-fighting.
- constexpr static float kScenicZElevationBetweenLayers = 0.0001f;
- constexpr static float kScenicZElevationForPlatformView = 100.f;
- constexpr static float kScenicElevationForInputInterceptor = 500.f;
- constexpr static SkAlpha kBackgroundLayerOpacity = SK_AlphaOPAQUE;
- constexpr static SkAlpha kOverlayLayerOpacity = SK_AlphaOPAQUE - 1;
-
- GfxExternalViewEmbedder(std::string debug_label,
- fuchsia::ui::views::ViewToken view_token,
- scenic::ViewRefPair view_ref_pair,
- std::shared_ptr<GfxSessionConnection> session,
- std::shared_ptr<SurfaceProducer> surface_producer,
- bool intercept_all_input = false);
- ~GfxExternalViewEmbedder();
-
- // |ExternalViewEmbedder|
- flutter::DlCanvas* GetRootCanvas() override;
-
- // |ExternalViewEmbedder|
- void PrerollCompositeEmbeddedView(
- int64_t view_id,
- std::unique_ptr<flutter::EmbeddedViewParams> params) override;
-
- // |ExternalViewEmbedder|
- flutter::DlCanvas* CompositeEmbeddedView(int64_t view_id) override;
-
- // |ExternalViewEmbedder|
- flutter::PostPrerollResult PostPrerollAction(
- fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger) override;
-
- // |ExternalViewEmbedder|
- void BeginFrame(
- SkISize frame_size,
- GrDirectContext* context,
- double device_pixel_ratio,
- fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger) override;
-
- // |ExternalViewEmbedder|
- void EndFrame(
- bool should_resubmit_frame,
- fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger) override;
-
- // |ExternalViewEmbedder|
- void SubmitFrame(GrDirectContext* context,
- const std::shared_ptr<impeller::AiksContext>& aiks_context,
- std::unique_ptr<flutter::SurfaceFrame> frame) override;
-
- // |ExternalViewEmbedder|
- void CancelFrame() override { Reset(); }
-
- // |ExternalViewEmbedder|
- bool SupportsDynamicThreadMerging() override { return false; }
-
- // View manipulation.
- // |SetViewProperties| doesn't manipulate the view directly -- it sets pending
- // properties for the next |UpdateView| call.
- void EnableWireframe(bool enable);
- void CreateView(int64_t view_id,
- ViewCallback on_view_created,
- GfxViewIdCallback on_view_bound);
- void DestroyView(int64_t view_id, GfxViewIdCallback on_view_unbound);
- void SetViewProperties(int64_t view_id,
- const SkRect& occlusion_hint,
- bool hit_testable,
- bool focusable);
-
- private:
- void Reset(); // Reset state for a new frame.
-
- struct EmbedderLayer {
- EmbedderLayer(const SkISize& frame_size,
- std::optional<flutter::EmbeddedViewParams> view_params,
- flutter::RTreeFactory rtree_factory)
- : rtree(rtree_factory.getInstance()),
- embedded_view_params(std::move(view_params)),
- recorder(std::make_unique<SkPictureRecorder>()),
- canvas_spy(std::make_unique<flutter::CanvasSpy>(
- recorder->beginRecording(SkRect::Make(frame_size),
- &rtree_factory))),
- surface_size(frame_size),
- picture(nullptr) {}
-
- // Records paint operations applied to this layer's `SkCanvas`.
- // These records are used to determine which portions of this layer
- // contain content. The embedder propagates this information to scenic, so
- // that scenic can accurately decide which portions of this layer may
- // interact with input.
- sk_sp<flutter::RTree> rtree;
-
- std::optional<flutter::EmbeddedViewParams> embedded_view_params;
- std::unique_ptr<SkPictureRecorder> recorder;
- // TODO(cyanglaz: use DlOpSpy instead.
- // https://github.com/flutter/flutter/issues/123805
- std::unique_ptr<flutter::CanvasSpy> canvas_spy;
- SkISize surface_size;
- sk_sp<SkPicture> picture;
- };
- using EmbedderLayerId = std::optional<uint32_t>;
- constexpr static EmbedderLayerId kRootLayerId = EmbedderLayerId{};
-
- struct ScenicView {
- std::vector<scenic::EntityNode> clip_nodes;
- scenic::OpacityNodeHACK opacity_node;
- scenic::EntityNode transform_node;
- scenic::ViewHolder view_holder;
-
- ViewMutators mutators;
- float elevation = 0.f;
-
- SkSize size = SkSize::MakeEmpty();
- SkRect occlusion_hint = SkRect::MakeEmpty();
- SkRect pending_occlusion_hint = SkRect::MakeEmpty();
- bool hit_testable = true;
- bool pending_hit_testable = true;
- bool focusable = true;
- bool pending_focusable = true;
- };
-
- // GFX resources required to render a composited flutter layer (i.e. an
- // SkPicture).
- struct ScenicImage {
- scenic::ShapeNode shape_node;
- scenic::Material material;
- };
-
- // All resources required to represent a flutter layer in the GFX scene
- // graph. The structure of the subgraph for a particular layer is:
- //
- // layer_node
- // / \
- // image node hit regions (zero or more)
- //
- // NOTE: `hit_regions` must be cleared before submitting each new frame;
- // otherwise, we will report stale hittable geometry to scenic.
- struct ScenicLayer {
- // Root of the subtree containing the scenic resources for this layer.
- scenic::EntityNode layer_node;
-
- // Scenic resources used to render this layer's image.
- ScenicImage image;
-
- // Scenic resources that specify which parts of this layer are responsive
- // to input.
- std::vector<scenic::ShapeNode> hit_regions;
- };
-
- std::shared_ptr<GfxSessionConnection> session_;
- std::shared_ptr<SurfaceProducer> surface_producer_;
-
- scenic::View root_view_;
- scenic::EntityNode metrics_node_;
- scenic::EntityNode layer_tree_node_;
- std::optional<scenic::ShapeNode> input_interceptor_node_;
-
- std::unordered_map<uint64_t, scenic::Rectangle> scenic_interceptor_rects_;
- std::unordered_map<uint64_t, std::vector<scenic::Rectangle>> scenic_rects_;
- std::unordered_map<int64_t, ScenicView> scenic_views_;
- std::vector<ScenicLayer> scenic_layers_;
-
- std::unordered_map<EmbedderLayerId, EmbedderLayer> frame_layers_;
- std::vector<EmbedderLayerId> frame_composition_order_;
- SkISize frame_size_ = SkISize::Make(0, 0);
- float frame_dpr_ = 1.f;
-
- FML_DISALLOW_COPY_AND_ASSIGN(GfxExternalViewEmbedder);
-};
-
-} // namespace flutter_runner
-
-#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_GFX_EXTERNAL_VIEW_EMBEDDER_H_
diff --git a/shell/platform/fuchsia/flutter/gfx_platform_view.cc b/shell/platform/fuchsia/flutter/gfx_platform_view.cc
deleted file mode 100644
index ddb0ce0..0000000
--- a/shell/platform/fuchsia/flutter/gfx_platform_view.cc
+++ /dev/null
@@ -1,370 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "gfx_platform_view.h"
-
-#include "flutter/fml/make_copyable.h"
-
-namespace flutter_runner {
-
-static constexpr int64_t kFlutterImplicitViewId = 0ll;
-
-GfxPlatformView::GfxPlatformView(
- flutter::PlatformView::Delegate& delegate,
- flutter::TaskRunners task_runners,
- fuchsia::ui::views::ViewRef view_ref,
- std::shared_ptr<flutter::ExternalViewEmbedder> external_view_embedder,
- fuchsia::ui::input::ImeServiceHandle ime_service,
- fuchsia::ui::input3::KeyboardHandle keyboard,
- fuchsia::ui::pointer::TouchSourceHandle touch_source,
- fuchsia::ui::pointer::MouseSourceHandle mouse_source,
- fuchsia::ui::views::FocuserHandle focuser,
- fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused,
- fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry,
- fidl::InterfaceRequest<fuchsia::ui::scenic::SessionListener>
- session_listener_request,
- fit::closure on_session_listener_error_callback,
- OnEnableWireframe wireframe_enabled_callback,
- OnCreateGfxView on_create_view_callback,
- OnUpdateView on_update_view_callback,
- OnDestroyGfxView on_destroy_view_callback,
- OnCreateSurface on_create_surface_callback,
- OnSemanticsNodeUpdate on_semantics_node_update_callback,
- OnRequestAnnounce on_request_announce_callback,
- OnShaderWarmup on_shader_warmup,
- AwaitVsyncCallback await_vsync_callback,
- AwaitVsyncForSecondaryCallbackCallback
- await_vsync_for_secondary_callback_callback,
- std::shared_ptr<sys::ServiceDirectory> dart_application_svc)
- : PlatformView(false /* is_flatland */,
- delegate,
- std::move(task_runners),
- std::move(view_ref),
- std::move(external_view_embedder),
- std::move(ime_service),
- std::move(keyboard),
- std::move(touch_source),
- std::move(mouse_source),
- std::move(focuser),
- std::move(view_ref_focused),
- std::move(pointerinjector_registry),
- std::move(wireframe_enabled_callback),
- std::move(on_update_view_callback),
- std::move(on_create_surface_callback),
- std::move(on_semantics_node_update_callback),
- std::move(on_request_announce_callback),
- std::move(on_shader_warmup),
- std::move(await_vsync_callback),
- std::move(await_vsync_for_secondary_callback_callback),
- std::move(dart_application_svc)),
- session_listener_binding_(this, std::move(session_listener_request)),
- session_listener_error_callback_(
- std::move(on_session_listener_error_callback)),
- on_create_view_callback_(std::move(on_create_view_callback)),
- on_destroy_view_callback_(std::move(on_destroy_view_callback)),
- weak_factory_(this) {
- session_listener_binding_.set_error_handler([](zx_status_t status) {
- FML_LOG(ERROR) << "Interface error on: SessionListener, status: " << status;
- });
-}
-
-GfxPlatformView::~GfxPlatformView() = default;
-
-void GfxPlatformView::OnScenicError(std::string error) {
- FML_LOG(ERROR) << "Session error: " << error;
- session_listener_error_callback_();
-}
-
-void GfxPlatformView::OnScenicEvent(
- std::vector<fuchsia::ui::scenic::Event> events) {
- TRACE_EVENT0("flutter", "PlatformView::OnScenicEvent");
-
- std::vector<fuchsia::ui::gfx::Event> deferred_view_events;
- bool metrics_changed = false;
- for (auto& event : events) {
- switch (event.Which()) {
- case fuchsia::ui::scenic::Event::Tag::kGfx:
- switch (event.gfx().Which()) {
- case fuchsia::ui::gfx::Event::Tag::kMetrics: {
- const fuchsia::ui::gfx::Metrics& metrics =
- event.gfx().metrics().metrics;
- const float new_view_pixel_ratio = metrics.scale_x;
- if (new_view_pixel_ratio <= 0.f) {
- FML_LOG(ERROR)
- << "Got an invalid pixel ratio from Scenic; ignoring: "
- << new_view_pixel_ratio;
- break;
- }
-
- // Avoid metrics update when possible -- it is computationally
- // expensive.
- if (view_pixel_ratio_.has_value() &&
- *view_pixel_ratio_ == new_view_pixel_ratio) {
- break;
- }
-
- view_pixel_ratio_ = new_view_pixel_ratio;
- metrics_changed = true;
- break;
- }
- case fuchsia::ui::gfx::Event::Tag::kViewPropertiesChanged: {
- const fuchsia::ui::gfx::BoundingBox& bounding_box =
- event.gfx().view_properties_changed().properties.bounding_box;
- const std::array<float, 2> new_view_size = {
- std::max(bounding_box.max.x - bounding_box.min.x, 0.0f),
- std::max(bounding_box.max.y - bounding_box.min.y, 0.0f)};
- if (new_view_size[0] <= 0.f || new_view_size[1] <= 0.f) {
- FML_LOG(ERROR)
- << "Got an invalid view size from Scenic; ignoring: "
- << new_view_size[0] << " " << new_view_size[1];
- break;
- }
-
- // Avoid metrics update when possible -- it is computationally
- // expensive.
- if (view_logical_size_.has_value() &&
- *view_logical_size_ == new_view_size) {
- break;
- }
-
- view_logical_size_ = new_view_size;
- view_logical_origin_ = {bounding_box.min.x, bounding_box.min.y};
- metrics_changed = true;
- break;
- }
- case fuchsia::ui::gfx::Event::Tag::kViewConnected:
- if (!OnChildViewConnected(
- event.gfx().view_connected().view_holder_id)) {
- deferred_view_events.push_back(std::move(event.gfx()));
- }
- break;
- case fuchsia::ui::gfx::Event::Tag::kViewDisconnected:
- if (!OnChildViewDisconnected(
- event.gfx().view_disconnected().view_holder_id)) {
- deferred_view_events.push_back(std::move(event.gfx()));
- }
- break;
- case fuchsia::ui::gfx::Event::Tag::kViewStateChanged:
- if (!OnChildViewStateChanged(
- event.gfx().view_state_changed().view_holder_id,
- event.gfx().view_state_changed().state.is_rendering)) {
- deferred_view_events.push_back(std::move(event.gfx()));
- }
- break;
- case fuchsia::ui::gfx::Event::Tag::Invalid:
- FML_DCHECK(false) << "Flutter PlatformView::OnScenicEvent: Got "
- "an invalid GFX event.";
- break;
- default:
- // We don't care about some event types, so not handling them is OK.
- break;
- }
- break;
- default: {
- break;
- }
- }
- }
-
- // If some View events went unmatched, try processing them again one more time
- // in case they arrived out-of-order with the View creation callback.
- if (!deferred_view_events.empty()) {
- task_runners_.GetPlatformTaskRunner()->PostTask(fml::MakeCopyable(
- [weak = weak_factory_.GetWeakPtr(),
- deferred_view_events = std::move(deferred_view_events)]() {
- if (!weak) {
- FML_LOG(WARNING)
- << "PlatformView already destroyed when "
- "processing deferred view events; dropping events.";
- return;
- }
-
- for (const auto& event : deferred_view_events) {
- switch (event.Which()) {
- case fuchsia::ui::gfx::Event::Tag::kViewConnected: {
- bool view_found = weak->OnChildViewConnected(
- event.view_connected().view_holder_id);
- FML_DCHECK(view_found);
- break;
- }
- case fuchsia::ui::gfx::Event::Tag::kViewDisconnected: {
- bool view_found = weak->OnChildViewDisconnected(
- event.view_disconnected().view_holder_id);
- FML_DCHECK(view_found);
- break;
- }
- case fuchsia::ui::gfx::Event::Tag::kViewStateChanged: {
- bool view_found = weak->OnChildViewStateChanged(
- event.view_state_changed().view_holder_id,
- event.view_state_changed().state.is_rendering);
- FML_DCHECK(view_found);
- break;
- }
- default:
- FML_DCHECK(false) << "Flutter PlatformView::OnScenicEvent: Got "
- "an invalid deferred GFX event.";
- break;
- }
- }
- }));
- }
-
- // If any of the viewport metrics changed, inform the engine now.
- if (view_pixel_ratio_.has_value() && view_logical_size_.has_value() &&
- metrics_changed) {
- const float pixel_ratio = *view_pixel_ratio_;
- const std::array<float, 2> logical_size = *view_logical_size_;
- flutter::ViewportMetrics metrics{
- pixel_ratio, // device_pixel_ratio
- std::round(logical_size[0] * pixel_ratio), // physical_width
- std::round(logical_size[1] * pixel_ratio), // physical_height
- 0.0f, // physical_padding_top
- 0.0f, // physical_padding_right
- 0.0f, // physical_padding_bottom
- 0.0f, // physical_padding_left
- 0.0f, // physical_view_inset_top
- 0.0f, // physical_view_inset_right
- 0.0f, // physical_view_inset_bottom
- 0.0f, // physical_view_inset_left
- 0.0f, // p_physical_system_gesture_inset_top
- 0.0f, // p_physical_system_gesture_inset_right
- 0.0f, // p_physical_system_gesture_inset_bottom
- 0.0f, // p_physical_system_gesture_inset_left,
- -1.0, // p_physical_touch_slop,
- {}, // p_physical_display_features_bounds
- {}, // p_physical_display_features_type
- {}, // p_physical_display_features_state
- 0, // pdisplay_id
- };
- SetViewportMetrics(kFlutterImplicitViewId, metrics);
- }
-}
-
-bool GfxPlatformView::OnChildViewConnected(scenic::ResourceId view_holder_id) {
- auto view_id_mapping = child_view_ids_.find(view_holder_id);
- if (view_id_mapping == child_view_ids_.end()) {
- return false;
- }
-
- std::ostringstream out;
- out << "{"
- << "\"method\":\"View.viewConnected\","
- << "\"args\":{"
- << " \"viewId\":" << view_id_mapping->second // ViewHolderToken handle
- << " }"
- << "}";
- auto call = out.str();
-
- std::unique_ptr<flutter::PlatformMessage> message =
- std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views",
- fml::MallocMapping::Copy(call.c_str(), call.size()), nullptr);
- DispatchPlatformMessage(std::move(message));
-
- return true;
-}
-
-bool GfxPlatformView::OnChildViewDisconnected(
- scenic::ResourceId view_holder_id) {
- auto view_id_mapping = child_view_ids_.find(view_holder_id);
- if (view_id_mapping == child_view_ids_.end()) {
- return false;
- }
-
- std::ostringstream out;
- out << "{"
- << "\"method\":\"View.viewDisconnected\","
- << "\"args\":{"
- << " \"viewId\":" << view_id_mapping->second // ViewHolderToken handle
- << " }"
- << "}";
- auto call = out.str();
-
- // A disconnected view cannot listen to pointer events.
- pointer_injector_delegate_->OnDestroyView(view_id_mapping->second);
-
- std::unique_ptr<flutter::PlatformMessage> message =
- std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views",
- fml::MallocMapping::Copy(call.c_str(), call.size()), nullptr);
- DispatchPlatformMessage(std::move(message));
-
- return true;
-}
-
-bool GfxPlatformView::OnChildViewStateChanged(scenic::ResourceId view_holder_id,
- bool is_rendering) {
- auto view_id_mapping = child_view_ids_.find(view_holder_id);
- if (view_id_mapping == child_view_ids_.end()) {
- return false;
- }
-
- const std::string is_rendering_str = is_rendering ? "true" : "false";
- std::ostringstream out;
- out << "{"
- << "\"method\":\"View.viewStateChanged\","
- << "\"args\":{"
- << " \"viewId\":" << view_id_mapping->second << "," // ViewHolderToken
- << " \"is_rendering\":" << is_rendering_str << "," // IsViewRendering
- << " \"state\":" << is_rendering_str // IsViewRendering
- << " }"
- << "}";
- auto call = out.str();
-
- std::unique_ptr<flutter::PlatformMessage> message =
- std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views",
- fml::MallocMapping::Copy(call.c_str(), call.size()), nullptr);
- DispatchPlatformMessage(std::move(message));
-
- return true;
-}
-
-void GfxPlatformView::OnCreateView(ViewCallback on_view_created,
- int64_t view_id_raw,
- bool hit_testable,
- bool focusable) {
- auto on_view_bound =
- [weak = weak_factory_.GetWeakPtr(),
- platform_task_runner = task_runners_.GetPlatformTaskRunner(),
- view_id = view_id_raw](scenic::ResourceId resource_id) {
- platform_task_runner->PostTask([weak, view_id, resource_id]() {
- if (!weak) {
- FML_LOG(WARNING)
- << "ViewHolder bound to PlatformView after PlatformView was "
- "destroyed; ignoring.";
- return;
- }
-
- FML_DCHECK(weak->child_view_ids_.count(resource_id) == 0);
- weak->child_view_ids_[resource_id] = view_id;
- weak->pointer_injector_delegate_->OnCreateView(view_id);
- });
- };
- on_create_view_callback_(view_id_raw, std::move(on_view_created),
- std::move(on_view_bound), hit_testable, focusable);
-}
-
-void GfxPlatformView::OnDisposeView(int64_t view_id_raw) {
- auto on_view_unbound =
- [weak = weak_factory_.GetWeakPtr(), view_id = view_id_raw,
- platform_task_runner = task_runners_.GetPlatformTaskRunner()](
- scenic::ResourceId resource_id) {
- platform_task_runner->PostTask([weak, resource_id, view_id]() {
- if (!weak) {
- FML_LOG(WARNING)
- << "ViewHolder unbound from PlatformView after PlatformView"
- "was destroyed; ignoring.";
- return;
- }
-
- FML_DCHECK(weak->child_view_ids_.count(resource_id) == 1);
- weak->child_view_ids_.erase(resource_id);
- weak->pointer_injector_delegate_->OnDestroyView(view_id);
- });
- };
- on_destroy_view_callback_(view_id_raw, std::move(on_view_unbound));
-}
-
-} // namespace flutter_runner
diff --git a/shell/platform/fuchsia/flutter/gfx_platform_view.h b/shell/platform/fuchsia/flutter/gfx_platform_view.h
deleted file mode 100644
index 2e92a41..0000000
--- a/shell/platform/fuchsia/flutter/gfx_platform_view.h
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_GFX_PLATFORM_VIEW_H_
-#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_GFX_PLATFORM_VIEW_H_
-
-#include "flutter/shell/platform/fuchsia/flutter/platform_view.h"
-
-#include <fuchsia/ui/gfx/cpp/fidl.h>
-#include <fuchsia/ui/pointer/cpp/fidl.h>
-
-#include "flutter/fml/memory/weak_ptr.h"
-#include "flutter/shell/platform/fuchsia/flutter/gfx_external_view_embedder.h"
-
-namespace flutter_runner {
-
-using OnCreateGfxView =
- fit::function<void(int64_t, ViewCallback, GfxViewIdCallback, bool, bool)>;
-using OnDestroyGfxView = fit::function<void(int64_t, GfxViewIdCallback)>;
-
-// The GfxPlatformView implements SessionListener and gets Session events but it
-// does *not* actually own the Session itself; that is owned by the
-// GfxExternalViewEmbedder on the raster thread.
-class GfxPlatformView final : public flutter_runner::PlatformView,
- private fuchsia::ui::scenic::SessionListener {
- public:
- GfxPlatformView(
- flutter::PlatformView::Delegate& delegate,
- flutter::TaskRunners task_runners,
- fuchsia::ui::views::ViewRef view_ref,
- std::shared_ptr<flutter::ExternalViewEmbedder> external_view_embedder,
- fuchsia::ui::input::ImeServiceHandle ime_service,
- fuchsia::ui::input3::KeyboardHandle keyboard,
- fuchsia::ui::pointer::TouchSourceHandle touch_source,
- fuchsia::ui::pointer::MouseSourceHandle mouse_source,
- fuchsia::ui::views::FocuserHandle focuser,
- fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused,
- fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry,
- fidl::InterfaceRequest<fuchsia::ui::scenic::SessionListener>
- session_listener_request,
- fit::closure on_session_listener_error_callback,
- OnEnableWireframe wireframe_enabled_callback,
- OnCreateGfxView on_create_view_callback,
- OnUpdateView on_update_view_callback,
- OnDestroyGfxView on_destroy_view_callback,
- OnCreateSurface on_create_surface_callback,
- OnSemanticsNodeUpdate on_semantics_node_update_callback,
- OnRequestAnnounce on_request_announce_callback,
- OnShaderWarmup on_shader_warmup,
- AwaitVsyncCallback await_vsync_callback,
- AwaitVsyncForSecondaryCallbackCallback
- await_vsync_for_secondary_callback_callback,
- std::shared_ptr<sys::ServiceDirectory> dart_application_svc);
-
- ~GfxPlatformView() override;
-
- private:
- // |fuchsia::ui::scenic::SessionListener|
- void OnScenicError(std::string error) override;
- void OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) override;
-
- // ViewHolder event handlers. These return false if the ViewHolder
- // corresponding to `view_holder_id` could not be found and the evnt was
- // unhandled.
- bool OnChildViewConnected(scenic::ResourceId view_holder_id);
- bool OnChildViewDisconnected(scenic::ResourceId view_holder_id);
- bool OnChildViewStateChanged(scenic::ResourceId view_holder_id,
- bool is_rendering);
-
- void OnCreateView(ViewCallback on_view_created,
- int64_t view_id_raw,
- bool hit_testable,
- bool focusable) override;
- void OnDisposeView(int64_t view_id_raw) override;
-
- fidl::Binding<fuchsia::ui::scenic::SessionListener> session_listener_binding_;
- fit::closure session_listener_error_callback_;
-
- // child_view_ids_ maintains a persistent mapping from Scenic ResourceId's to
- // flutter view ids, which are really zx_handle_t of ViewHolderToken.
- std::unordered_map<scenic::ResourceId, zx_handle_t> child_view_ids_;
-
- OnCreateGfxView on_create_view_callback_;
- OnDestroyGfxView on_destroy_view_callback_;
-
- fml::WeakPtrFactory<GfxPlatformView>
- weak_factory_; // Must be the last member.
-
- FML_DISALLOW_COPY_AND_ASSIGN(GfxPlatformView);
-};
-
-} // namespace flutter_runner
-
-#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_GFX_PLATFORM_VIEW_H_
diff --git a/shell/platform/fuchsia/flutter/gfx_session_connection.cc b/shell/platform/fuchsia/flutter/gfx_session_connection.cc
deleted file mode 100644
index 530b07d..0000000
--- a/shell/platform/fuchsia/flutter/gfx_session_connection.cc
+++ /dev/null
@@ -1,522 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "gfx_session_connection.h"
-
-#include <lib/async/cpp/task.h>
-#include <lib/async/cpp/time.h>
-#include <lib/async/default.h>
-#include <lib/fit/function.h>
-#include <zircon/status.h>
-
-#include "flutter/fml/make_copyable.h"
-#include "flutter/fml/time/time_point.h"
-#include "flutter/fml/trace_event.h"
-
-#include "vsync_waiter.h"
-
-namespace flutter_runner {
-namespace {
-
-fml::TimePoint Now() {
- return fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromNanoseconds(
- async::Now(async_get_default_dispatcher()).get()));
-}
-
-} // namespace
-
-// This function takes in all relevant information to determining when should
-// the next frame be scheduled. It returns a pair of (frame_start_time,
-// frame_end_time) to be passed into FireCallback().
-//
-// Importantly, there are two invariants for correct and performant scheduling
-// that this function upholds:
-// 1. Schedule the next frame at least half a vsync interval from the previous
-// one. In practice, this means that every vsync interval Flutter produces
-// exactly one frame in steady state behavior.
-// 2. Only produce frames beginning in the future.
-//
-// |vsync_offset| - the time from the next vsync that the animator should begin
-// working on the next frame. For instance if vsyncs are at 0ms, 16ms, and 33ms,
-// and the |vsync_offset| is 5ms, then frames should begin at 11ms and 28ms.
-//
-// |vsync_interval| - the interval between vsyncs. Would be 16.6ms for a 60Hz
-// display.
-//
-// |last_targeted_vsync| - the last vsync targeted, which is usually the
-// frame_end_time returned from the last invocation of this function
-//
-// |now| - the current time
-//
-// |next_vsync| - the next vsync after |now|. This can be generated using the
-// SnapToNextPhase function.
-FlutterFrameTimes GfxSessionConnection::GetTargetTimes(
- fml::TimeDelta vsync_offset,
- fml::TimeDelta vsync_interval,
- fml::TimePoint last_targeted_vsync,
- fml::TimePoint now,
- fml::TimePoint next_vsync) {
- FML_DCHECK(vsync_offset <= vsync_interval);
- FML_DCHECK(vsync_interval > fml::TimeDelta::FromMilliseconds(0));
- FML_DCHECK(now < next_vsync && next_vsync < now + vsync_interval);
-
- // This makes the math much easier below, since we live in a (mod
- // vsync_interval) world.
- if (vsync_offset == fml::TimeDelta::FromNanoseconds(0)) {
- vsync_offset = vsync_interval;
- }
-
- // Start the frame after Scenic has finished its CPU work. This is
- // accomplished using the vsync_offset.
- fml::TimeDelta vsync_offset2 = vsync_interval - vsync_offset;
- fml::TimePoint frame_start_time =
- (next_vsync - vsync_interval) + vsync_offset2;
-
- fml::TimePoint frame_end_time = next_vsync;
-
- // Advance to next available slot, keeping in mind the two invariants.
- while (frame_end_time < (last_targeted_vsync + (vsync_interval / 2)) ||
- frame_start_time < now) {
- frame_start_time = frame_start_time + vsync_interval;
- frame_end_time = frame_end_time + vsync_interval;
- }
-
- // Useful knowledge for analyzing traces.
- fml::TimePoint previous_vsync = next_vsync - vsync_interval;
- TRACE_DURATION(
- "flutter", "GfxSessionConnection::GetTargetTimes", "previous_vsync(ms)",
- previous_vsync.ToEpochDelta().ToMilliseconds(), "last_targeted(ms)",
- last_targeted_vsync.ToEpochDelta().ToMilliseconds(), "now(ms)",
- now.ToEpochDelta().ToMilliseconds(), "next_vsync(ms))",
- next_vsync.ToEpochDelta().ToMilliseconds(), "frame_start_time(ms)",
- frame_start_time.ToEpochDelta().ToMilliseconds(), "frame_end_time(ms)",
- frame_end_time.ToEpochDelta().ToMilliseconds());
-
- return {frame_start_time, frame_end_time};
-}
-
-fml::TimePoint GfxSessionConnection::CalculateNextLatchPoint(
- fml::TimePoint present_requested_time,
- fml::TimePoint now,
- fml::TimePoint last_latch_point_targeted,
- fml::TimeDelta flutter_frame_build_time,
- fml::TimeDelta vsync_interval,
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>&
- future_presentation_infos) {
- // The minimum latch point is the largest of:
- // Now
- // When we expect the Flutter work for the frame to be completed
- // The last latch point targeted
- fml::TimePoint minimum_latch_point_to_target =
- std::max(std::max(now, present_requested_time + flutter_frame_build_time),
- last_latch_point_targeted);
-
- for (auto& info : future_presentation_infos) {
- fml::TimePoint latch_point = info.first;
-
- if (latch_point >= minimum_latch_point_to_target) {
- return latch_point;
- }
- }
-
- // We could not find a suitable latch point in the list given to us from
- // Scenic, so aim for the smallest safe value.
- return minimum_latch_point_to_target;
-}
-
-/// Returns the system time at which the next frame is likely to be presented.
-///
-/// Consider the following scenarios, where in both the
-/// scenarios the result will be the same.
-///
-/// Scenario 1:
-/// presentation_interval is 2
-/// ^ ^ ^ ^ ^
-/// + + + + +
-/// 0--1--2--3--4--5--6--7--8--9--
-/// + + +
-/// | | +---------> result: next_presentation_time
-/// | v
-/// v now
-/// last_presentation_time
-///
-/// Scenario 2:
-/// presentation_interval is 2
-/// ^ ^ ^ ^ ^
-/// + + + + +
-/// 0--1--2--3--4--5--6--7--8--9--
-/// + + +
-/// | | +--------->result: next_presentation_time
-/// | |
-/// | +>now
-/// |
-/// +->last_presentation_time
-fml::TimePoint GfxSessionConnection::SnapToNextPhase(
- const fml::TimePoint now,
- const fml::TimePoint last_frame_presentation_time,
- const fml::TimeDelta presentation_interval) {
- if (presentation_interval <= fml::TimeDelta::Zero()) {
- FML_LOG(WARNING)
- << "Presentation interval must be positive. The value was: "
- << presentation_interval.ToMilliseconds() << "ms.";
- return now;
- }
-
- if (last_frame_presentation_time > now) {
- FML_LOG(WARNING)
- << "Last frame was presented in the future. Clamping to now.";
- return now + presentation_interval;
- }
-
- const fml::TimeDelta time_since_last_presentation =
- now - last_frame_presentation_time;
- // this will be the most likely scenario if we are rendering at a good
- // frame rate, short circuiting the other checks in this case.
- if (time_since_last_presentation < presentation_interval) {
- return last_frame_presentation_time + presentation_interval;
- } else {
- const int64_t num_phases_passed =
- (time_since_last_presentation / presentation_interval);
- return last_frame_presentation_time +
- (presentation_interval * (num_phases_passed + 1));
- }
-}
-
-GfxSessionConnection::GfxSessionConnection(
- std::string debug_label,
- inspect::Node inspect_node,
- fuchsia::ui::scenic::SessionHandle session,
- fml::closure session_error_callback,
- on_frame_presented_event on_frame_presented_callback,
- uint64_t max_frames_in_flight,
- fml::TimeDelta vsync_offset)
- : session_wrapper_(session.Bind(), nullptr),
- inspect_node_(std::move(inspect_node)),
- secondary_vsyncs_completed_(
- inspect_node_.CreateUint("SecondaryVsyncsCompleted", 0u)),
- vsyncs_requested_(inspect_node_.CreateUint("VsyncsRequested", 0u)),
- vsyncs_completed_(inspect_node_.CreateUint("VsyncsCompleted", 0u)),
- presents_requested_(inspect_node_.CreateUint("PresentsRequested", 0u)),
- presents_submitted_(inspect_node_.CreateUint("PresentsSubmitted", 0u)),
- presents_completed_(inspect_node_.CreateUint("PresentsCompleted", 0u)),
- last_secondary_vsync_completed_(
- inspect_node_.CreateInt("LastSecondaryVsyncCompleteTime", 0)),
- last_vsync_requested_(inspect_node_.CreateInt("LastVsyncRequestTime", 0)),
- last_vsync_completed_(
- inspect_node_.CreateInt("LastVsyncCompleteTime", 0)),
- last_frame_requested_(
- inspect_node_.CreateInt("LastPresentRequestTime", 0)),
- last_frame_presented_(
- inspect_node_.CreateInt("LastPresentSubmitTime", 0)),
- last_frame_completed_(
- inspect_node_.CreateInt("LastSubmitCompleteTime", 0)),
- inspect_dispatcher_(async_get_default_dispatcher()),
- on_frame_presented_callback_(std::move(on_frame_presented_callback)),
- kMaxFramesInFlight(max_frames_in_flight),
- vsync_offset_(vsync_offset),
- weak_factory_(this) {
- FML_CHECK(kMaxFramesInFlight > 0);
- last_presentation_time_ = Now();
-
- next_presentation_info_.set_presentation_time(0);
-
- session_wrapper_.set_error_handler([callback = session_error_callback](
- zx_status_t status) {
- FML_LOG(ERROR) << "scenic::Session error: " << zx_status_get_string(status);
- callback();
- });
-
- // Set the |fuchsia::ui::scenic::OnFramePresented()| event handler that will
- // fire every time a set of one or more frames is presented.
- session_wrapper_.set_on_frame_presented_handler(
- [weak = weak_factory_.GetWeakPtr()](
- fuchsia::scenic::scheduling::FramePresentedInfo info) {
- if (!weak) {
- return;
- }
-
- std::lock_guard<std::mutex> lock(weak->mutex_);
-
- // Update Scenic's limit for our remaining frames in flight allowed.
- size_t num_presents_handled = info.presentation_infos.size();
-
- // A frame was presented: Update our |frames_in_flight| to match the
- // updated unfinalized present requests.
- weak->frames_in_flight_ -= num_presents_handled;
-
- TRACE_DURATION("gfx", "OnFramePresented5", "frames_in_flight",
- weak->frames_in_flight_, "max_frames_in_flight",
- weak->kMaxFramesInFlight, "num_presents_handled",
- num_presents_handled);
- FML_DCHECK(weak->frames_in_flight_ >= 0);
-
- weak->last_presentation_time_ = fml::TimePoint::FromEpochDelta(
- fml::TimeDelta::FromNanoseconds(info.actual_presentation_time));
-
- // Scenic retired a given number of frames, so mark them as completed.
- // Inspect updates must run on the inspect dispatcher.
- //
- // TODO(akbiggs): It might not be necessary to post an async task for
- // the inspect updates. Read over the Inspect API's thread safety and
- // adjust accordingly.
- async::PostTask(weak->inspect_dispatcher_, [weak, now = Now(),
- num_presents_handled]() {
- if (!weak) {
- return;
- }
-
- weak->presents_completed_.Add(num_presents_handled);
- weak->last_frame_completed_.Set(now.ToEpochDelta().ToNanoseconds());
- });
-
- if (weak->fire_callback_request_pending_) {
- weak->FireCallbackMaybe();
- }
-
- if (weak->present_session_pending_) {
- weak->PresentSession();
- }
-
- // Call the client-provided callback once we are done using |info|.
- weak->on_frame_presented_callback_(std::move(info));
- });
-
- session_wrapper_.SetDebugName(debug_label);
-
- // Get information to finish initialization and only then allow Present()s.
- session_wrapper_.RequestPresentationTimes(
- /*requested_prediction_span=*/0,
- [weak = weak_factory_.GetWeakPtr()](
- fuchsia::scenic::scheduling::FuturePresentationTimes info) {
- if (!weak) {
- return;
- }
-
- std::lock_guard<std::mutex> lock(weak->mutex_);
-
- weak->next_presentation_info_ = UpdatePresentationInfo(
- std::move(info), weak->next_presentation_info_);
-
- weak->initialized_ = true;
-
- weak->PresentSession();
- });
- FML_LOG(INFO) << "Flutter GfxSessionConnection: Set vsync_offset to "
- << vsync_offset_.ToMicroseconds() << "us";
-}
-
-GfxSessionConnection::~GfxSessionConnection() = default;
-
-void GfxSessionConnection::Present() {
- std::lock_guard<std::mutex> lock(mutex_);
-
- TRACE_DURATION("gfx", "GfxSessionConnection::Present", "frames_in_flight",
- frames_in_flight_, "max_frames_in_flight", kMaxFramesInFlight);
-
- TRACE_FLOW_BEGIN("gfx", "GfxSessionConnection::PresentSession",
- next_present_session_trace_id_);
- ++next_present_session_trace_id_;
-
- auto now = Now();
- present_requested_time_ = now;
-
- // Flutter is requesting a frame here, so mark it as such.
- // Inspect updates must run on the inspect dispatcher.
- async::PostTask(inspect_dispatcher_, [this, now]() {
- presents_requested_.Add(1);
- last_frame_requested_.Set(now.ToEpochDelta().ToNanoseconds());
- });
-
- // Throttle frame submission to Scenic if we already have the maximum amount
- // of frames in flight. This allows the paint tasks for this frame to execute
- // in parallel with the presentation of previous frame but still provides
- // back-pressure to prevent us from enqueuing even more work.
- if (initialized_ && frames_in_flight_ < kMaxFramesInFlight) {
- PresentSession();
- } else {
- // We should never exceed the max frames in flight.
- FML_CHECK(frames_in_flight_ <= kMaxFramesInFlight);
-
- present_session_pending_ = true;
- }
-}
-
-void GfxSessionConnection::AwaitVsync(FireCallbackCallback callback) {
- std::lock_guard<std::mutex> lock(mutex_);
- TRACE_DURATION("flutter", "GfxSessionConnection::AwaitVsync");
- fire_callback_ = callback;
-
- // Flutter is requesting a vsync here, so mark it as such.
- // Inspect updates must run on the inspect dispatcher.
- async::PostTask(inspect_dispatcher_, [this, now = Now()]() {
- vsyncs_requested_.Add(1);
- last_vsync_requested_.Set(now.ToEpochDelta().ToNanoseconds());
- });
-
- FireCallbackMaybe();
-}
-
-void GfxSessionConnection::AwaitVsyncForSecondaryCallback(
- FireCallbackCallback callback) {
- std::lock_guard<std::mutex> lock(mutex_);
- TRACE_DURATION("flutter",
- "GfxSessionConnection::AwaitVsyncForSecondaryCallback");
- fire_callback_ = callback;
-
- // Flutter is requesting a secondary vsync here, so mark it as such.
- // Inspect updates must run on the inspect dispatcher.
- async::PostTask(inspect_dispatcher_, [this, now = Now()]() {
- secondary_vsyncs_completed_.Add(1);
- last_secondary_vsync_completed_.Set(now.ToEpochDelta().ToNanoseconds());
- });
-
- FlutterFrameTimes times = GetTargetTimesHelper(/*secondary_callback=*/true);
- fire_callback_(times.frame_start, times.frame_target);
-}
-
-// Precondition: |mutex_| is held
-void GfxSessionConnection::PresentSession() {
- TRACE_DURATION("gfx", "GfxSessionConnection::PresentSession");
-
- present_session_pending_ = false;
-
- while (processed_present_session_trace_id_ < next_present_session_trace_id_) {
- TRACE_FLOW_END("gfx", "GfxSessionConnection::PresentSession",
- processed_present_session_trace_id_);
- ++processed_present_session_trace_id_;
- }
- TRACE_FLOW_BEGIN("gfx", "Session::Present", next_present_trace_id_);
- ++next_present_trace_id_;
-
- ++frames_in_flight_;
-
- fml::TimeDelta presentation_interval =
- GetCurrentVsyncInfo().presentation_interval;
-
- fml::TimePoint next_latch_point = CalculateNextLatchPoint(
- Now(), present_requested_time_, last_latch_point_targeted_,
- fml::TimeDelta::FromMicroseconds(0), // flutter_frame_build_time
- presentation_interval, future_presentation_infos_);
-
- last_latch_point_targeted_ = next_latch_point;
-
- // Flutter is presenting a frame here, so mark it as such.
- // Inspect updates must run on the inspect dispatcher.
- async::PostTask(inspect_dispatcher_, [this, now = Now()]() {
- presents_submitted_.Add(1);
- last_frame_presented_.Set(now.ToEpochDelta().ToNanoseconds());
- });
-
- session_wrapper_.Present2(
- /*requested_presentation_time=*/next_latch_point.ToEpochDelta()
- .ToNanoseconds(),
- /*requested_prediction_span=*/presentation_interval.ToNanoseconds() * 10,
- [weak = weak_factory_.GetWeakPtr()](
- fuchsia::scenic::scheduling::FuturePresentationTimes info) {
- if (!weak) {
- return;
- }
-
- std::lock_guard<std::mutex> lock(weak->mutex_);
-
- // Clear |future_presentation_infos_| and replace it with the updated
- // information.
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>().swap(
- weak->future_presentation_infos_);
-
- for (fuchsia::scenic::scheduling::PresentationInfo& presentation_info :
- info.future_presentations) {
- weak->future_presentation_infos_.push_back(
- {fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromNanoseconds(
- presentation_info.latch_point())),
- fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromNanoseconds(
- presentation_info.presentation_time()))});
- }
-
- weak->next_presentation_info_ = UpdatePresentationInfo(
- std::move(info), weak->next_presentation_info_);
- });
-}
-
-// Precondition: |mutex_| is held.
-//
-// Postcondition: Either a frame is scheduled or fire_callback_request_pending_
-// is set to true, meaning we will attempt to schedule a frame on the next
-// |OnFramePresented|.
-void GfxSessionConnection::FireCallbackMaybe() {
- TRACE_DURATION("flutter", "FireCallbackMaybe");
-
- if (frames_in_flight_ < kMaxFramesInFlight) {
- FlutterFrameTimes times =
- GetTargetTimesHelper(/*secondary_callback=*/false);
-
- last_targeted_vsync_ = times.frame_target;
- fire_callback_request_pending_ = false;
-
- // Scenic completed a vsync here, so mark it as such.
- // Inspect updates must run on the inspect dispatcher.
- async::PostTask(inspect_dispatcher_, [this, now = Now()]() {
- vsyncs_completed_.Add(1);
- last_vsync_completed_.Set(now.ToEpochDelta().ToNanoseconds());
- });
-
- fire_callback_(times.frame_start, times.frame_target);
- } else {
- fire_callback_request_pending_ = true;
- }
-}
-
-// Precondition: |mutex_| is held
-//
-// A helper function for GetTargetTimes(), since many of the fields it takes
-// have to be derived from other state.
-FlutterFrameTimes GfxSessionConnection::GetTargetTimesHelper(
- bool secondary_callback) {
- fml::TimeDelta presentation_interval =
- GetCurrentVsyncInfo().presentation_interval;
-
- fml::TimePoint next_vsync = GetCurrentVsyncInfo().presentation_time;
- fml::TimePoint now = Now();
- fml::TimePoint last_presentation_time = last_presentation_time_;
- if (next_vsync <= now) {
- next_vsync =
- SnapToNextPhase(now, last_presentation_time, presentation_interval);
- }
-
- fml::TimePoint last_targeted_vsync =
- secondary_callback ? fml::TimePoint::Min() : last_targeted_vsync_;
- return GetTargetTimes(vsync_offset_, presentation_interval,
- last_targeted_vsync, now, next_vsync);
-}
-
-fuchsia::scenic::scheduling::PresentationInfo
-GfxSessionConnection::UpdatePresentationInfo(
- fuchsia::scenic::scheduling::FuturePresentationTimes future_info,
- fuchsia::scenic::scheduling::PresentationInfo& presentation_info) {
- fuchsia::scenic::scheduling::PresentationInfo new_presentation_info;
- new_presentation_info.set_presentation_time(
- presentation_info.presentation_time());
-
- auto next_time = presentation_info.presentation_time();
- // Get the earliest vsync time that is after our recorded |presentation_time|.
- for (auto& presentation_info : future_info.future_presentations) {
- auto current_time = presentation_info.presentation_time();
-
- if (current_time > next_time) {
- new_presentation_info.set_presentation_time(current_time);
- return new_presentation_info;
- }
- }
-
- return new_presentation_info;
-}
-
-// Precondition: |mutex_| is held
-VsyncInfo GfxSessionConnection::GetCurrentVsyncInfo() const {
- return {fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromNanoseconds(
- next_presentation_info_.presentation_time())),
- kDefaultPresentationInterval};
-}
-
-} // namespace flutter_runner
diff --git a/shell/platform/fuchsia/flutter/gfx_session_connection.h b/shell/platform/fuchsia/flutter/gfx_session_connection.h
deleted file mode 100644
index 27dc1e1..0000000
--- a/shell/platform/fuchsia/flutter/gfx_session_connection.h
+++ /dev/null
@@ -1,186 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_GFX_SESSION_CONNECTION_H_
-#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_GFX_SESSION_CONNECTION_H_
-
-#include <fuchsia/scenic/scheduling/cpp/fidl.h>
-#include <fuchsia/ui/scenic/cpp/fidl.h>
-#include <lib/async/dispatcher.h>
-#include <lib/fidl/cpp/interface_handle.h>
-#include <lib/inspect/cpp/inspect.h>
-#include <lib/ui/scenic/cpp/session.h>
-
-#include "flutter/fml/closure.h"
-#include "flutter/fml/macros.h"
-
-#include "fml/time/time_delta.h"
-#include "vsync_waiter.h"
-
-#include <mutex>
-
-namespace flutter_runner {
-
-using on_frame_presented_event =
- std::function<void(fuchsia::scenic::scheduling::FramePresentedInfo)>;
-
-struct FlutterFrameTimes {
- fml::TimePoint frame_start;
- fml::TimePoint frame_target;
-};
-
-struct VsyncInfo {
- fml::TimePoint presentation_time;
- fml::TimeDelta presentation_interval;
-};
-
-// Assume a 60hz refresh rate before we have enough past
-// |fuchsia::scenic::scheduling::PresentationInfo|s to calculate it ourselves.
-static constexpr fml::TimeDelta kDefaultPresentationInterval =
- fml::TimeDelta::FromSecondsF(1.0 / 60.0);
-
-// The component residing on the raster thread that is responsible for
-// maintaining the Scenic session connection and presenting node updates.
-class GfxSessionConnection final {
- public:
- static FlutterFrameTimes GetTargetTimes(fml::TimeDelta vsync_offset,
- fml::TimeDelta vsync_interval,
- fml::TimePoint last_targeted_vsync,
- fml::TimePoint now,
- fml::TimePoint next_vsync);
-
- static fml::TimePoint CalculateNextLatchPoint(
- fml::TimePoint present_requested_time,
- fml::TimePoint now,
- fml::TimePoint last_latch_point_targeted,
- fml::TimeDelta flutter_frame_build_time,
- fml::TimeDelta vsync_interval,
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>&
- future_presentation_infos);
-
- static fml::TimePoint SnapToNextPhase(
- const fml::TimePoint now,
- const fml::TimePoint last_frame_presentation_time,
- const fml::TimeDelta presentation_interval);
-
- // Update the next Vsync info to |next_presentation_info_|. This is expected
- // to be called in |scenic::Session::Present2| immedaite callbacks with the
- // presentation info provided by Scenic. Only the next vsync
- // information will be saved (in order to handle edge cases involving
- // multiple Scenic sessions in the same process). This function is safe to
- // call from any thread.
- static fuchsia::scenic::scheduling::PresentationInfo UpdatePresentationInfo(
- fuchsia::scenic::scheduling::FuturePresentationTimes future_info,
- fuchsia::scenic::scheduling::PresentationInfo& presentation_info);
-
- GfxSessionConnection(std::string debug_label,
- inspect::Node inspect_node,
- fuchsia::ui::scenic::SessionHandle session,
- fml::closure session_error_callback,
- on_frame_presented_event on_frame_presented_callback,
- uint64_t max_frames_in_flight,
- fml::TimeDelta vsync_offset);
-
- ~GfxSessionConnection();
-
- scenic::Session* get() { return &session_wrapper_; }
-
- // Call to request that the all enqueued Session ops since the last |Present|
- // be sent to Scenic.
- void Present();
-
- // Used to implement VsyncWaiter functionality.
- void AwaitVsync(FireCallbackCallback callback);
- void AwaitVsyncForSecondaryCallback(FireCallbackCallback callback);
-
- private:
- void PresentSession();
-
- void FireCallbackMaybe();
-
- FlutterFrameTimes GetTargetTimesHelper(bool secondary_callback);
- VsyncInfo GetCurrentVsyncInfo() const;
-
- scenic::Session session_wrapper_;
-
- inspect::Node inspect_node_;
- inspect::UintProperty secondary_vsyncs_completed_;
- inspect::UintProperty vsyncs_requested_;
- inspect::UintProperty vsyncs_completed_;
- inspect::UintProperty presents_requested_;
- inspect::UintProperty presents_submitted_;
- inspect::UintProperty presents_completed_;
- inspect::IntProperty last_secondary_vsync_completed_;
- inspect::IntProperty last_vsync_requested_;
- inspect::IntProperty last_vsync_completed_;
- inspect::IntProperty last_frame_requested_;
- inspect::IntProperty last_frame_presented_;
- inspect::IntProperty last_frame_completed_;
- async_dispatcher_t* inspect_dispatcher_;
-
- on_frame_presented_event on_frame_presented_callback_;
-
- fml::TimePoint last_latch_point_targeted_;
- fml::TimePoint present_requested_time_;
-
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos_ = {};
-
- bool initialized_ = false;
-
- // A flow event trace id for following |Session::Present| calls into
- // Scenic. This will be incremented each |Session::Present| call. By
- // convention, the Scenic side will also contain its own trace id that
- // begins at 0, and is incremented each |Session::Present| call.
- uint64_t next_present_trace_id_ = 0;
- uint64_t next_present_session_trace_id_ = 0;
- uint64_t processed_present_session_trace_id_ = 0;
-
- // The maximum number of frames Flutter sent to Scenic that it can have
- // outstanding at any time. This is equivalent to how many times it has
- // called Present2() before receiving an OnFramePresented() event.
- const int kMaxFramesInFlight;
-
- int frames_in_flight_ = 0;
- bool present_session_pending_ = false;
-
- // The time from vsync that the Flutter animator should begin its frames. This
- // is non-zero so that Flutter and Scenic compete less for CPU and GPU time.
- fml::TimeDelta vsync_offset_;
-
- // Variables for recording past and future vsync info, as reported by Scenic.
- fml::TimePoint last_presentation_time_;
- fuchsia::scenic::scheduling::PresentationInfo next_presentation_info_;
-
- // Flutter framework pipeline logic.
-
- // The following fields can be accessed from both the raster and UI threads,
- // so guard them with this mutex. If performance dictates, this could probably
- // be made lock-free, but it's much easier to reason about with this mutex.
- std::mutex mutex_;
-
- // This is the last Vsync we submitted as the frame_target_time to
- // FireCallback(). This value should be strictly increasing in order to
- // guarantee that animation code that relies on target vsyncs works correctly,
- // and that Flutter is not producing multiple frames in a small interval.
- fml::TimePoint last_targeted_vsync_;
-
- // This is true iff AwaitVSync() was called but we could not schedule a frame.
- bool fire_callback_request_pending_ = false;
-
- // The callback passed in from VsyncWaiter which eventually runs on the UI
- // thread.
- FireCallbackCallback fire_callback_;
-
- // Generates WeakPtrs to the instance of the class so callbacks can verify
- // that the instance is still in-scope before accessing state.
- // This must be the last field in the class.
- fml::WeakPtrFactory<GfxSessionConnection> weak_factory_;
-
- FML_DISALLOW_COPY_AND_ASSIGN(GfxSessionConnection);
-};
-
-} // namespace flutter_runner
-
-#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_GFX_SESSION_CONNECTION_H_
diff --git a/shell/platform/fuchsia/flutter/isolate_configurator.h b/shell/platform/fuchsia/flutter/isolate_configurator.h
index dc8c317..a0ed2ba 100644
--- a/shell/platform/fuchsia/flutter/isolate_configurator.h
+++ b/shell/platform/fuchsia/flutter/isolate_configurator.h
@@ -5,8 +5,8 @@
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_ISOLATE_CONFIGURATOR_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_ISOLATE_CONFIGURATOR_H_
-#include <fuchsia/ui/scenic/cpp/fidl.h>
-
+#include <lib/zx/channel.h>
+#include <lib/zx/eventpair.h>
#include "flutter/fml/macros.h"
#include "unique_fdio_ns.h"
diff --git a/shell/platform/fuchsia/flutter/platform_view.h b/shell/platform/fuchsia/flutter/platform_view.h
index 8ab5a14..2565370 100644
--- a/shell/platform/fuchsia/flutter/platform_view.h
+++ b/shell/platform/fuchsia/flutter/platform_view.h
@@ -13,7 +13,6 @@
#include <lib/fidl/cpp/binding.h>
#include <lib/fit/function.h>
#include <lib/sys/cpp/service_directory.h>
-#include <lib/ui/scenic/cpp/id.h>
#include <array>
#include <functional>
diff --git a/shell/platform/fuchsia/flutter/platform_view_unittest.cc b/shell/platform/fuchsia/flutter/platform_view_unittest.cc
deleted file mode 100644
index 34959fd..0000000
--- a/shell/platform/fuchsia/flutter/platform_view_unittest.cc
+++ /dev/null
@@ -1,1490 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "gfx_platform_view.h"
-
-#include <fuchsia/ui/gfx/cpp/fidl.h>
-#include <fuchsia/ui/input/cpp/fidl.h>
-#include <fuchsia/ui/input3/cpp/fidl.h>
-#include <fuchsia/ui/input3/cpp/fidl_test_base.h>
-#include <fuchsia/ui/scenic/cpp/fidl.h>
-#include <fuchsia/ui/views/cpp/fidl.h>
-#include <lib/async-loop/cpp/loop.h>
-#include <lib/async-loop/default.h>
-#include <lib/async/default.h>
-#include <lib/fidl/cpp/binding_set.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
-
-#include <memory>
-#include <ostream>
-#include <string>
-#include <vector>
-
-#include "flutter/flow/embedded_views.h"
-#include "flutter/lib/ui/window/platform_message.h"
-#include "flutter/lib/ui/window/pointer_data.h"
-#include "flutter/lib/ui/window/viewport_metrics.h"
-#include "flutter/shell/common/context_options.h"
-#include "flutter/shell/platform/fuchsia/flutter/gfx_platform_view.h"
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-#include "platform/assert.h"
-#include "surface.h"
-#include "task_runner_adapter.h"
-#include "tests/fakes/focuser.h"
-#include "tests/fakes/platform_message.h"
-#include "tests/fakes/touch_source.h"
-#include "tests/fakes/view_ref_focused.h"
-#include "tests/pointer_event_utility.h"
-
-namespace flutter_runner::testing {
-namespace {
-
-class MockExternalViewEmbedder : public flutter::ExternalViewEmbedder {
- public:
- flutter::DlCanvas* GetRootCanvas() override { return nullptr; }
-
- void CancelFrame() override {}
- void BeginFrame(
- SkISize frame_size,
- GrDirectContext* context,
- double device_pixel_ratio,
- fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger) override {}
-
- void SubmitFrame(GrDirectContext* context,
- const std::shared_ptr<impeller::AiksContext>& aiks_context,
- std::unique_ptr<flutter::SurfaceFrame> frame) override {}
-
- void PrerollCompositeEmbeddedView(
- int64_t view_id,
- std::unique_ptr<flutter::EmbeddedViewParams> params) override {}
-
- flutter::DlCanvas* CompositeEmbeddedView(int64_t view_id) override {
- return nullptr;
- }
-};
-
-class MockPlatformViewDelegate : public flutter::PlatformView::Delegate {
- public:
- void Reset() {
- message_ = nullptr;
- metrics_ = flutter::ViewportMetrics{};
- semantics_features_ = 0;
- semantics_enabled_ = false;
- pointer_packets_.clear();
- }
-
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewCreated(std::unique_ptr<flutter::Surface> surface) {
- ASSERT_EQ(surface_.get(), nullptr);
-
- surface_ = std::move(surface);
- }
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewDestroyed() {}
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewScheduleFrame() {}
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) {}
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewSetViewportMetrics(
- int64_t view_id,
- const flutter::ViewportMetrics& metrics) {
- metrics_ = metrics;
- }
- // |flutter::PlatformView::Delegate|
- const flutter::Settings& OnPlatformViewGetSettings() const {
- return settings_;
- }
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewDispatchPlatformMessage(
- std::unique_ptr<flutter::PlatformMessage> message) {
- message_ = std::move(message);
- }
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewDispatchPointerDataPacket(
- std::unique_ptr<flutter::PointerDataPacket> packet) {
- pointer_packets_.push_back(std::move(packet));
- }
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewDispatchSemanticsAction(int32_t id,
- flutter::SemanticsAction action,
- fml::MallocMapping args) {}
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewSetSemanticsEnabled(bool enabled) {
- semantics_enabled_ = enabled;
- }
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewSetAccessibilityFeatures(int32_t flags) {
- semantics_features_ = flags;
- }
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewRegisterTexture(
- std::shared_ptr<flutter::Texture> texture) {}
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewUnregisterTexture(int64_t texture_id) {}
- // |flutter::PlatformView::Delegate|
- void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) {}
- // |flutter::PlatformView::Delegate|
- std::unique_ptr<std::vector<std::string>> ComputePlatformViewResolvedLocale(
- const std::vector<std::string>& supported_locale_data) {
- return nullptr;
- }
- // |flutter::PlatformView::Delegate|
- void LoadDartDeferredLibrary(
- intptr_t loading_unit_id,
- std::unique_ptr<const fml::Mapping> snapshot_data,
- std::unique_ptr<const fml::Mapping> snapshot_instructions) {}
- // |flutter::PlatformView::Delegate|
- void LoadDartDeferredLibraryError(intptr_t loading_unit_id,
- const std::string error_message,
- bool transient) {}
- // |flutter::PlatformView::Delegate|
- void UpdateAssetResolverByType(
- std::unique_ptr<flutter::AssetResolver> updated_asset_resolver,
- flutter::AssetResolver::AssetResolverType type) {}
-
- flutter::Surface* surface() const { return surface_.get(); }
- flutter::PlatformMessage* message() const { return message_.get(); }
- const flutter::ViewportMetrics& metrics() const { return metrics_; }
- int32_t semantics_features() const { return semantics_features_; }
- bool semantics_enabled() const { return semantics_enabled_; }
- const std::vector<std::unique_ptr<flutter::PointerDataPacket>>&
- pointer_packets() const {
- return pointer_packets_;
- }
- std::vector<std::unique_ptr<flutter::PointerDataPacket>>
- TakePointerDataPackets() {
- auto tmp = std::move(pointer_packets_);
- pointer_packets_.clear();
- return tmp;
- }
-
- private:
- std::unique_ptr<flutter::Surface> surface_;
- std::unique_ptr<flutter::PlatformMessage> message_;
- flutter::ViewportMetrics metrics_;
- std::vector<std::unique_ptr<flutter::PointerDataPacket>> pointer_packets_;
- int32_t semantics_features_ = 0;
- bool semantics_enabled_ = false;
- flutter::Settings settings_;
-};
-
-class MockResponse : public flutter::PlatformMessageResponse {
- public:
- MOCK_METHOD1(Complete, void(std::unique_ptr<fml::Mapping> data));
- MOCK_METHOD0(CompleteEmpty, void());
-};
-
-class TestPlatformMessageResponse : public flutter::PlatformMessageResponse {
- public:
- TestPlatformMessageResponse() {}
- void Complete(std::unique_ptr<fml::Mapping> data) override {
- result_string = std::string(
- reinterpret_cast<const char*>(data->GetMapping()), data->GetSize());
- is_complete_ = true;
- }
- void CompleteEmpty() override { is_complete_ = true; }
- std::string result_string;
- FML_DISALLOW_COPY_AND_ASSIGN(TestPlatformMessageResponse);
-};
-
-class MockKeyboard : public fuchsia::ui::input3::testing::Keyboard_TestBase {
- public:
- explicit MockKeyboard(
- fidl::InterfaceRequest<fuchsia::ui::input3::Keyboard> keyboard)
- : keyboard_(this, std::move(keyboard)) {}
- ~MockKeyboard() = default;
-
- void AddListener(fuchsia::ui::views::ViewRef view_ref,
- fuchsia::ui::input3::KeyboardListenerHandle listener,
- AddListenerCallback callback) override {
- FML_CHECK(!listener_.is_bound());
-
- listener_ = listener.Bind();
- view_ref_ = std::move(view_ref);
-
- callback();
- }
-
- void NotImplemented_(const std::string& name) override { FAIL(); }
-
- fidl::Binding<fuchsia::ui::input3::Keyboard> keyboard_;
- fuchsia::ui::input3::KeyboardListenerPtr listener_{};
- fuchsia::ui::views::ViewRef view_ref_{};
-
- FML_DISALLOW_COPY_AND_ASSIGN(MockKeyboard);
-};
-
-// Used to construct partial instances of PlatformView for testing. The
-// PlatformView constructor has many parameters, not all of which need to
-// be filled out for each test. The builder allows you to initialize only
-// those that matter to your specific test. Not all builder methods are
-// provided: if you find some that are missing, feel free to add them.
-class PlatformViewBuilder {
- public:
- PlatformViewBuilder(flutter::PlatformView::Delegate& delegate,
- flutter::TaskRunners task_runners)
- : delegate_(delegate),
- task_runners_(task_runners),
- view_ref_pair_(scenic::ViewRefPair::New()) {}
-
- PlatformViewBuilder& SetExternalViewEmbedder(
- std::shared_ptr<flutter::ExternalViewEmbedder> embedder) {
- external_external_view_embedder_ = embedder;
- return *this;
- }
-
- PlatformViewBuilder& SetImeService(
- fuchsia::ui::input::ImeServiceHandle ime_service) {
- ime_service_ = std::move(ime_service);
- return *this;
- }
-
- PlatformViewBuilder& SetKeyboard(
- fuchsia::ui::input3::KeyboardHandle keyboard) {
- keyboard_ = std::move(keyboard);
- return *this;
- }
-
- PlatformViewBuilder& SetTouchSource(
- fuchsia::ui::pointer::TouchSourceHandle touch_source) {
- touch_source_ = std::move(touch_source);
- return *this;
- }
-
- PlatformViewBuilder& SetMouseSource(
- fuchsia::ui::pointer::MouseSourceHandle mouse_source) {
- mouse_source_ = std::move(mouse_source);
- return *this;
- }
-
- PlatformViewBuilder& SetFocuser(fuchsia::ui::views::FocuserHandle focuser) {
- focuser_ = std::move(focuser);
- return *this;
- }
-
- PlatformViewBuilder& SetViewRefFocused(
- fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused) {
- view_ref_focused_ = std::move(view_ref_focused);
- return *this;
- }
-
- PlatformViewBuilder& SetPointerinjectorRegistry(
- fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry) {
- pointerinjector_registry_ = std::move(pointerinjector_registry);
- return *this;
- }
-
- PlatformViewBuilder& SetSessionListenerRequest(
- fidl::InterfaceRequest<fuchsia::ui::scenic::SessionListener> request) {
- session_listener_request_ = std::move(request);
- return *this;
- }
-
- PlatformViewBuilder& SetEnableWireframeCallback(
- OnEnableWireframeCallback callback) {
- wireframe_enabled_callback_ = std::move(callback);
- return *this;
- }
-
- PlatformViewBuilder& SetCreateViewCallback(OnCreateGfxView callback) {
- on_create_view_callback_ = std::move(callback);
- return *this;
- }
-
- PlatformViewBuilder& SetUpdateViewCallback(OnUpdateView callback) {
- on_update_view_callback_ = std::move(callback);
- return *this;
- }
-
- PlatformViewBuilder& SetDestroyViewCallback(OnDestroyGfxView callback) {
- on_destroy_view_callback_ = std::move(callback);
- return *this;
- }
-
- PlatformViewBuilder& SetCreateSurfaceCallback(OnCreateSurface callback) {
- on_create_surface_callback_ = std::move(callback);
- return *this;
- }
-
- PlatformViewBuilder& SetShaderWarmupCallback(
- OnShaderWarmupCallback callback) {
- on_shader_warmup_callback_ = std::move(callback);
- return *this;
- }
-
- // Once Build is called, the instance is no longer usable.
- GfxPlatformView Build() {
- EXPECT_FALSE(std::exchange(built_, true))
- << "Build() was already called, this builder is good for one use only.";
- return GfxPlatformView(
- delegate_, task_runners_, std::move(view_ref_pair_.view_ref),
- external_external_view_embedder_, std::move(ime_service_),
- std::move(keyboard_), std::move(touch_source_),
- std::move(mouse_source_), std::move(focuser_),
- std::move(view_ref_focused_), std::move(pointerinjector_registry_),
- std::move(session_listener_request_),
- std::move(on_session_listener_error_callback_),
- std::move(wireframe_enabled_callback_),
- std::move(on_create_view_callback_),
- std::move(on_update_view_callback_),
- std::move(on_destroy_view_callback_),
- std::move(on_create_surface_callback_),
- std::move(on_semantics_node_update_callback_),
- std::move(on_request_announce_callback_),
- std::move(on_shader_warmup_callback_), [](auto...) {}, [](auto...) {},
- nullptr);
- }
-
- private:
- PlatformViewBuilder() = delete;
-
- flutter::PlatformView::Delegate& delegate_;
- flutter::TaskRunners task_runners_;
- scenic::ViewRefPair view_ref_pair_;
-
- std::shared_ptr<flutter::ExternalViewEmbedder>
- external_external_view_embedder_;
- fuchsia::ui::input::ImeServiceHandle ime_service_;
- fuchsia::ui::input3::KeyboardHandle keyboard_;
- fuchsia::ui::pointer::TouchSourceHandle touch_source_;
- fuchsia::ui::pointer::MouseSourceHandle mouse_source_;
- fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused_;
- fuchsia::ui::views::FocuserHandle focuser_;
- fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry_;
- fidl::InterfaceRequest<fuchsia::ui::scenic::SessionListener>
- session_listener_request_;
- fit::closure on_session_listener_error_callback_;
- OnEnableWireframeCallback wireframe_enabled_callback_;
- OnUpdateViewCallback on_update_view_callback_;
- OnCreateSurfaceCallback on_create_surface_callback_;
- OnSemanticsNodeUpdateCallback on_semantics_node_update_callback_;
- OnRequestAnnounceCallback on_request_announce_callback_;
- OnShaderWarmupCallback on_shader_warmup_callback_;
-
- bool built_{false};
-};
-
-std::string ToString(const fml::Mapping& mapping) {
- return std::string(mapping.GetMapping(),
- mapping.GetMapping() + mapping.GetSize());
-}
-
-// Stolen from pointer_data_packet_converter_unittests.cc.
-void UnpackPointerPacket(std::vector<flutter::PointerData>& output, // NOLINT
- std::unique_ptr<flutter::PointerDataPacket> packet) {
- for (size_t i = 0; i < packet->GetLength(); i++) {
- flutter::PointerData pointer_data = packet->GetPointerData(i);
- output.push_back(pointer_data);
- }
- packet.reset();
-}
-
-} // namespace
-
-class PlatformViewTests : public ::testing::Test {
- protected:
- PlatformViewTests() : loop_(&kAsyncLoopConfigAttachToCurrentThread) {}
-
- async_dispatcher_t* dispatcher() { return loop_.dispatcher(); }
-
- void RunLoopUntilIdle() {
- loop_.RunUntilIdle();
- loop_.ResetQuit();
- }
-
- fuchsia::ui::input3::KeyEvent MakeEvent(
- fuchsia::ui::input3::KeyEventType event_type,
- std::optional<fuchsia::ui::input3::Modifiers> modifiers,
- fuchsia::input::Key key) {
- fuchsia::ui::input3::KeyEvent event;
- event.set_timestamp(++event_timestamp_);
- event.set_type(event_type);
- if (modifiers.has_value()) {
- event.set_modifiers(modifiers.value());
- }
- event.set_key(key);
- return event;
- }
-
- private:
- async::Loop loop_;
-
- uint64_t event_timestamp_{42};
-
- FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewTests);
-};
-
-// This test makes sure that the PlatformView always completes a platform
-// message request, even for error conditions or if the request is malformed.
-TEST_F(PlatformViewTests, InvalidPlatformMessageRequest) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
-
- FakeViewRefFocused vrf;
- fidl::BindingSet<fuchsia::ui::views::ViewRefFocused> vrf_bindings;
- auto vrf_handle = vrf_bindings.AddBinding(&vrf);
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetViewRefFocused(std::move(vrf_handle))
- .Build();
-
- // Cast platform_view to its base view so we can have access to the public
- // "HandlePlatformMessage" function.
- auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
- EXPECT_TRUE(base_view);
-
- // Invalid platform channel.
- auto response1 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(response1->WithMessage(
- "flutter/invalid", "{\"method\":\"Invalid.invalidMethod\"}"));
-
- // Invalid json.
- auto response2 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(
- response2->WithMessage("flutter/platform_views", "{Invalid JSON"));
-
- // Invalid method.
- auto response3 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(response3->WithMessage(
- "flutter/platform_views", "{\"method\":\"View.focus.invalidMethod\"}"));
-
- // Missing arguments.
- auto response4 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(response4->WithMessage(
- "flutter/platform_views", "{\"method\":\"View.update\"}"));
- auto response5 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(
- response5->WithMessage("flutter/platform_views",
- "{\"method\":\"View.update\",\"args\":{"
- "\"irrelevantField\":\"irrelevantValue\"}}"));
-
- // Wrong argument types.
- auto response6 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(response6->WithMessage(
- "flutter/platform_views",
- "{\"method\":\"View.update\",\"args\":{\"viewId\":false,\"hitTestable\":"
- "123,\"focusable\":\"yes\"}}"));
-
- // Run the event loop and check our responses.
- RunLoopUntilIdle();
- response1->ExpectCompleted("");
- response2->ExpectCompleted("");
- response3->ExpectCompleted("");
- response4->ExpectCompleted("");
- response5->ExpectCompleted("");
- response6->ExpectCompleted("");
-}
-
-// This test makes sure that the PlatformView correctly returns a Surface
-// instance that can surface the provided gr_context and external_view_embedder.
-TEST_F(PlatformViewTests, CreateSurfaceTest) {
- MockPlatformViewDelegate delegate;
-
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", // label
- nullptr, // platform
- flutter_runner::CreateFMLTaskRunner(
- async_get_default_dispatcher()), // raster
- nullptr, // ui
- nullptr // io
- );
-
- // Test create surface callback function.
- sk_sp<GrDirectContext> gr_context = GrDirectContext::MakeMock(
- nullptr,
- flutter::MakeDefaultContextOptions(flutter::ContextType::kRender));
- std::shared_ptr<MockExternalViewEmbedder> external_view_embedder =
- std::make_shared<MockExternalViewEmbedder>();
- auto CreateSurfaceCallback = [&external_view_embedder, gr_context]() {
- return std::make_unique<flutter_runner::Surface>(
- "PlatformViewTest", external_view_embedder, gr_context.get());
- };
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetCreateSurfaceCallback(CreateSurfaceCallback)
- .SetExternalViewEmbedder(external_view_embedder)
- .Build();
- platform_view.NotifyCreated();
-
- RunLoopUntilIdle();
-
- EXPECT_EQ(gr_context.get(), delegate.surface()->GetContext());
- EXPECT_EQ(external_view_embedder.get(),
- platform_view.CreateExternalViewEmbedder().get());
-}
-
-// This test makes sure that the PlatformView correctly registers Scenic
-// MetricsEvents sent to it via FIDL, correctly parses the metrics it receives,
-// and calls the SetViewportMetrics callback with the appropriate parameters.
-TEST_F(PlatformViewTests, SetViewportMetrics) {
- constexpr float invalid_pixel_ratio = -0.75f;
- constexpr float valid_pixel_ratio = 0.75f;
- constexpr float invalid_max_bound = -0.75f;
- constexpr float valid_max_bound = 0.75f;
-
- MockPlatformViewDelegate delegate;
- EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics());
-
- fuchsia::ui::scenic::SessionListenerPtr session_listener;
- std::vector<fuchsia::ui::scenic::Event> events;
- flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr,
- nullptr);
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetSessionListenerRequest(session_listener.NewRequest())
- .Build();
- RunLoopUntilIdle();
- EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics());
-
- // Test updating with an invalid pixel ratio. The final metrics should be
- // unchanged.
- events.clear();
- events.emplace_back(fuchsia::ui::scenic::Event::WithGfx(
- fuchsia::ui::gfx::Event::WithMetrics(fuchsia::ui::gfx::MetricsEvent{
- .node_id = 0,
- .metrics =
- fuchsia::ui::gfx::Metrics{
- .scale_x = invalid_pixel_ratio,
- .scale_y = 1.f,
- .scale_z = 1.f,
- },
- })));
- session_listener->OnScenicEvent(std::move(events));
- RunLoopUntilIdle();
- EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics());
-
- // Test updating with an invalid size. The final metrics should be unchanged.
- events.clear();
- events.emplace_back(
- fuchsia::ui::scenic::Event::WithGfx(
- fuchsia::ui::gfx::Event::WithViewPropertiesChanged(
- fuchsia::ui::gfx::ViewPropertiesChangedEvent{
- .view_id = 0,
- .properties =
- fuchsia::ui::gfx::ViewProperties{
- .bounding_box =
- fuchsia::ui::gfx::BoundingBox{
- .min =
- fuchsia::ui::gfx::vec3{
- .x = 0.f,
- .y = 0.f,
- .z = 0.f,
- },
- .max =
- fuchsia::ui::gfx::vec3{
- .x = invalid_max_bound,
- .y = invalid_max_bound,
- .z = invalid_max_bound,
- },
- },
- },
- })));
- session_listener->OnScenicEvent(std::move(events));
- RunLoopUntilIdle();
- EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics());
-
- // Test updating the size only. The final metrics should be unchanged until
- // both pixel ratio and size are updated.
- events.clear();
- events.emplace_back(
- fuchsia::ui::scenic::Event::WithGfx(
- fuchsia::ui::gfx::Event::WithViewPropertiesChanged(
- fuchsia::ui::gfx::ViewPropertiesChangedEvent{
- .view_id = 0,
- .properties =
- fuchsia::ui::gfx::ViewProperties{
- .bounding_box =
- fuchsia::ui::gfx::BoundingBox{
- .min =
- fuchsia::ui::gfx::vec3{
- .x = 0.f,
- .y = 0.f,
- .z = 0.f,
- },
- .max =
- fuchsia::ui::gfx::vec3{
- .x = valid_max_bound,
- .y = valid_max_bound,
- .z = valid_max_bound,
- },
- },
- },
- })));
- session_listener->OnScenicEvent(std::move(events));
- RunLoopUntilIdle();
- EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics());
-
- // Test updating the pixel ratio only. The final metrics should change now.
- events.clear();
- events.emplace_back(fuchsia::ui::scenic::Event::WithGfx(
- fuchsia::ui::gfx::Event::WithMetrics(fuchsia::ui::gfx::MetricsEvent{
- .node_id = 0,
- .metrics =
- fuchsia::ui::gfx::Metrics{
- .scale_x = valid_pixel_ratio,
- .scale_y = 1.f,
- .scale_z = 1.f,
- },
- })));
- session_listener->OnScenicEvent(std::move(events));
- RunLoopUntilIdle();
- EXPECT_EQ(
- delegate.metrics(),
- flutter::ViewportMetrics(
- valid_pixel_ratio, std::round(valid_pixel_ratio * valid_max_bound),
- std::round(valid_pixel_ratio * valid_max_bound), -1.0, 0));
-}
-
-// This test makes sure that the PlatformView correctly registers semantics
-// settings changes applied to it and calls the SetSemanticsEnabled /
-// SetAccessibilityFeatures callbacks with the appropriate parameters.
-TEST_F(PlatformViewTests, ChangesAccessibilitySettings) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
-
- EXPECT_FALSE(delegate.semantics_enabled());
- EXPECT_EQ(delegate.semantics_features(), 0);
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners)).Build();
-
- RunLoopUntilIdle();
-
- platform_view.SetSemanticsEnabled(true);
-
- EXPECT_TRUE(delegate.semantics_enabled());
- EXPECT_EQ(delegate.semantics_features(),
- static_cast<int32_t>(
- flutter::AccessibilityFeatureFlag::kAccessibleNavigation));
-
- platform_view.SetSemanticsEnabled(false);
-
- EXPECT_FALSE(delegate.semantics_enabled());
- EXPECT_EQ(delegate.semantics_features(), 0);
-}
-
-// This test makes sure that the PlatformView forwards messages on the
-// "flutter/platform_views" channel for EnableWireframe.
-TEST_F(PlatformViewTests, EnableWireframeTest) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
-
- // Test wireframe callback function. If the message sent to the platform
- // view was properly handled and parsed, this function should be called,
- // setting |wireframe_enabled| to true.
- bool wireframe_enabled = false;
- auto EnableWireframeCallback = [&wireframe_enabled](bool should_enable) {
- wireframe_enabled = should_enable;
- };
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetEnableWireframeCallback(EnableWireframeCallback)
- .Build();
-
- // Cast platform_view to its base view so we can have access to the public
- // "HandlePlatformMessage" function.
- auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
- EXPECT_TRUE(base_view);
-
- // JSON for the message to be passed into the PlatformView.
- const uint8_t txt[] =
- "{"
- " \"method\":\"View.enableWireframe\","
- " \"args\": {"
- " \"enable\":true"
- " }"
- "}";
-
- std::unique_ptr<flutter::PlatformMessage> message =
- std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views", fml::MallocMapping::Copy(txt, sizeof(txt)),
- fml::RefPtr<flutter::PlatformMessageResponse>());
- base_view->HandlePlatformMessage(std::move(message));
-
- RunLoopUntilIdle();
-
- EXPECT_TRUE(wireframe_enabled);
-}
-
-// This test makes sure that the PlatformView forwards messages on the
-// "flutter/platform_views" channel for Createview.
-TEST_F(PlatformViewTests, CreateViewTest) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", // label
- flutter_runner::CreateFMLTaskRunner(
- async_get_default_dispatcher()), // platform
- nullptr, // raster
- nullptr, // ui
- nullptr // io
- );
-
- // Test wireframe callback function. If the message sent to the platform
- // view was properly handled and parsed, this function should be called,
- // setting |wireframe_enabled| to true.
- bool create_view_called = false;
- auto CreateViewCallback = [&create_view_called](
- int64_t view_id,
- flutter_runner::ViewCallback on_view_created,
- flutter_runner::GfxViewIdCallback on_view_bound,
- bool hit_testable, bool focusable) {
- create_view_called = true;
- on_view_created();
- on_view_bound(0);
- };
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetCreateViewCallback(CreateViewCallback)
- .Build();
-
- // Cast platform_view to its base view so we can have access to the public
- // "HandlePlatformMessage" function.
- auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
- EXPECT_TRUE(base_view);
-
- // JSON for the message to be passed into the PlatformView.
- const uint8_t txt[] =
- "{"
- " \"method\":\"View.create\","
- " \"args\": {"
- " \"viewId\":42,"
- " \"hitTestable\":true,"
- " \"focusable\":true"
- " }"
- "}";
-
- std::unique_ptr<flutter::PlatformMessage> message =
- std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views", fml::MallocMapping::Copy(txt, sizeof(txt)),
- fml::RefPtr<flutter::PlatformMessageResponse>());
- base_view->HandlePlatformMessage(std::move(message));
-
- RunLoopUntilIdle();
-
- EXPECT_TRUE(create_view_called);
-}
-
-// This test makes sure that the PlatformView forwards messages on the
-// "flutter/platform_views" channel for UpdateView.
-TEST_F(PlatformViewTests, UpdateViewTest) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
-
- std::optional<SkRect> occlusion_hint_for_test;
- std::optional<bool> hit_testable_for_test;
- std::optional<bool> focusable_for_test;
- auto UpdateViewCallback = [&occlusion_hint_for_test, &hit_testable_for_test,
- &focusable_for_test](
- int64_t view_id, SkRect occlusion_hint,
- bool hit_testable, bool focusable) {
- occlusion_hint_for_test = occlusion_hint;
- hit_testable_for_test = hit_testable;
- focusable_for_test = focusable;
- };
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetUpdateViewCallback(UpdateViewCallback)
- .Build();
-
- // Cast platform_view to its base view so we can have access to the public
- // "HandlePlatformMessage" function.
- auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
- EXPECT_TRUE(base_view);
-
- // Send a basic message.
- const uint8_t json[] =
- "{"
- " \"method\":\"View.update\","
- " \"args\": {"
- " \"viewId\":42,"
- " \"hitTestable\":true,"
- " \"focusable\":true"
- " }"
- "}";
- std::unique_ptr<flutter::PlatformMessage> message =
- std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views",
- fml::MallocMapping::Copy(json, sizeof(json)),
- fml::RefPtr<flutter::PlatformMessageResponse>());
- base_view->HandlePlatformMessage(std::move(message));
-
- RunLoopUntilIdle();
- ASSERT_TRUE(occlusion_hint_for_test.has_value());
- ASSERT_TRUE(hit_testable_for_test.has_value());
- ASSERT_TRUE(focusable_for_test.has_value());
- EXPECT_EQ(occlusion_hint_for_test.value(), SkRect::MakeEmpty());
- EXPECT_EQ(hit_testable_for_test.value(), true);
- EXPECT_EQ(focusable_for_test.value(), true);
-
- // Reset for the next message.
- occlusion_hint_for_test.reset();
- hit_testable_for_test.reset();
- focusable_for_test.reset();
-
- // Send another basic message.
- const uint8_t json_false[] =
- "{"
- " \"method\":\"View.update\","
- " \"args\": {"
- " \"viewId\":42,"
- " \"hitTestable\":false,"
- " \"focusable\":false"
- " }"
- "}";
- std::unique_ptr<flutter::PlatformMessage> message_false =
- std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views",
- fml::MallocMapping::Copy(json_false, sizeof(json_false)),
- fml::RefPtr<flutter::PlatformMessageResponse>());
- base_view->HandlePlatformMessage(std::move(message_false));
- RunLoopUntilIdle();
- ASSERT_TRUE(occlusion_hint_for_test.has_value());
- ASSERT_TRUE(hit_testable_for_test.has_value());
- ASSERT_TRUE(focusable_for_test.has_value());
- EXPECT_EQ(occlusion_hint_for_test.value(), SkRect::MakeEmpty());
- EXPECT_EQ(hit_testable_for_test.value(), false);
- EXPECT_EQ(focusable_for_test.value(), false);
-
- // Reset for the next message.
- occlusion_hint_for_test.reset();
- hit_testable_for_test.reset();
- focusable_for_test.reset();
-
- // Send a message including an occlusion hint.
- const uint8_t json_occlusion_hint[] =
- "{"
- " \"method\":\"View.update\","
- " \"args\": {"
- " \"viewId\":42,"
- " \"hitTestable\":true,"
- " \"focusable\":true,"
- " \"viewOcclusionHintLTRB\":[0.1,0.2,0.3,0.4]"
- " }"
- "}";
- std::unique_ptr<flutter::PlatformMessage> message_occlusion_hint =
- std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views",
- fml::MallocMapping::Copy(json_occlusion_hint,
- sizeof(json_occlusion_hint)),
- fml::RefPtr<flutter::PlatformMessageResponse>());
- base_view->HandlePlatformMessage(std::move(message_occlusion_hint));
- RunLoopUntilIdle();
- ASSERT_TRUE(occlusion_hint_for_test.has_value());
- ASSERT_TRUE(hit_testable_for_test.has_value());
- ASSERT_TRUE(focusable_for_test.has_value());
- EXPECT_EQ(occlusion_hint_for_test.value(),
- SkRect::MakeLTRB(0.1, 0.2, 0.3, 0.4));
- EXPECT_EQ(hit_testable_for_test.value(), true);
- EXPECT_EQ(focusable_for_test.value(), true);
-}
-
-// This test makes sure that the PlatformView forwards messages on the
-// "flutter/platform_views" channel for DestroyView.
-TEST_F(PlatformViewTests, DestroyViewTest) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", // label
- flutter_runner::CreateFMLTaskRunner(
- async_get_default_dispatcher()), // platform
- nullptr, // raster
- nullptr, // ui
- nullptr // io
- );
-
- // Test wireframe callback function. If the message sent to the platform
- // view was properly handled and parsed, this function should be called,
- // setting |wireframe_enabled| to true.
- bool destroy_view_called = false;
- auto DestroyViewCallback =
- [&destroy_view_called](
- int64_t view_id, flutter_runner::GfxViewIdCallback on_view_unbound) {
- destroy_view_called = true;
- on_view_unbound(0);
- };
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetDestroyViewCallback(DestroyViewCallback)
- .Build();
-
- // Cast platform_view to its base view so we can have access to the public
- // "HandlePlatformMessage" function.
- auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
- EXPECT_TRUE(base_view);
-
- // JSON for the message to be passed into the PlatformView.
- const uint8_t txt[] =
- "{"
- " \"method\":\"View.dispose\","
- " \"args\": {"
- " \"viewId\":42"
- " }"
- "}";
-
- std::unique_ptr<flutter::PlatformMessage> message =
- std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views", fml::MallocMapping::Copy(txt, sizeof(txt)),
- fml::RefPtr<flutter::PlatformMessageResponse>());
- base_view->HandlePlatformMessage(std::move(message));
-
- RunLoopUntilIdle();
-
- EXPECT_TRUE(destroy_view_called);
-}
-
-// This test makes sure that the PlatformView forwards messages on the
-// "flutter/platform_views" channel for ViewConnected, ViewDisconnected, and
-// ViewStateChanged events.
-TEST_F(PlatformViewTests, ViewEventsTest) {
- constexpr int64_t kViewId = 33;
- constexpr scenic::ResourceId kViewHolderId = 42;
- MockPlatformViewDelegate delegate;
-
- fuchsia::ui::scenic::SessionListenerPtr session_listener;
- std::vector<fuchsia::ui::scenic::Event> events;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", // label
- flutter_runner::CreateFMLTaskRunner(
- async_get_default_dispatcher()), // platform
- flutter_runner::CreateFMLTaskRunner(
- async_get_default_dispatcher()), // raster
- flutter_runner::CreateFMLTaskRunner(
- async_get_default_dispatcher()), // ui
- nullptr // io
- );
-
- auto on_create_view =
- [kViewId](int64_t view_id, flutter_runner::ViewCallback on_view_created,
- flutter_runner::GfxViewIdCallback on_view_bound,
- bool hit_testable, bool focusable) {
- ASSERT_EQ(view_id, kViewId);
- on_view_created();
- on_view_bound(kViewHolderId);
- };
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetSessionListenerRequest(session_listener.NewRequest())
- .SetCreateViewCallback(on_create_view)
- .Build();
- RunLoopUntilIdle();
- ASSERT_EQ(delegate.message(), nullptr);
-
- // Create initial view for testing.
- std::ostringstream create_view_message;
- create_view_message << "{"
- << " \"method\":\"View.create\","
- << " \"args\":{"
- << " \"viewId\":" << kViewId << ","
- << " \"hitTestable\":true,"
- << " \"focusable\":true"
- << " }"
- << "}";
- std::string create_view_call = create_view_message.str();
- static_cast<flutter::PlatformView*>(&platform_view)
- ->HandlePlatformMessage(std::make_unique<flutter::PlatformMessage>(
- "flutter/platform_views",
- fml::MallocMapping::Copy(create_view_call.c_str(),
- create_view_call.size()),
- fml::RefPtr<flutter::PlatformMessageResponse>()));
- RunLoopUntilIdle();
-
- // ViewConnected event.
- delegate.Reset();
- events.clear();
- events.emplace_back(fuchsia::ui::scenic::Event::WithGfx(
- fuchsia::ui::gfx::Event::WithViewConnected(
- fuchsia::ui::gfx::ViewConnectedEvent{
- .view_holder_id = kViewHolderId,
- })));
- session_listener->OnScenicEvent(std::move(events));
- RunLoopUntilIdle();
-
- flutter::PlatformMessage* view_connected_msg = delegate.message();
- ASSERT_NE(view_connected_msg, nullptr);
- std::ostringstream view_connected_expected_out;
- view_connected_expected_out
- << "{"
- << "\"method\":\"View.viewConnected\","
- << "\"args\":{"
- << " \"viewId\":" << kViewId // ViewHolderToken handle
- << " }"
- << "}";
- EXPECT_EQ(view_connected_expected_out.str(),
- ToString(view_connected_msg->data()));
-
- // ViewDisconnected event.
- delegate.Reset();
- events.clear();
- events.emplace_back(fuchsia::ui::scenic::Event::WithGfx(
- fuchsia::ui::gfx::Event::WithViewDisconnected(
- fuchsia::ui::gfx::ViewDisconnectedEvent{
- .view_holder_id = kViewHolderId,
- })));
- session_listener->OnScenicEvent(std::move(events));
- RunLoopUntilIdle();
-
- flutter::PlatformMessage* view_disconnected_msg = delegate.message();
- ASSERT_NE(view_disconnected_msg, nullptr);
- std::ostringstream view_disconnected_expected_out;
- view_disconnected_expected_out
- << "{"
- << "\"method\":\"View.viewDisconnected\","
- << "\"args\":{"
- << " \"viewId\":" << kViewId // ViewHolderToken handle
- << " }"
- << "}";
- EXPECT_EQ(view_disconnected_expected_out.str(),
- ToString(view_disconnected_msg->data()));
-
- // ViewStateChanged event.
- delegate.Reset();
- events.clear();
- events.emplace_back(fuchsia::ui::scenic::Event::WithGfx(
- fuchsia::ui::gfx::Event::WithViewStateChanged(
- fuchsia::ui::gfx::ViewStateChangedEvent{
- .view_holder_id = kViewHolderId,
- .state =
- fuchsia::ui::gfx::ViewState{
- .is_rendering = true,
- },
- })));
- session_listener->OnScenicEvent(std::move(events));
- RunLoopUntilIdle();
-
- flutter::PlatformMessage* view_state_changed_msg = delegate.message();
- ASSERT_NE(view_state_changed_msg, nullptr);
- std::ostringstream view_state_changed_expected_out;
- view_state_changed_expected_out
- << "{"
- << "\"method\":\"View.viewStateChanged\","
- << "\"args\":{"
- << " \"viewId\":" << kViewId << "," // ViewHolderToken
- << " \"is_rendering\":true," // IsViewRendering
- << " \"state\":true" // IsViewRendering
- << " }"
- << "}";
- EXPECT_EQ(view_state_changed_expected_out.str(),
- ToString(view_state_changed_msg->data()));
-}
-
-// This test makes sure that the PlatformView forwards messages on the
-// "flutter/platform_views" channel for View.focus.getCurrent and
-// View.focus.getNext.
-TEST_F(PlatformViewTests, GetFocusStatesTest) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
-
- FakeViewRefFocused vrf;
- fidl::BindingSet<fuchsia::ui::views::ViewRefFocused> vrf_bindings;
- auto vrf_handle = vrf_bindings.AddBinding(&vrf);
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetViewRefFocused(std::move(vrf_handle))
- .Build();
-
- // Cast platform_view to its base view so we can have access to the public
- // "HandlePlatformMessage" function.
- auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
- EXPECT_TRUE(base_view);
-
- std::vector<bool> vrf_states{false, true, true, false,
- true, false, true, true};
-
- for (std::size_t i = 0; i < vrf_states.size(); ++i) {
- // View.focus.getNext should complete with the next focus state.
- auto response1 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(response1->WithMessage(
- "flutter/platform_views", "{\"method\":\"View.focus.getNext\"}"));
- // Duplicate View.focus.getNext requests should complete empty.
- auto response2 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(response2->WithMessage(
- "flutter/platform_views", "{\"method\":\"View.focus.getNext\"}"));
-
- // Post watch events and make sure the hanging get is invoked each time.
- RunLoopUntilIdle();
- EXPECT_EQ(vrf.times_watched, i + 1);
-
- // Dispatch the next vrf event.
- vrf.ScheduleCallback(vrf_states[i]);
- RunLoopUntilIdle();
-
- // Make sure View.focus.getCurrent completes with the current focus state.
- auto response3 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(response3->WithMessage(
- "flutter/platform_views", "{\"method\":\"View.focus.getCurrent\"}"));
- // Duplicate View.focus.getCurrent are allowed.
- auto response4 = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(response4->WithMessage(
- "flutter/platform_views", "{\"method\":\"View.focus.getCurrent\"}"));
-
- // Run event loop and check our results.
- RunLoopUntilIdle();
- response1->ExpectCompleted(vrf_states[i] ? "[true]" : "[false]");
- response2->ExpectCompleted("[null]");
- response3->ExpectCompleted(vrf_states[i] ? "[true]" : "[false]");
- response4->ExpectCompleted(vrf_states[i] ? "[true]" : "[false]");
- }
-}
-
-// This test makes sure that the PlatformView forwards messages on the
-// "flutter/platform_views" channel for View.focus.request.
-TEST_F(PlatformViewTests, RequestFocusTest) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
-
- FakeFocuser focuser;
- fidl::BindingSet<fuchsia::ui::views::Focuser> focuser_bindings;
- auto focuser_handle = focuser_bindings.AddBinding(&focuser);
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetFocuser(std::move(focuser_handle))
- .Build();
-
- // Cast platform_view to its base view so we can have access to the public
- // "HandlePlatformMessage" function.
- auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
- EXPECT_TRUE(base_view);
-
- // This "Mock" ViewRef serves as the target for the RequestFocus operation.
- auto mock_view_ref_pair = scenic::ViewRefPair::New();
-
- // JSON for the message to be passed into the PlatformView.
- std::ostringstream message;
- message << "{"
- << " \"method\":\"View.focus.request\","
- << " \"args\": {"
- << " \"viewRef\":"
- << mock_view_ref_pair.view_ref.reference.get() << " }"
- << "}";
-
- // Dispatch the plaform message request.
- auto response = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(
- response->WithMessage("flutter/platform_views", message.str()));
- RunLoopUntilIdle();
-
- response->ExpectCompleted("[0]");
- EXPECT_TRUE(focuser.request_focus_called());
-}
-
-// This test makes sure that the PlatformView correctly replies with an error
-// response when a View.focus.request call fails.
-TEST_F(PlatformViewTests, RequestFocusFailTest) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
-
- FakeFocuser focuser;
- focuser.fail_request_focus();
- fidl::BindingSet<fuchsia::ui::views::Focuser> focuser_bindings;
- auto focuser_handle = focuser_bindings.AddBinding(&focuser);
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetFocuser(std::move(focuser_handle))
- .Build();
-
- // Cast platform_view to its base view so we can have access to the public
- // "HandlePlatformMessage" function.
- auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
- EXPECT_TRUE(base_view);
-
- // This "Mock" ViewRef serves as the target for the RequestFocus operation.
- auto mock_view_ref_pair = scenic::ViewRefPair::New();
-
- // JSON for the message to be passed into the PlatformView.
- std::ostringstream message;
- message << "{"
- << " \"method\":\"View.focus.request\","
- << " \"args\": {"
- << " \"viewRef\":"
- << mock_view_ref_pair.view_ref.reference.get() << " }"
- << "}";
-
- // Dispatch the plaform message request.
- auto response = FakePlatformMessageResponse::Create();
- base_view->HandlePlatformMessage(
- response->WithMessage("flutter/platform_views", message.str()));
- RunLoopUntilIdle();
-
- response->ExpectCompleted(
- "[" +
- std::to_string(
- static_cast<std::underlying_type_t<fuchsia::ui::views::Error>>(
- fuchsia::ui::views::Error::DENIED)) +
- "]");
- EXPECT_TRUE(focuser.request_focus_called());
-}
-
-// Makes sure that OnKeyEvent is dispatched as a platform message.
-TEST_F(PlatformViewTests, OnKeyEvent) {
- struct EventFlow {
- fuchsia::ui::input3::KeyEvent event;
- fuchsia::ui::input3::KeyEventStatus expected_key_event_status;
- std::string expected_platform_message;
- };
-
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
-
- fuchsia::ui::input3::KeyboardHandle keyboard_service;
- MockKeyboard keyboard(keyboard_service.NewRequest());
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetKeyboard(std::move(keyboard_service))
- .Build();
- RunLoopUntilIdle();
-
- std::vector<EventFlow> events;
- // Press A. Get 'a'.
- // The HID usage for the key A is 0x70004, or 458756.
- events.emplace_back(EventFlow{
- MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, std::nullopt,
- fuchsia::input::Key::A),
- fuchsia::ui::input3::KeyEventStatus::HANDLED,
- R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":97,"modifiers":0})",
- });
- // Release A. Get 'a' release.
- events.emplace_back(EventFlow{
- MakeEvent(fuchsia::ui::input3::KeyEventType::RELEASED, std::nullopt,
- fuchsia::input::Key::A),
- fuchsia::ui::input3::KeyEventStatus::HANDLED,
- R"({"type":"keyup","keymap":"fuchsia","hidUsage":458756,"codePoint":97,"modifiers":0})",
- });
- // Press CAPS_LOCK. Modifier now active.
- events.emplace_back(EventFlow{
- MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED,
- fuchsia::ui::input3::Modifiers::CAPS_LOCK,
- fuchsia::input::Key::CAPS_LOCK),
- fuchsia::ui::input3::KeyEventStatus::HANDLED,
- R"({"type":"keydown","keymap":"fuchsia","hidUsage":458809,"codePoint":0,"modifiers":1})",
- });
- // Press A. Get 'A'.
- events.emplace_back(EventFlow{
- MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, std::nullopt,
- fuchsia::input::Key::A),
- fuchsia::ui::input3::KeyEventStatus::HANDLED,
- R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":65,"modifiers":1})",
- });
- // Release CAPS_LOCK.
- events.emplace_back(EventFlow{
- MakeEvent(fuchsia::ui::input3::KeyEventType::RELEASED,
- fuchsia::ui::input3::Modifiers::CAPS_LOCK,
- fuchsia::input::Key::CAPS_LOCK),
- fuchsia::ui::input3::KeyEventStatus::HANDLED,
- R"({"type":"keyup","keymap":"fuchsia","hidUsage":458809,"codePoint":0,"modifiers":1})",
- });
- // Press A again. This time get 'A'.
- // CAPS_LOCK is latched active even if it was just released.
- events.emplace_back(EventFlow{
- MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, std::nullopt,
- fuchsia::input::Key::A),
- fuchsia::ui::input3::KeyEventStatus::HANDLED,
- R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":65,"modifiers":1})",
- });
-
- for (const auto& event : events) {
- fuchsia::ui::input3::KeyEvent e;
- event.event.Clone(&e);
- fuchsia::ui::input3::KeyEventStatus key_event_status{0u};
- keyboard.listener_->OnKeyEvent(
- std::move(e),
- [&key_event_status](fuchsia::ui::input3::KeyEventStatus status) {
- key_event_status = status;
- });
- RunLoopUntilIdle();
-
- ASSERT_NOTNULL(delegate.message());
- EXPECT_EQ(event.expected_platform_message,
- ToString(delegate.message()->data()));
- EXPECT_EQ(event.expected_key_event_status, key_event_status);
- }
-}
-
-TEST_F(PlatformViewTests, OnShaderWarmup) {
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners =
- flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
-
- uint64_t width = 200;
- uint64_t height = 100;
- std::vector<std::string> shaders = {"foo.skp", "bar.skp", "baz.skp"};
-
- OnShaderWarmupCallback on_shader_warmup_callback =
- [&](const std::vector<std::string>& shaders_in,
- std::function<void(uint32_t)> completion_callback, uint64_t width_in,
- uint64_t height_in) {
- ASSERT_EQ(shaders.size(), shaders_in.size());
- for (size_t i = 0; i < shaders_in.size(); i++) {
- ASSERT_EQ(shaders[i], shaders_in[i]);
- }
- ASSERT_EQ(width, width_in);
- ASSERT_EQ(height, height_in);
-
- completion_callback(shaders_in.size());
- };
-
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetShaderWarmupCallback(on_shader_warmup_callback)
- .Build();
-
- std::ostringstream shaders_array_ostream;
- shaders_array_ostream << "[ ";
- for (auto it = shaders.begin(); it != shaders.end(); ++it) {
- shaders_array_ostream << "\"" << *it << "\"";
- if (std::next(it) != shaders.end()) {
- shaders_array_ostream << ", ";
- }
- }
- shaders_array_ostream << "]";
-
- std::string shaders_array_string = shaders_array_ostream.str();
-
- // Create initial view for testing.
- std::ostringstream warmup_shaders_ostream;
- warmup_shaders_ostream << "{"
- << " \"method\":\"WarmupSkps\","
- << " \"args\":{"
- << " \"shaders\":" << shaders_array_string << ","
- << " \"width\":" << width << ","
- << " \"height\":" << height << " }"
- << "}\n";
- std::string warmup_shaders_string = warmup_shaders_ostream.str();
-
- fml::RefPtr<TestPlatformMessageResponse> response(
- new TestPlatformMessageResponse);
- static_cast<flutter::PlatformView*>(&platform_view)
- ->HandlePlatformMessage(std::make_unique<flutter::PlatformMessage>(
- "fuchsia/shader_warmup",
- fml::MallocMapping::Copy(warmup_shaders_string.c_str(),
- warmup_shaders_string.size()),
- response));
- RunLoopUntilIdle();
- ASSERT_TRUE(response->is_complete());
-
- std::ostringstream expected_result_ostream;
- expected_result_ostream << "[" << shaders.size() << "]";
- std::string expected_result_string = expected_result_ostream.str();
- EXPECT_EQ(expected_result_string, response->result_string);
-}
-
-TEST_F(PlatformViewTests, TouchSourceLogicalToPhysicalConversion) {
- constexpr std::array<std::array<float, 2>, 2> kRect = {{{0, 0}, {20, 20}}};
- constexpr std::array<float, 9> kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1};
- constexpr fuchsia::ui::pointer::TouchInteractionId kIxnOne = {
- .device_id = 0u, .pointer_id = 1u, .interaction_id = 2u};
- constexpr float valid_pixel_ratio = 2.f;
-
- MockPlatformViewDelegate delegate;
- flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr,
- nullptr);
-
- fuchsia::ui::scenic::SessionListenerPtr session_listener;
- FakeTouchSource touch_server;
- fidl::BindingSet<fuchsia::ui::pointer::TouchSource> touch_bindings;
- auto touch_handle = touch_bindings.AddBinding(&touch_server);
- flutter_runner::GfxPlatformView platform_view =
- PlatformViewBuilder(delegate, std::move(task_runners))
- .SetSessionListenerRequest(session_listener.NewRequest())
- .SetTouchSource(std::move(touch_handle))
- .Build();
- RunLoopUntilIdle();
- EXPECT_EQ(delegate.pointer_packets().size(), 0u);
-
- // Set logical-to-physical metrics and logical view size
- std::vector<fuchsia::ui::scenic::Event> scenic_events;
- scenic_events.emplace_back(fuchsia::ui::scenic::Event::WithGfx(
- fuchsia::ui::gfx::Event::WithMetrics(fuchsia::ui::gfx::MetricsEvent{
- .node_id = 0,
- .metrics =
- fuchsia::ui::gfx::Metrics{
- .scale_x = valid_pixel_ratio,
- .scale_y = valid_pixel_ratio,
- .scale_z = valid_pixel_ratio,
- },
- })));
- scenic_events.emplace_back(
- fuchsia::ui::scenic::Event::WithGfx(
- fuchsia::ui::gfx::Event::WithViewPropertiesChanged(
- fuchsia::ui::gfx::ViewPropertiesChangedEvent{
- .view_id = 0,
- .properties =
- fuchsia::ui::gfx::ViewProperties{
- .bounding_box =
- fuchsia::ui::gfx::BoundingBox{
- .min =
- fuchsia::ui::gfx::vec3{
- .x = 0.f,
- .y = 0.f,
- .z = 0.f,
- },
- .max =
- fuchsia::ui::gfx::vec3{
- .x = 20.f,
- .y = 20.f,
- .z = 20.f,
- },
- },
- },
- })));
- session_listener->OnScenicEvent(std::move(scenic_events));
- RunLoopUntilIdle();
- EXPECT_EQ(delegate.metrics(),
- flutter::ViewportMetrics(2.f, 40.f, 40.f, -1, 0));
-
- // Inject
- std::vector<fuchsia::ui::pointer::TouchEvent> events =
- TouchEventBuilder::New()
- .AddTime(/* in nanoseconds */ 1111789u)
- .AddViewParameters(kRect, kRect, kIdentity)
- .AddSample(kIxnOne, fuchsia::ui::pointer::EventPhase::ADD,
- {10.f, 10.f})
- .AddResult(
- {.interaction = kIxnOne,
- .status = fuchsia::ui::pointer::TouchInteractionStatus::GRANTED})
- .BuildAsVector();
- touch_server.ScheduleCallback(std::move(events));
- RunLoopUntilIdle();
-
- // Unpack
- std::vector<std::unique_ptr<flutter::PointerDataPacket>> packets =
- delegate.TakePointerDataPackets();
- ASSERT_EQ(packets.size(), 1u);
- std::vector<flutter::PointerData> flutter_events;
- UnpackPointerPacket(flutter_events, std::move(packets[0]));
-
- // Examine phases
- ASSERT_EQ(flutter_events.size(), 2u);
- EXPECT_EQ(flutter_events[0].change, flutter::PointerData::Change::kAdd);
- EXPECT_EQ(flutter_events[1].change, flutter::PointerData::Change::kDown);
-
- // Examine coordinates
- // With metrics defined, observe metrics ratio applied.
- EXPECT_EQ(flutter_events[0].physical_x, 20.f);
- EXPECT_EQ(flutter_events[0].physical_y, 20.f);
- EXPECT_EQ(flutter_events[1].physical_x, 20.f);
- EXPECT_EQ(flutter_events[1].physical_y, 20.f);
-}
-
-} // namespace flutter_runner::testing
diff --git a/shell/platform/fuchsia/flutter/pointer_injector_delegate_unittest.cc b/shell/platform/fuchsia/flutter/pointer_injector_delegate_unittest.cc
index 5153000..eedd2b4 100644
--- a/shell/platform/fuchsia/flutter/pointer_injector_delegate_unittest.cc
+++ b/shell/platform/fuchsia/flutter/pointer_injector_delegate_unittest.cc
@@ -9,9 +9,9 @@
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/async/cpp/task.h>
+#include <lib/zx/eventpair.h>
#include <lib/fidl/cpp/binding_set.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
#include "pointer_injector_delegate.h"
#include "tests/fakes/mock_injector_registry.h"
@@ -204,9 +204,17 @@
}
void SetUp() override {
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
- host_view_ref_ = std::move(view_ref_pair.view_ref);
+ host_view_ref_ = std::move(view_ref);
fup_RegistryHandle registry;
registry_ = std::make_unique<MockInjectorRegistry>(registry.NewRequest());
@@ -224,8 +232,17 @@
if (view_ref.has_value()) {
ref = std::move(*view_ref);
} else {
- auto view_ref_pair = scenic::ViewRefPair::New();
- ref = std::move(view_ref_pair.view_ref);
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+
+ ref = std::move(view_ref);
}
pointer_injector_delegate_->OnCreateView(view_id, std::move(ref));
}
@@ -281,7 +298,15 @@
CreateView(view_id);
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
for (size_t i = 0; i < num_events; i++) {
auto response = FakePlatformMessageResponse::Create();
@@ -299,7 +324,15 @@
CreateView(view_id);
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
for (size_t i = 0; i < num_events; i++) {
auto response = FakePlatformMessageResponse::Create();
@@ -328,7 +361,15 @@
// Inject |num_events| platform messages for |view_id_1|.
{
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
for (size_t i = 0; i < num_events; i++) {
auto response = FakePlatformMessageResponse::Create();
@@ -346,7 +387,15 @@
// Inject |num_events| platform messages for |view_id_2|.
{
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
for (size_t i = 0; i < num_events; i++) {
auto response = FakePlatformMessageResponse::Create();
@@ -376,12 +425,20 @@
auto response = FakePlatformMessageResponse::Create();
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
// Create the view.
- fuv_ViewRef view_ref;
- fidl::Clone(view_ref_pair.view_ref, &view_ref);
- CreateView(view_id, std::move(view_ref));
+ fuv_ViewRef view_ref_clone;
+ fidl::Clone(view_ref, &view_ref_clone);
+ CreateView(view_id, std::move(view_ref_clone));
// Inject a platform message.
EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage(
@@ -425,8 +482,7 @@
ASSERT_TRUE(config.has_target());
ASSERT_TRUE(config.target().is_view());
- EXPECT_EQ(ExtractKoid(config.target().view()),
- ExtractKoid(view_ref_pair.view_ref));
+ EXPECT_EQ(ExtractKoid(config.target().view()), ExtractKoid(view_ref));
ASSERT_TRUE(config.has_viewport());
ASSERT_TRUE(config.viewport().has_viewport_to_context_transform());
@@ -447,12 +503,20 @@
auto response = FakePlatformMessageResponse::Create();
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
// Create the view.
- fuv_ViewRef view_ref;
- fidl::Clone(view_ref_pair.view_ref, &view_ref);
- CreateView(view_id, std::move(view_ref));
+ fuv_ViewRef view_ref_clone;
+ fidl::Clone(view_ref, &view_ref_clone);
+ CreateView(view_id, std::move(view_ref_clone));
// Inject a platform message.
EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage(
@@ -508,7 +572,15 @@
TEST_P(PointerInjectorDelegateTest, DestroyedViewsDontGetPointerEvents) {
const uint64_t view_id = 1, num_events = 150;
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
// Create the view.
CreateView(view_id);
@@ -539,7 +611,15 @@
TEST_P(PointerInjectorDelegateTest, ViewsGetPointerEventsInFIFO) {
const uint64_t view_id = 1, num_events = 150;
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
// Create the view.
CreateView(view_id);
@@ -591,15 +671,23 @@
TEST_P(PointerInjectorDelegateTest, DeviceRetriesRegisterWhenClosed) {
const uint64_t view_id = 1;
const int pointer_id = 1;
- auto view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
auto response = FakePlatformMessageResponse::Create();
auto response_2 = FakePlatformMessageResponse::Create();
// Create the view.
- fuv_ViewRef view_ref;
- fidl::Clone(view_ref_pair.view_ref, &view_ref);
- CreateView(view_id, std::move(view_ref));
+ fuv_ViewRef view_ref_clone;
+ fidl::Clone(view_ref, &view_ref_clone);
+ CreateView(view_id, std::move(view_ref_clone));
EXPECT_TRUE(pointer_injector_delegate_->HandlePlatformMessage(
PlatformMessageBuilder()
diff --git a/shell/platform/fuchsia/flutter/software_surface.cc b/shell/platform/fuchsia/flutter/software_surface.cc
index d776cd7..4b19855 100644
--- a/shell/platform/fuchsia/flutter/software_surface.cc
+++ b/shell/platform/fuchsia/flutter/software_surface.cc
@@ -5,7 +5,6 @@
#include "software_surface.h"
#include <lib/async/default.h>
-#include <lib/ui/scenic/cpp/commands.h>
#include <zircon/rights.h>
#include <zircon/status.h>
#include <zircon/types.h>
diff --git a/shell/platform/fuchsia/flutter/software_surface.h b/shell/platform/fuchsia/flutter/software_surface.h
index b2bcee0..667f87b 100644
--- a/shell/platform/fuchsia/flutter/software_surface.h
+++ b/shell/platform/fuchsia/flutter/software_surface.h
@@ -7,8 +7,6 @@
#include <fuchsia/sysmem/cpp/fidl.h>
#include <fuchsia/ui/composition/cpp/fidl.h>
#include <lib/async/cpp/wait.h>
-#include <lib/ui/scenic/cpp/id.h>
-#include <lib/ui/scenic/cpp/resources.h>
#include <lib/zx/event.h>
#include <lib/zx/vmo.h>
diff --git a/shell/platform/fuchsia/flutter/tests/external_view_embedder_unittests.cc b/shell/platform/fuchsia/flutter/tests/external_view_embedder_unittests.cc
index a9d28b9..69f0106 100644
--- a/shell/platform/fuchsia/flutter/tests/external_view_embedder_unittests.cc
+++ b/shell/platform/fuchsia/flutter/tests/external_view_embedder_unittests.cc
@@ -10,6 +10,7 @@
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/async-testing/test_loop.h>
#include <lib/zx/event.h>
+#include <lib/zx/eventpair.h>
#include <cstdint>
#include <functional>
@@ -439,18 +440,27 @@
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher;
fuchsia::ui::views::ViewportCreationToken viewport_creation_token;
fuchsia::ui::views::ViewCreationToken view_creation_token;
- fuchsia::ui::views::ViewRef view_ref;
+ fuchsia::ui::views::ViewRef view_ref_clone;
auto view_creation_token_status = zx::channel::create(
0u, &viewport_creation_token.value, &view_creation_token.value);
ASSERT_EQ(view_creation_token_status, ZX_OK);
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ view_ref.Clone(&view_ref_clone);
ExternalViewEmbedder external_view_embedder(
std::move(view_creation_token),
fuchsia::ui::views::ViewIdentityOnCreation{
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref),
+ .view_ref = std::move(view_ref),
+ .view_ref_control = std::move(view_ref_control),
},
fuchsia::ui::composition::ViewBoundProtocols{},
parent_viewport_watcher.NewRequest(), flatland_connection(),
@@ -467,27 +477,36 @@
loop().RunUntilIdle();
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
}
TEST_F(ExternalViewEmbedderTest, SimpleScene) {
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher;
fuchsia::ui::views::ViewportCreationToken viewport_creation_token;
fuchsia::ui::views::ViewCreationToken view_creation_token;
- fuchsia::ui::views::ViewRef view_ref;
+ fuchsia::ui::views::ViewRef view_ref_clone;
auto view_creation_token_status = zx::channel::create(
0u, &viewport_creation_token.value, &view_creation_token.value);
ASSERT_EQ(view_creation_token_status, ZX_OK);
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ view_ref.Clone(&view_ref_clone);
// Create the `ExternalViewEmbedder` and pump the message loop until
// the initial scene graph is setup.
ExternalViewEmbedder external_view_embedder(
std::move(view_creation_token),
fuchsia::ui::views::ViewIdentityOnCreation{
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref),
+ .view_ref = std::move(view_ref),
+ .view_ref_control = std::move(view_ref_control),
},
fuchsia::ui::composition::ViewBoundProtocols{},
parent_viewport_watcher.NewRequest(), flatland_connection(),
@@ -498,7 +517,7 @@
loop().RunUntilIdle();
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Draw the scene. The scene graph shouldn't change yet.
const SkISize frame_size_signed = SkISize::Make(512, 512);
@@ -521,7 +540,7 @@
});
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Pump the message loop. The scene updates should propagate to flatland.
loop().RunUntilIdle();
@@ -529,7 +548,7 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref,
+ parent_viewport_watcher, viewport_creation_token, view_ref_clone,
/*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
@@ -546,20 +565,29 @@
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher;
fuchsia::ui::views::ViewportCreationToken viewport_creation_token;
fuchsia::ui::views::ViewCreationToken view_creation_token;
- fuchsia::ui::views::ViewRef view_ref;
+ fuchsia::ui::views::ViewRef view_ref_clone;
auto view_creation_token_status = zx::channel::create(
0u, &viewport_creation_token.value, &view_creation_token.value);
ASSERT_EQ(view_creation_token_status, ZX_OK);
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ view_ref.Clone(&view_ref_clone);
// Create the `ExternalViewEmbedder` and pump the message loop until
// the initial scene graph is setup.
ExternalViewEmbedder external_view_embedder(
std::move(view_creation_token),
fuchsia::ui::views::ViewIdentityOnCreation{
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref),
+ .view_ref = std::move(view_ref),
+ .view_ref_control = std::move(view_ref_control),
},
fuchsia::ui::composition::ViewBoundProtocols{},
parent_viewport_watcher.NewRequest(), flatland_connection(),
@@ -570,7 +598,7 @@
loop().RunUntilIdle();
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Create the view before drawing the scene.
const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f);
@@ -646,7 +674,7 @@
});
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Pump the message loop. The scene updates should propagate to flatland.
loop().RunUntilIdle();
@@ -656,7 +684,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -685,7 +714,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -726,7 +756,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -754,7 +785,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -770,20 +802,29 @@
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher;
fuchsia::ui::views::ViewportCreationToken viewport_creation_token;
fuchsia::ui::views::ViewCreationToken view_creation_token;
- fuchsia::ui::views::ViewRef view_ref;
+ fuchsia::ui::views::ViewRef view_ref_clone;
auto view_creation_token_status = zx::channel::create(
0u, &viewport_creation_token.value, &view_creation_token.value);
ASSERT_EQ(view_creation_token_status, ZX_OK);
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ view_ref.Clone(&view_ref_clone);
// Create the `ExternalViewEmbedder` and pump the message loop until
// the initial scene graph is setup.
ExternalViewEmbedder external_view_embedder(
std::move(view_creation_token),
fuchsia::ui::views::ViewIdentityOnCreation{
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref),
+ .view_ref = std::move(view_ref),
+ .view_ref_control = std::move(view_ref_control),
},
fuchsia::ui::composition::ViewBoundProtocols{},
parent_viewport_watcher.NewRequest(), flatland_connection(),
@@ -794,7 +835,7 @@
loop().RunUntilIdle();
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Create the view before drawing the scene.
const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f);
@@ -883,7 +924,7 @@
});
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Pump the message loop. The scene updates should propagate to flatland.
loop().RunUntilIdle();
@@ -893,7 +934,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -962,7 +1004,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -1006,7 +1049,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -1022,20 +1066,29 @@
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher;
fuchsia::ui::views::ViewportCreationToken viewport_creation_token;
fuchsia::ui::views::ViewCreationToken view_creation_token;
- fuchsia::ui::views::ViewRef view_ref;
+ fuchsia::ui::views::ViewRef view_ref_clone;
auto view_creation_token_status = zx::channel::create(
0u, &viewport_creation_token.value, &view_creation_token.value);
ASSERT_EQ(view_creation_token_status, ZX_OK);
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ view_ref.Clone(&view_ref_clone);
// Create the `ExternalViewEmbedder` and pump the message loop until
// the initial scene graph is setup.
ExternalViewEmbedder external_view_embedder(
std::move(view_creation_token),
fuchsia::ui::views::ViewIdentityOnCreation{
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref),
+ .view_ref = std::move(view_ref),
+ .view_ref_control = std::move(view_ref_control),
},
fuchsia::ui::composition::ViewBoundProtocols{},
parent_viewport_watcher.NewRequest(), flatland_connection(),
@@ -1046,7 +1099,7 @@
loop().RunUntilIdle();
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Create the view before drawing the scene.
const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f);
@@ -1098,7 +1151,7 @@
[](flutter::DlCanvas* canvas) {});
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Pump the message loop. The scene updates should propagate to flatland.
loop().RunUntilIdle();
@@ -1107,7 +1160,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -1127,7 +1181,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -1160,7 +1215,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -1179,7 +1235,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -1195,20 +1252,29 @@
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher;
fuchsia::ui::views::ViewportCreationToken viewport_creation_token;
fuchsia::ui::views::ViewCreationToken view_creation_token;
- fuchsia::ui::views::ViewRef view_ref;
+ fuchsia::ui::views::ViewRef view_ref_clone;
auto view_creation_token_status = zx::channel::create(
0u, &viewport_creation_token.value, &view_creation_token.value);
ASSERT_EQ(view_creation_token_status, ZX_OK);
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ view_ref.Clone(&view_ref_clone);
// Create the `ExternalViewEmbedder` and pump the message loop until
// the initial scene graph is setup.
ExternalViewEmbedder external_view_embedder(
std::move(view_creation_token),
fuchsia::ui::views::ViewIdentityOnCreation{
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref),
+ .view_ref = std::move(view_ref),
+ .view_ref_control = std::move(view_ref_control),
},
fuchsia::ui::composition::ViewBoundProtocols{},
parent_viewport_watcher.NewRequest(), flatland_connection(),
@@ -1219,7 +1285,7 @@
loop().RunUntilIdle();
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Create the view before drawing the scene.
auto [child_view_token, child_viewport_token] = ViewTokenPair::New();
@@ -1256,7 +1322,7 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref,
+ parent_viewport_watcher, viewport_creation_token, view_ref_clone,
/*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
@@ -1274,7 +1340,7 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref,
+ parent_viewport_watcher, viewport_creation_token, view_ref_clone,
/*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
@@ -1309,7 +1375,7 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref,
+ parent_viewport_watcher, viewport_creation_token, view_ref_clone,
/*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
@@ -1326,7 +1392,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
new_frame_size, kFirstLayerBlendMode,
{IsHitRegion(
@@ -1345,20 +1412,29 @@
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher;
fuchsia::ui::views::ViewportCreationToken viewport_creation_token;
fuchsia::ui::views::ViewCreationToken view_creation_token;
- fuchsia::ui::views::ViewRef view_ref;
+ fuchsia::ui::views::ViewRef view_ref_clone;
auto view_creation_token_status = zx::channel::create(
0u, &viewport_creation_token.value, &view_creation_token.value);
ASSERT_EQ(view_creation_token_status, ZX_OK);
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ view_ref.Clone(&view_ref_clone);
// Create the `ExternalViewEmbedder` and pump the message loop until
// the initial scene graph is setup.
ExternalViewEmbedder external_view_embedder(
std::move(view_creation_token),
fuchsia::ui::views::ViewIdentityOnCreation{
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref),
+ .view_ref = std::move(view_ref),
+ .view_ref_control = std::move(view_ref_control),
},
fuchsia::ui::composition::ViewBoundProtocols{},
parent_viewport_watcher.NewRequest(), flatland_connection(),
@@ -1369,7 +1445,7 @@
loop().RunUntilIdle();
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Draw the scene. The scene graph shouldn't change yet.
const SkISize frame_size_signed = SkISize::Make(512, 512);
@@ -1402,7 +1478,7 @@
});
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Pump the message loop. The scene updates should propagate to flatland.
loop().RunUntilIdle();
@@ -1410,7 +1486,7 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref,
+ parent_viewport_watcher, viewport_creation_token, view_ref_clone,
/*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
@@ -1438,20 +1514,29 @@
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher;
fuchsia::ui::views::ViewportCreationToken viewport_creation_token;
fuchsia::ui::views::ViewCreationToken view_creation_token;
- fuchsia::ui::views::ViewRef view_ref;
+ fuchsia::ui::views::ViewRef view_ref_clone;
auto view_creation_token_status = zx::channel::create(
0u, &viewport_creation_token.value, &view_creation_token.value);
ASSERT_EQ(view_creation_token_status, ZX_OK);
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ view_ref.Clone(&view_ref_clone);
// Create the `ExternalViewEmbedder` and pump the message loop until
// the initial scene graph is setup.
ExternalViewEmbedder external_view_embedder(
std::move(view_creation_token),
fuchsia::ui::views::ViewIdentityOnCreation{
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref),
+ .view_ref = std::move(view_ref),
+ .view_ref_control = std::move(view_ref_control),
},
fuchsia::ui::composition::ViewBoundProtocols{},
parent_viewport_watcher.NewRequest(), flatland_connection(),
@@ -1462,7 +1547,7 @@
loop().RunUntilIdle();
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Draw the scene. The scene graph shouldn't change yet.
const SkISize frame_size_signed = SkISize::Make(512, 512);
@@ -1495,7 +1580,7 @@
});
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref));
+ view_ref_clone));
// Pump the message loop. The scene updates should propagate to flatland.
loop().RunUntilIdle();
@@ -1503,7 +1588,7 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref,
+ parent_viewport_watcher, viewport_creation_token, view_ref_clone,
/*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
@@ -1520,20 +1605,29 @@
fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher;
fuchsia::ui::views::ViewportCreationToken viewport_creation_token;
fuchsia::ui::views::ViewCreationToken view_creation_token;
- fuchsia::ui::views::ViewRef view_ref;
+ fuchsia::ui::views::ViewRef view_ref_clone;
auto view_creation_token_status = zx::channel::create(
0u, &viewport_creation_token.value, &view_creation_token.value);
ASSERT_EQ(view_creation_token_status, ZX_OK);
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
+
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ASSERT_EQ(status, ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ view_ref.Clone(&view_ref_clone);
// Create the `ExternalViewEmbedder` and pump the message loop until
// the initial scene graph is setup.
ExternalViewEmbedder external_view_embedder(
std::move(view_creation_token),
fuchsia::ui::views::ViewIdentityOnCreation{
- .view_ref = std::move(view_ref_pair.view_ref),
- .view_ref_control = std::move(view_ref_pair.control_ref),
+ .view_ref = std::move(view_ref),
+ .view_ref_control = std::move(view_ref_control),
},
fuchsia::ui::composition::ViewBoundProtocols{},
parent_viewport_watcher.NewRequest(), flatland_connection(),
@@ -1546,7 +1640,7 @@
loop().RunUntilIdle();
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref, {IsInputShield()}));
+ view_ref_clone, {IsInputShield()}));
// Create the view before drawing the scene.
const SkSize child_view_size_signed = SkSize::Make(256.f, 512.f);
@@ -1622,7 +1716,7 @@
});
EXPECT_THAT(fake_flatland().graph(),
IsFlutterGraph(parent_viewport_watcher, viewport_creation_token,
- view_ref, {IsInputShield()}));
+ view_ref_clone, {IsInputShield()}));
// Pump the message loop. The scene updates should propagate to flatland.
loop().RunUntilIdle();
@@ -1632,7 +1726,8 @@
EXPECT_THAT(
fake_flatland().graph(),
IsFlutterGraph(
- parent_viewport_watcher, viewport_creation_token, view_ref, /*layers*/
+ parent_viewport_watcher, viewport_creation_token,
+ view_ref_clone, /*layers*/
{IsImageLayer(
frame_size, kFirstLayerBlendMode,
{IsHitRegion(
diff --git a/shell/platform/fuchsia/flutter/tests/fake_session_unittests.cc b/shell/platform/fuchsia/flutter/tests/fake_session_unittests.cc
deleted file mode 100644
index 966d133..0000000
--- a/shell/platform/fuchsia/flutter/tests/fake_session_unittests.cc
+++ /dev/null
@@ -1,461 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "fakes/scenic/fake_session.h"
-
-#include <fuchsia/ui/scenic/cpp/fidl.h>
-#include <fuchsia/ui/views/cpp/fidl.h>
-#include <lib/async-testing/test_loop.h>
-#include <lib/async/dispatcher.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 <lib/ui/scenic/cpp/view_token_pair.h>
-#include <zircon/types.h>
-
-#include <memory>
-#include <string>
-#include <type_traits>
-#include <vector>
-
-#include "flutter/fml/logging.h"
-#include "gmock/gmock.h" // For EXPECT_THAT and matchers
-#include "gtest/gtest.h"
-
-#include "fakes/scenic/fake_resources.h"
-
-using ::testing::_;
-using ::testing::AllOf;
-using ::testing::ElementsAre;
-using ::testing::FieldsAre;
-using ::testing::IsEmpty;
-using ::testing::Matcher;
-using ::testing::Not;
-using ::testing::Pair;
-using ::testing::Pointee;
-using ::testing::SizeIs;
-using ::testing::VariantWith;
-
-namespace flutter_runner::testing {
-namespace {
-
-std::string GetCurrentTestName() {
- return ::testing::UnitTest::GetInstance()->current_test_info()->name();
-}
-
-zx_koid_t GetKoid(zx_handle_t handle) {
- if (handle == ZX_HANDLE_INVALID) {
- return ZX_KOID_INVALID;
- }
-
- zx_info_handle_basic_t info;
- zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info,
- sizeof(info), nullptr, nullptr);
- return status == ZX_OK ? info.koid : ZX_KOID_INVALID;
-}
-
-zx_koid_t GetPeerKoid(zx_handle_t handle) {
- if (handle == ZX_HANDLE_INVALID) {
- return ZX_KOID_INVALID;
- }
-
- zx_info_handle_basic_t info;
- zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info,
- sizeof(info), nullptr, nullptr);
- return status == ZX_OK ? info.related_koid : ZX_KOID_INVALID;
-}
-
-Matcher<FakeResource> IsEntityNode(
- Matcher<decltype(FakeResource::id)> id,
- Matcher<decltype(FakeResource::label)> label,
- Matcher<decltype(FakeNode::children)> children) {
- return FieldsAre(
- id, label, FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeEntityNode>(FieldsAre(
- FieldsAre(children, FakeNode::kDefaultZeroRotation,
- FakeNode::kDefaultOneScale,
- FakeNode::kDefaultZeroTranslation,
- FakeNode::kDefaultZeroAnchor, FakeNode::kIsHitTestable,
- FakeNode::kIsSemanticallyVisible),
- IsEmpty())));
-}
-
-Matcher<FakeSceneGraph> IsEmptySceneGraph() {
- return FieldsAre(IsEmpty(), IsEmpty(), IsEmpty(), kInvalidFakeResourceId);
-}
-
-MATCHER_P2(IsEntityNodeSceneGraph, node_label, node_id, "") {
- static_assert(std::is_same_v<FakeSceneGraph, std::decay_t<decltype(arg)>>);
- static_assert(
- std::is_constructible_v<std::string, std::decay_t<decltype(node_label)>>);
- static_assert(
- std::is_same_v<FakeResourceId, std::decay_t<decltype(node_id)>>);
-
- return ExplainMatchResult(
- FieldsAre(
- IsEmpty(),
- AllOf(SizeIs(1u),
- Contains(Pair(node_id, Pointee(IsEntityNode(node_id, node_label,
- IsEmpty()))))),
- _, kInvalidFakeResourceId),
- arg, result_listener);
-}
-
-MATCHER_P5(IsBasicSceneGraph,
- view_label,
- node_label,
- view_holder_koid,
- view_ref_control_koid,
- view_ref_koid,
- "") {
- static_assert(std::is_same_v<FakeSceneGraph, std::decay_t<decltype(arg)>>);
- static_assert(
- std::is_constructible_v<std::string, std::decay_t<decltype(view_label)>>);
- static_assert(
- std::is_constructible_v<std::string, std::decay_t<decltype(node_label)>>);
- static_assert(
- std::is_same_v<zx_koid_t, std::decay_t<decltype(view_holder_koid)>>);
- static_assert(
- std::is_same_v<zx_koid_t, std::decay_t<decltype(view_ref_control_koid)>>);
- static_assert(
- std::is_same_v<zx_koid_t, std::decay_t<decltype(view_ref_koid)>>);
-
- return ExplainMatchResult(
- FieldsAre(
- IsEmpty(),
- AllOf(SizeIs(2u),
- Contains(Pair(arg.root_view_id,
- Pointee(FieldsAre(
- arg.root_view_id, "",
- FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeView>(FieldsAre(
- view_holder_koid, view_ref_control_koid,
- view_ref_koid, view_label,
- ElementsAre(Pointee(IsEntityNode(
- _, node_label, IsEmpty()))),
- FakeView::kDebugBoundsDisbaled))))))),
- _, AllOf(Not(kInvalidFakeResourceId), arg.root_view_id)),
- arg, result_listener);
-}
-
-} // namespace
-
-class FakeSessionTest : public ::testing::Test,
- public fuchsia::ui::scenic::SessionListener {
- protected:
- FakeSessionTest()
- : session_listener_(this), session_subloop_(loop_.StartNewLoop()) {}
- ~FakeSessionTest() override = default;
-
- async::TestLoop& loop() { return loop_; }
-
- FakeSession& fake_session() { return fake_session_; }
-
- scenic::Session CreateSession() {
- FML_CHECK(!fake_session_.is_bound());
- FML_CHECK(!session_listener_.is_bound());
-
- auto [session, session_listener] =
- fake_session_.Bind(session_subloop_->dispatcher());
- session_listener_.Bind(std::move(session_listener));
-
- return scenic::Session(session.Bind());
- }
-
- private:
- // |fuchsia::ui::scenic::SessionListener|
- void OnScenicError(std::string error) override { FAIL(); }
-
- // |fuchsia::ui::scenic::SessionListener|
- void OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) override {
- FAIL();
- }
-
- async::TestLoop loop_; // Must come before FIDL bindings.
-
- fuchsia::ui::scenic::SessionPtr session_ptr_;
- fidl::Binding<fuchsia::ui::scenic::SessionListener> session_listener_;
-
- std::unique_ptr<async::LoopInterface> session_subloop_;
- FakeSession fake_session_;
-};
-
-TEST_F(FakeSessionTest, Initialization) {
- EXPECT_EQ(fake_session().debug_name(), "");
- EXPECT_EQ(fake_session().command_queue().size(), 0u);
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-
- // Pump the loop one time; the session should retain its initial state.
- loop().RunUntilIdle();
- EXPECT_EQ(fake_session().debug_name(), "");
- EXPECT_EQ(fake_session().command_queue().size(), 0u);
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-}
-
-TEST_F(FakeSessionTest, DebugLabel) {
- scenic::Session session = CreateSession();
-
- // Set the session's debug name. The `SetDebugName` hasn't been processed
- // yet, so the session's view of the debug name is still empty.
- const std::string kDebugLabel = GetCurrentTestName();
- session.SetDebugName(kDebugLabel);
- session.Flush(); // Bypass local command caching.
- EXPECT_EQ(fake_session().debug_name(), "");
-
- // Pump the loop; the contents of the initial `SetDebugName` should be
- // processed.
- loop().RunUntilIdle();
- EXPECT_EQ(fake_session().debug_name(), kDebugLabel);
-}
-
-TEST_F(FakeSessionTest, CommandQueueInvariants) {
- scenic::Session session = CreateSession();
-
- // The scene graph is initially empty.
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-
- // Create entity node for testing; no creation commands have been processed
- // yet, so the session's view of the scene graph is empty.
- std::optional<scenic::EntityNode> node(&session);
- session.Flush(); // Bypass local command caching.
- EXPECT_EQ(fake_session().command_queue().size(), 0u);
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-
- // Pump the loop; the initial creation command should be enqueued but still
- // not processed yet, so the session's view of the scene graph is empty.
- loop().RunUntilIdle();
- EXPECT_GT(fake_session().command_queue().size(), 0u);
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-
- // Present initial scene graph. The `Present` hasn't been processed yet, so
- // the session's view of the scene graph is still empty.
- session.Present2(0u, 0u, [](auto...) {});
- EXPECT_GT(fake_session().command_queue().size(), 0u);
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-
- // Pump the loop; the contents of the initial `Present` should be processed.
- loop().RunUntilIdle();
- EXPECT_EQ(fake_session().command_queue().size(), 0u);
- EXPECT_THAT(fake_session().SceneGraph(),
- IsEntityNodeSceneGraph("", node->id()));
-}
-
-TEST_F(FakeSessionTest, SimpleResourceLifecycle) {
- scenic::Session session = CreateSession();
-
- // The scene graph is initially empty.
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-
- // Present an initial entity node, pumping the loop to process commands.
- std::optional<scenic::EntityNode> node(&session);
- session.Present2(0u, 0u, [](auto...) {});
- loop().RunUntilIdle();
- EXPECT_THAT(fake_session().SceneGraph(),
- IsEntityNodeSceneGraph("", node->id()));
-
- // Present a simple property update on the test entity node.
- const std::string kNodeLabel = "EntityNode";
- node->SetLabel(kNodeLabel);
- session.Present2(0u, 0u, [](auto...) {});
- loop().RunUntilIdle();
- EXPECT_THAT(fake_session().SceneGraph(),
- IsEntityNodeSceneGraph(kNodeLabel, node->id()));
-
- // Present the destruction of the entity node.
- node.reset();
- session.Present2(0u, 0u, [](auto...) {});
- loop().RunUntilIdle();
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-}
-
-TEST_F(FakeSessionTest, ResourceReferenceCounting) {
- scenic::Session session = CreateSession();
-
- // Present a chain of 4 entity nodes for testing.
- std::array<std::optional<scenic::EntityNode>, 4> nodes{
- std::optional<scenic::EntityNode>(&session),
- std::optional<scenic::EntityNode>(&session),
- std::optional<scenic::EntityNode>(&session),
- std::optional<scenic::EntityNode>(&session)};
- const std::string kNodeLabel = "EntityNode";
- for (size_t i = 0; i < 4; i++) {
- nodes[i]->SetLabel(kNodeLabel + std::string(1, '0' + i));
- if (i < 3) {
- nodes[i]->AddChild(*nodes[i + 1]);
- }
- }
- session.Present2(0u, 0u, [](auto...) {});
- loop().RunUntilIdle();
- {
- auto scene_graph = fake_session().SceneGraph();
- EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
- EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
- EXPECT_EQ(scene_graph.resource_map.size(), 4u);
- EXPECT_EQ(scene_graph.label_map.size(), 4u);
- for (size_t i = 0; i < 4; i++) {
- const std::string node_i_label = kNodeLabel + std::string(1, '0' + i);
- ASSERT_EQ(scene_graph.resource_map.count(nodes[i]->id()), 1u);
- ASSERT_EQ(scene_graph.label_map.count(node_i_label), 1u);
-
- const auto node_i = scene_graph.resource_map[nodes[i]->id()];
- const auto node_i_label_resources = scene_graph.label_map[node_i_label];
- EXPECT_EQ(node_i_label_resources.size(), 1u);
- EXPECT_FALSE(node_i_label_resources[0].expired());
- EXPECT_EQ(node_i_label_resources[0].lock(), node_i);
- }
-
- EXPECT_THAT(
- scene_graph.resource_map[nodes[0]->id()],
- Pointee(IsEntityNode(
- nodes[0]->id(), kNodeLabel + std::string(1, '0'),
- ElementsAre(Pointee(IsEntityNode(
- nodes[1]->id(), kNodeLabel + std::string(1, '1'),
- ElementsAre(Pointee(IsEntityNode(
- nodes[2]->id(), kNodeLabel + std::string(1, '2'),
- ElementsAre(Pointee(IsEntityNode(
- nodes[3]->id(), kNodeLabel + std::string(1, '3'),
- IsEmpty()))))))))))));
- }
-
- // Destroy node #0. It should be dropped immediately since it has no parent.
- nodes[0].reset();
- session.Present2(0u, 0u, [](auto...) {});
- loop().RunUntilIdle();
- {
- auto scene_graph = fake_session().SceneGraph();
- EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
- EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
- EXPECT_EQ(scene_graph.resource_map.size(), 3u);
- EXPECT_EQ(scene_graph.label_map.size(), 3u);
- for (size_t i = 1; i < 4; i++) {
- const std::string node_i_label = kNodeLabel + std::string(1, '0' + i);
- ASSERT_EQ(scene_graph.resource_map.count(nodes[i]->id()), 1u);
- ASSERT_EQ(scene_graph.label_map.count(node_i_label), 1u);
-
- const auto node_i = scene_graph.resource_map[nodes[i]->id()];
- const auto node_i_label_resources = scene_graph.label_map[node_i_label];
- EXPECT_EQ(node_i_label_resources.size(), 1u);
- EXPECT_FALSE(node_i_label_resources[0].expired());
- EXPECT_EQ(node_i_label_resources[0].lock(), node_i);
- }
-
- EXPECT_EQ(scene_graph.resource_map.count(nodes[0]->id()), 0u);
- EXPECT_THAT(scene_graph.resource_map[nodes[1]->id()],
- Pointee(IsEntityNode(
- nodes[1]->id(), kNodeLabel + std::string(1, '1'),
- ElementsAre(Pointee(IsEntityNode(
- nodes[2]->id(), kNodeLabel + std::string(1, '2'),
- ElementsAre(Pointee(IsEntityNode(
- nodes[3]->id(), kNodeLabel + std::string(1, '3'),
- IsEmpty())))))))));
- }
-
- // Destroy node #2. It should still exist in the tree and the labels map
- // because it has a parent, but it is removed from the resource map.
- nodes[2].reset();
- session.Present2(0u, 0u, [](auto...) {});
- loop().RunUntilIdle();
- {
- auto scene_graph = fake_session().SceneGraph();
- EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
- EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
- EXPECT_EQ(scene_graph.resource_map.size(), 2u);
- EXPECT_EQ(scene_graph.label_map.size(), 3u);
- for (size_t i = 1; i < 4; i++) {
- const std::string node_i_label = kNodeLabel + std::string(1, '0' + i);
- ASSERT_EQ(scene_graph.label_map.count(node_i_label), 1u);
- ASSERT_EQ(scene_graph.resource_map.count(nodes[i]->id()),
- i != 2 ? 1u : 0u);
-
- const auto node_i_label_resources = scene_graph.label_map[node_i_label];
- EXPECT_EQ(node_i_label_resources.size(), 1u);
- EXPECT_FALSE(node_i_label_resources[0].expired());
-
- if (i != 2) {
- const auto node_i = scene_graph.resource_map[nodes[i]->id()];
- EXPECT_EQ(node_i_label_resources[0].lock(), node_i);
- } else {
- EXPECT_EQ(scene_graph.resource_map.count(nodes[i]->id()), 0u);
- }
- }
-
- EXPECT_THAT(scene_graph.resource_map[nodes[1]->id()],
- Pointee(IsEntityNode(
- nodes[1]->id(), kNodeLabel + std::string(1, '1'),
- ElementsAre(Pointee(IsEntityNode(
- nodes[2]->id(), kNodeLabel + std::string(1, '2'),
- ElementsAre(Pointee(IsEntityNode(
- nodes[3]->id(), kNodeLabel + std::string(1, '3'),
- IsEmpty())))))))));
- }
-
- // Destroy node #3. It should still exist in the tree and the labels map
- // because it has a grand-parent, but it is removed from the resource map.
- nodes[3].reset();
- session.Present2(0u, 0u, [](auto...) {});
- loop().RunUntilIdle();
- {
- auto scene_graph = fake_session().SceneGraph();
- EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
- EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
- EXPECT_EQ(scene_graph.resource_map.size(), 1u);
- EXPECT_EQ(scene_graph.label_map.size(), 3u);
- for (size_t i = 1; i < 4; i++) {
- const std::string node_i_label = kNodeLabel + std::string(1, '0' + i);
- ASSERT_EQ(scene_graph.label_map.count(node_i_label), 1u);
- ASSERT_EQ(scene_graph.resource_map.count(nodes[i]->id()),
- i < 2 ? 1u : 0u);
-
- const auto node_i_label_resources = scene_graph.label_map[node_i_label];
- EXPECT_EQ(node_i_label_resources.size(), 1u);
- EXPECT_FALSE(node_i_label_resources[0].expired());
-
- if (i < 2) {
- const auto node_i = scene_graph.resource_map[nodes[i]->id()];
- EXPECT_EQ(node_i_label_resources[0].lock(), node_i);
- } else {
- EXPECT_EQ(scene_graph.resource_map.count(nodes[i]->id()), 0u);
- }
- }
-
- EXPECT_THAT(scene_graph.resource_map[nodes[1]->id()],
- Pointee(IsEntityNode(
- nodes[1]->id(), kNodeLabel + std::string(1, '1'),
- ElementsAre(Pointee(IsEntityNode(
- nodes[2]->id(), kNodeLabel + std::string(1, '2'),
- ElementsAre(Pointee(IsEntityNode(
- nodes[3]->id(), kNodeLabel + std::string(1, '3'),
- IsEmpty())))))))));
- }
-}
-
-TEST_F(FakeSessionTest, BasicSceneGraph) {
- scenic::Session session = CreateSession();
-
- // The scene graph is initially empty.
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-
- // Create and present initial scene graph.
- const std::string kViewDebugString = GetCurrentTestName();
- const std::string kNodeLabel = "ChildNode";
- fuchsia::ui::views::ViewRef view_ref;
- auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
- auto view_ref_pair = scenic::ViewRefPair::New();
- view_ref_pair.view_ref.Clone(&view_ref);
- scenic::View root_view(&session, std::move(view_token),
- std::move(view_ref_pair.control_ref),
- std::move(view_ref_pair.view_ref), kViewDebugString);
- scenic::EntityNode child_node(&session);
- child_node.SetLabel(kNodeLabel);
- root_view.AddChild(child_node);
- session.Present2(0u, 0u, [](auto...) {});
- loop().RunUntilIdle();
- EXPECT_THAT(fake_session().SceneGraph(),
- IsBasicSceneGraph(kViewDebugString, kNodeLabel,
- GetPeerKoid(view_holder_token.value.get()),
- GetPeerKoid(view_ref.reference.get()),
- GetKoid(view_ref.reference.get())));
-}
-
-} // namespace flutter_runner::testing
diff --git a/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_resources.cc b/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_resources.cc
deleted file mode 100644
index ac4fda9..0000000
--- a/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_resources.cc
+++ /dev/null
@@ -1,311 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "fake_resources.h"
-
-#include "flutter/fml/logging.h"
-
-namespace flutter_runner::testing {
-namespace {
-
-using FakeResourceCache =
- std::unordered_map<FakeResourceState*, std::shared_ptr<FakeResource>>;
-
-std::shared_ptr<FakeResource> ResourceFromState(
- const std::shared_ptr<FakeResourceState>& resource,
- FakeResourceCache& cache);
-std::vector<std::shared_ptr<FakeResource>> ResourcesFromStates(
- const std::vector<std::shared_ptr<FakeResourceState>>& resources,
- FakeResourceCache& cache);
-
-FakeNode NodeFromState(FakeNodeState* node, FakeResourceCache& cache) {
- FML_CHECK(node);
-
- return FakeNode{
- .children = ResourcesFromStates(node->children, cache),
- .rotation_quaternion = node->rotation_quaternion,
- .scale_vector = node->scale_vector,
- .translation_vector = node->translation_vector,
- .anchor_vector = node->anchor_vector,
- .hit_testable = node->hit_testable,
- .semantically_visible = node->semantically_visible,
- };
-}
-
-FakeEntityNode EntityNodeFromState(FakeEntityNodeState* entity_node,
- FakeResourceCache& cache) {
- FML_CHECK(entity_node);
-
- // Convert clip planes.
- std::vector<FakeEntityNode::ClipPlane> clip_planes;
- for (auto& clip_plane : entity_node->clip_planes) {
- clip_planes.emplace_back(FakeEntityNode::ClipPlane{
- .dir = clip_plane.dir,
- .dist = clip_plane.dist,
- });
- }
-
- return FakeEntityNode{
- .node_state = NodeFromState(&entity_node->node_state, cache),
- .clip_planes = std::move(clip_planes),
- };
-}
-
-FakeOpacityNode OpacityNodeFromState(FakeOpacityNodeState* opacity_node,
- FakeResourceCache& cache) {
- FML_CHECK(opacity_node);
-
- return FakeOpacityNode{
- .node_state = NodeFromState(&opacity_node->node_state, cache),
- .opacity = opacity_node->opacity,
- };
-}
-
-FakeShapeNode ShapeNodeFromState(FakeShapeNodeState* shape_node,
- FakeResourceCache& cache) {
- FML_CHECK(shape_node);
-
- return FakeShapeNode{
- .node_state = NodeFromState(&shape_node->node_state, cache),
- .shape = ResourceFromState(shape_node->shape, cache),
- .material = ResourceFromState(shape_node->material, cache),
- };
-}
-
-FakeView ViewFromState(FakeViewState* view, FakeResourceCache& cache) {
- FML_CHECK(view);
-
- return FakeView{
- .token = view->token.koid,
- .control_ref = view->control_ref.koid,
- .view_ref = view->view_ref.koid,
- .debug_name = view->debug_name,
- .children = ResourcesFromStates(view->children, cache),
- .enable_debug_bounds = view->enable_debug_bounds,
- };
-}
-
-FakeViewHolder ViewHolderFromState(FakeViewHolderState* view_holder,
- FakeResourceCache& cache) {
- FML_CHECK(view_holder);
-
- return FakeViewHolder{
- .token = view_holder->token.koid,
- .debug_name = view_holder->debug_name,
- .properties = view_holder->properties,
- .bounds_color = view_holder->bounds_color,
- };
-}
-
-FakeShape ShapeFromState(FakeShapeState* shape, FakeResourceCache& cache) {
- FML_CHECK(shape);
-
- auto snapshot = FakeShape{};
- std::visit(
- [&snapshot](auto&& shape_def) {
- using T = std::decay_t<decltype(shape_def)>;
- if constexpr (std::is_same_v<T, FakeShapeState::CircleDef>) {
- snapshot.shape_def = FakeShape::CircleDef{
- .radius = shape_def.radius,
- };
- } else if constexpr (std::is_same_v<T, FakeShapeState::RectangleDef>) {
- snapshot.shape_def = FakeShape::RectangleDef{
- .width = shape_def.width,
- .height = shape_def.height,
- };
- } else if constexpr (std::is_same_v<
- T, FakeShapeState::RoundedRectangleDef>) {
- snapshot.shape_def = FakeShape::RoundedRectangleDef{
- .width = shape_def.width,
- .height = shape_def.height,
- .top_left_radius = shape_def.top_left_radius,
- .top_right_radius = shape_def.top_right_radius,
- .bottom_right_radius = shape_def.bottom_right_radius,
- .bottom_left_radius = shape_def.bottom_left_radius,
- };
- } else {
- FML_CHECK(false);
- }
- },
- shape->shape_def);
-
- return snapshot;
-}
-
-FakeMaterial MaterialFromState(FakeMaterialState* material,
- FakeResourceCache& cache) {
- FML_CHECK(material);
-
- return FakeMaterial{
- .image = ResourceFromState(material->image, cache),
- .color = material->color,
- };
-}
-
-FakeImage ImageFromState(FakeImageState* image, FakeResourceCache& cache) {
- FML_CHECK(image);
-
- auto snapshot = FakeImage{
- .memory = ResourceFromState(image->memory, cache),
- };
- std::visit(
- [&snapshot](auto&& image_def) {
- using T = std::decay_t<decltype(image_def)>;
- if constexpr (std::is_same_v<T, FakeImageState::ImageDef>) {
- snapshot.image_def = FakeImage::ImageDef{
- .info = image_def.info,
- .memory_offset = image_def.memory_offset,
- };
- } else if constexpr (std::is_same_v<T, FakeImageState::Image2Def>) {
- snapshot.image_def = FakeImage::Image2Def{
- .buffer_collection_id = image_def.buffer_collection_id,
- .buffer_collection_index = image_def.buffer_collection_index,
- .width = image_def.width,
- .height = image_def.height,
- };
- } else if constexpr (std::is_same_v<T, FakeImageState::Image3Def>) {
- snapshot.image_def = FakeImage::Image3Def{
- .import_token = image_def.import_token.koid,
- .buffer_collection_index = image_def.buffer_collection_index,
- .width = image_def.width,
- .height = image_def.height,
- };
- } else if constexpr (std::is_same_v<T, FakeImageState::ImagePipe2Def>) {
- snapshot.image_def = FakeImage::ImagePipe2Def{
- .image_pipe_request = image_def.image_pipe_request.koid,
- };
- } else {
- FML_CHECK(false);
- }
- },
- image->image_def);
-
- return snapshot;
-}
-
-FakeMemory MemoryFromState(FakeMemoryState* memory, FakeResourceCache& cache) {
- FML_CHECK(memory);
-
- return FakeMemory{
- .vmo = memory->vmo.koid,
- .allocation_size = memory->allocation_size,
- .is_device_memory = memory->is_device_memory,
- };
-}
-
-std::shared_ptr<FakeResource> ResourceFromState(
- const std::shared_ptr<FakeResourceState>& resource,
- FakeResourceCache& cache) {
- if (!resource) {
- return std::shared_ptr<FakeResource>();
- }
-
- // Try to hit the cache first...
- auto cache_it = cache.find(resource.get());
- if (cache_it != cache.end()) {
- return cache_it->second;
- }
-
- // Otherwise create a brand-new snapshot.
- std::shared_ptr<FakeResource> snapshot =
- std::make_shared<FakeResource>(FakeResource{
- .id = resource->id,
- .label = resource->label,
- .event_mask = resource->event_mask,
- });
- std::visit(
- [&snapshot, &resource, &cache](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (std::is_same_v<T, FakeEntityNodeState>) {
- snapshot->state = EntityNodeFromState(
- std::get_if<FakeEntityNodeState>(&resource->state), cache);
- } else if constexpr (std::is_same_v<T, FakeOpacityNodeState>) {
- snapshot->state = OpacityNodeFromState(
- std::get_if<FakeOpacityNodeState>(&resource->state), cache);
- } else if constexpr (std::is_same_v<T, FakeShapeNodeState>) {
- snapshot->state = ShapeNodeFromState(
- std::get_if<FakeShapeNodeState>(&resource->state), cache);
- } else if constexpr (std::is_same_v<T, FakeViewState>) {
- snapshot->state = ViewFromState(
- std::get_if<FakeViewState>(&resource->state), cache);
- } else if constexpr (std::is_same_v<T, FakeViewHolderState>) {
- snapshot->state = ViewHolderFromState(
- std::get_if<FakeViewHolderState>(&resource->state), cache);
- } else if constexpr (std::is_same_v<T, FakeShapeState>) {
- snapshot->state = ShapeFromState(
- std::get_if<FakeShapeState>(&resource->state), cache);
- } else if constexpr (std::is_same_v<T, FakeMaterialState>) {
- snapshot->state = MaterialFromState(
- std::get_if<FakeMaterialState>(&resource->state), cache);
- } else if constexpr (std::is_same_v<T, FakeImageState>) {
- snapshot->state = ImageFromState(
- std::get_if<FakeImageState>(&resource->state), cache);
- } else if constexpr (std::is_same_v<T, FakeMemoryState>) {
- snapshot->state = MemoryFromState(
- std::get_if<FakeMemoryState>(&resource->state), cache);
- } else {
- FML_CHECK(false);
- }
- },
- resource->state);
- auto [_, cache_success] =
- cache.emplace(std::make_pair(resource.get(), snapshot));
- FML_CHECK(cache_success);
-
- return snapshot;
-}
-
-std::vector<std::shared_ptr<FakeResource>> ResourcesFromStates(
- const std::vector<std::shared_ptr<FakeResourceState>>& resources,
- FakeResourceCache& cache) {
- std::vector<std::shared_ptr<FakeResource>> snapshots;
-
- for (auto& resource : resources) {
- snapshots.emplace_back(ResourceFromState(resource, cache));
- }
- return snapshots;
-}
-
-} // namespace
-
-FakeSceneGraph SceneGraphFromState(const FakeSceneGraphState& state) {
- FakeResourceCache resource_cache;
- FakeSceneGraph scene_graph;
-
- // Snapshot all buffer collections.
- for (auto& buffer_collection : state.buffer_collection_map) {
- scene_graph.buffer_collection_map.emplace(
- std::make_pair(buffer_collection.first, buffer_collection.second.koid));
- }
-
- // Snapshot resources in the map recursively.
- for (auto& resource : state.resource_map) {
- scene_graph.resource_map.emplace(std::make_pair(
- resource.first, ResourceFromState(resource.second, resource_cache)));
- }
-
- // Snapshot labels in the map.
- for (auto& label_resources : state.label_map) {
- auto [label_iter, label_success] =
- scene_graph.label_map.emplace(std::make_pair(
- label_resources.first, std::vector<std::weak_ptr<FakeResource>>()));
- FML_CHECK(label_success);
- auto& snapshot_label_resources = label_iter->second;
-
- for (auto& resource : label_resources.second) {
- auto resource_ptr = resource.lock();
- FML_CHECK(resource_ptr);
-
- snapshot_label_resources.emplace_back(
- ResourceFromState(resource_ptr, resource_cache));
- }
- }
-
- // Snapshot the view id.
- scene_graph.root_view_id = state.root_view_id;
-
- return scene_graph;
-}
-
-} // namespace flutter_runner::testing
diff --git a/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_resources.h b/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_resources.h
deleted file mode 100644
index 5a6484b..0000000
--- a/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_resources.h
+++ /dev/null
@@ -1,538 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_RESOURCES_H_
-#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_RESOURCES_H_
-
-#include <fuchsia/images/cpp/fidl.h>
-#include <fuchsia/sysmem/cpp/fidl.h>
-#include <fuchsia/ui/composition/cpp/fidl.h>
-#include <fuchsia/ui/gfx/cpp/fidl.h>
-#include <fuchsia/ui/views/cpp/fidl.h>
-#include <lib/fidl/cpp/interface_handle.h>
-#include <lib/fidl/cpp/interface_request.h>
-#include <lib/zx/vmo.h>
-#include <zircon/types.h>
-
-#include <array>
-#include <memory>
-#include <string>
-#include <unordered_map>
-#include <variant>
-#include <vector>
-
-inline bool operator==(const fuchsia::images::ImageInfo& a,
- const fuchsia::images::ImageInfo& b) {
- return a.height == b.height && a.width == b.width && a.stride == b.stride &&
- a.tiling == b.tiling && a.transform == b.transform &&
- a.alpha_format == b.alpha_format && a.pixel_format == b.pixel_format &&
- a.color_space == b.color_space;
-}
-
-inline bool operator==(const fuchsia::ui::gfx::vec3& a,
- const fuchsia::ui::gfx::vec3& b) {
- return a.x == b.x && a.y == b.y && a.z == b.z;
-}
-
-inline bool operator==(const fuchsia::ui::gfx::BoundingBox& a,
- const fuchsia::ui::gfx::BoundingBox& b) {
- return a.min == b.min && a.max == b.max;
-}
-
-inline bool operator==(const fuchsia::ui::gfx::ViewProperties& a,
- const fuchsia::ui::gfx::ViewProperties& b) {
- return a.downward_input == b.downward_input &&
- a.focus_change == b.focus_change && a.bounding_box == b.bounding_box &&
- a.inset_from_min == b.inset_from_min &&
- a.inset_from_max == b.inset_from_max;
-}
-
-namespace flutter_runner::testing {
-
-// Forward declarations
-template <typename S>
-struct FakeResourceT;
-
-// Unique (within a Session) identifier for a Resource.
-using FakeResourceId = decltype(fuchsia::ui::gfx::CreateResourceCmd::id);
-constexpr FakeResourceId kInvalidFakeResourceId = 0u;
-
-// Tag type for a Resource "state". The Resource state keeps alive any handles
-// associated with a resource e.g. view token or sysmem token.
-//
-// "snapshot" Resources are generated from "state" Resources during
-// `SceneGraphFromState()` calls.
-//
-// The `FakeSession` stores `FakeResourceT<StateT>` internally.
-struct StateT {
- using ResourceT = FakeResourceT<StateT>;
-
- template <typename T>
- struct HandleT {
- T value{};
- zx_koid_t koid{ZX_KOID_INVALID};
- };
-
- template <typename T>
- static bool HandlesAreEqual(const HandleT<T>& token,
- const HandleT<T>& other_token) {
- return token.koid == other_token.koid;
- }
-};
-
-// Tag type for a Resource "snapshot". The Resource snapshot only stores koids
-// for any handles associated with the resource; in this way it doesn't have any
-// control over the underlying handle lifetime.
-//
-// "snapshot" Resources are generated from "state" Resources during
-// `SceneGraphFromState()` calls.
-//
-// The `FakeSession` returns `FakeResourceT<SnapshotT>` from its `SceneGraph()`
-// accessor.
-struct SnapshotT {
- using ResourceT = FakeResourceT<SnapshotT>;
-
- template <typename T>
- using HandleT = zx_koid_t;
-
- template <typename T>
- static bool HandlesAreEqual(const HandleT<T>& token,
- const HandleT<T>& other_token) {
- return token == other_token;
- }
-};
-
-// Common state for Node-typed Resources: EntityNode, OpacityNode, ShapeNode,
-// ViewHolder.
-//
-// FakeNodeT's are never used directly, only as an embedded field of a
-// Node-typed resource.
-template <typename S>
-struct FakeNodeT {
- bool operator==(const FakeNodeT& other) const;
-
- constexpr static std::array<float, 4> kDefaultZeroRotation{0.f, 0.f, 0.f,
- 1.f};
- constexpr static std::array<float, 3> kDefaultOneScale{1.f, 1.f, 1.f};
- constexpr static std::array<float, 3> kDefaultZeroTranslation{0.f, 0.f, 0.f};
- constexpr static std::array<float, 3> kDefaultZeroAnchor{0.f, 0.f, 0.f};
- constexpr static bool kIsHitTestable{true};
- constexpr static bool kIsNotHitTestable{false};
- constexpr static bool kIsSemanticallyVisible{true};
- constexpr static bool kIsNotSemanticallyVisible{false};
-
- std::vector<std::shared_ptr<typename S::ResourceT>> children;
- std::array<float, 4> rotation_quaternion{kDefaultZeroRotation};
- std::array<float, 3> scale_vector{kDefaultOneScale};
- std::array<float, 3> translation_vector{kDefaultZeroTranslation};
- std::array<float, 3> anchor_vector{kDefaultZeroAnchor};
- bool hit_testable{kIsHitTestable};
- bool semantically_visible{kIsSemanticallyVisible};
-};
-
-using FakeNodeState = FakeNodeT<StateT>;
-using FakeNode = FakeNodeT<SnapshotT>;
-
-// EntityNode Resource state.
-template <typename S>
-struct FakeEntityNodeT {
- struct ClipPlane {
- bool operator==(const ClipPlane& other) const;
-
- constexpr static std::array<float, 3> kDefaultZeroDir{0.f, 0.f, 0.f};
- constexpr static float kDefaultZeroDist{0.f};
-
- std::array<float, 3> dir{kDefaultZeroDir};
- float dist{kDefaultZeroDist};
- };
-
- bool operator==(const FakeEntityNodeT& other) const;
-
- FakeNodeT<S> node_state;
-
- std::vector<ClipPlane> clip_planes;
-};
-using FakeEntityNodeState = FakeEntityNodeT<StateT>;
-using FakeEntityNode = FakeEntityNodeT<SnapshotT>;
-
-// OpacityNode Resource state.
-template <typename S>
-struct FakeOpacityNodeT {
- bool operator==(const FakeOpacityNodeT& other) const;
-
- FakeNodeT<S> node_state;
-
- constexpr static float kDefaultOneOpacity{1.f};
-
- float opacity{kDefaultOneOpacity};
-};
-using FakeOpacityNodeState = FakeOpacityNodeT<StateT>;
-using FakeOpacityNode = FakeOpacityNodeT<SnapshotT>;
-
-// ShapeNode Resource state.
-template <typename S>
-struct FakeShapeNodeT {
- bool operator==(const FakeShapeNodeT& other) const;
-
- FakeNodeT<S> node_state;
-
- std::shared_ptr<typename S::ResourceT> shape;
- std::shared_ptr<typename S::ResourceT> material;
-};
-using FakeShapeNodeState = FakeShapeNodeT<StateT>;
-using FakeShapeNode = FakeShapeNodeT<SnapshotT>;
-
-// View Resource state.
-template <typename S>
-struct FakeViewT {
- bool operator==(const FakeViewT& other) const;
-
- constexpr static bool kDebugBoundsEnabled{true};
- constexpr static bool kDebugBoundsDisbaled{false};
-
- typename S::template HandleT<fuchsia::ui::views::ViewToken> token{};
- typename S::template HandleT<fuchsia::ui::views::ViewRefControl>
- control_ref{};
- typename S::template HandleT<fuchsia::ui::views::ViewRef> view_ref{};
- std::string debug_name{};
-
- std::vector<std::shared_ptr<typename S::ResourceT>> children;
- bool enable_debug_bounds{kDebugBoundsDisbaled};
-};
-using FakeViewState = FakeViewT<StateT>;
-using FakeView = FakeViewT<SnapshotT>;
-
-// ViewHolder Resource state.
-template <typename S>
-struct FakeViewHolderT {
- bool operator==(const FakeViewHolderT& other) const;
-
- FakeNodeT<S> node_state;
-
- constexpr static std::array<float, 4> kDefaultBoundsColorWhite{1.f, 1.f, 1.f,
- 1.f};
- typename S::template HandleT<fuchsia::ui::views::ViewHolderToken> token{};
- std::string debug_name{};
-
- fuchsia::ui::gfx::ViewProperties properties;
- std::array<float, 4> bounds_color{kDefaultBoundsColorWhite};
-};
-using FakeViewHolderState = FakeViewHolderT<StateT>;
-using FakeViewHolder = FakeViewHolderT<SnapshotT>;
-
-// Shape Resource state.
-template <typename S>
-struct FakeShapeT {
- bool operator==(const FakeShapeT& other) const;
-
- struct CircleDef {
- bool operator==(const CircleDef& other) const;
-
- float radius{0.f};
- };
-
- struct RectangleDef {
- bool operator==(const RectangleDef& other) const;
-
- float width{0.f};
- float height{0.f};
- };
-
- struct RoundedRectangleDef {
- bool operator==(const RoundedRectangleDef& other) const;
-
- float width{0.f};
- float height{0.f};
- float top_left_radius{0.f};
- float top_right_radius{0.f};
- float bottom_right_radius{0.f};
- float bottom_left_radius{0.f};
- };
-
- std::variant<CircleDef, RectangleDef, RoundedRectangleDef> shape_def;
-};
-using FakeShapeState = FakeShapeT<StateT>;
-using FakeShape = FakeShapeT<SnapshotT>;
-
-// Material Resource state.
-template <typename S>
-struct FakeMaterialT {
- bool operator==(const FakeMaterialT& other) const;
-
- constexpr static std::array<float, 4> kDefaultColorWhite{1.f, 1.f, 1.f, 1.f};
-
- std::shared_ptr<typename S::ResourceT> image;
- std::array<float, 4> color{kDefaultColorWhite};
-};
-using FakeMaterialState = FakeMaterialT<StateT>;
-using FakeMaterial = FakeMaterialT<SnapshotT>;
-
-// Image Resource state.
-template <typename S>
-struct FakeImageT {
- struct ImageDef {
- bool operator==(const ImageDef& other) const;
-
- fuchsia::images::ImageInfo info{};
- uint32_t memory_offset{};
- };
-
- struct Image2Def {
- bool operator==(const Image2Def& other) const;
-
- uint32_t buffer_collection_id{};
- uint32_t buffer_collection_index{};
- uint32_t width{};
- uint32_t height{};
- };
-
- struct Image3Def {
- bool operator==(const Image3Def& other) const;
-
- typename S::template HandleT<
- fuchsia::ui::composition::BufferCollectionImportToken>
- import_token{};
- uint32_t buffer_collection_index{};
- uint32_t width{};
- uint32_t height{};
- };
-
- struct ImagePipe2Def {
- bool operator==(const ImagePipe2Def& other) const;
-
- typename S::template HandleT<
- fidl::InterfaceRequest<fuchsia::images::ImagePipe2>>
- image_pipe_request{};
- };
-
- bool operator==(const FakeImageT& other) const;
-
- std::variant<ImageDef, Image2Def, Image3Def, ImagePipe2Def> image_def;
- std::shared_ptr<typename S::ResourceT> memory;
-};
-using FakeImageState = FakeImageT<StateT>;
-using FakeImage = FakeImageT<SnapshotT>;
-
-// Memory Resource state.
-template <typename S>
-struct FakeMemoryT {
- bool operator==(const FakeMemoryT& other) const;
-
- constexpr static bool kIsDeviceMemory{true};
- constexpr static bool kIsNotDeviceMemory{false};
-
- typename S::template HandleT<zx::vmo> vmo{};
- uint64_t allocation_size{};
- bool is_device_memory{kIsNotDeviceMemory};
-};
-using FakeMemoryState = FakeMemoryT<StateT>;
-using FakeMemory = FakeMemoryT<SnapshotT>;
-
-// A complete Resource which records common Resource data and stores it's
-// type-specific state inside of a variant.
-template <typename S>
-struct FakeResourceT {
- bool operator==(const FakeResourceT& other) const;
-
- constexpr static uint32_t kDefaultEmptyEventMask{0};
-
- FakeResourceId id{kInvalidFakeResourceId};
-
- std::string label{};
- uint32_t event_mask{kDefaultEmptyEventMask};
-
- std::variant<FakeEntityNodeT<S>,
- FakeOpacityNodeT<S>,
- FakeShapeNodeT<S>,
- FakeViewT<S>,
- FakeViewHolderT<S>,
- FakeShapeT<S>,
- FakeMaterialT<S>,
- FakeImageT<S>,
- FakeMemoryT<S>>
- state;
-};
-using FakeResourceState = FakeResourceT<StateT>;
-using FakeResource = FakeResourceT<SnapshotT>;
-
-// A complete scene graph which records a forest of Resource trees.
-//
-// It also records auxiliary data like buffer collection IDs and resource labels
-// for fast lookup.
-//
-// Each Session / scene graph may only have a single View Resource which is
-// treated as the root of that scene. The root View and all Resources
-// descending from it are what the real scenic implementation would submit for
-// rendering.
-template <typename S>
-struct FakeSceneGraphT {
- bool operator==(const FakeSceneGraphT& other) const;
-
- std::unordered_map<uint32_t,
- typename S::template HandleT<fidl::InterfaceHandle<
- fuchsia::sysmem::BufferCollectionToken>>>
- buffer_collection_map;
-
- std::unordered_map<FakeResourceId, std::shared_ptr<FakeResourceT<S>>>
- resource_map;
- std::unordered_map<std::string, std::vector<std::weak_ptr<FakeResourceT<S>>>>
- label_map;
- FakeResourceId root_view_id{kInvalidFakeResourceId};
-};
-using FakeSceneGraphState = FakeSceneGraphT<StateT>;
-using FakeSceneGraph = FakeSceneGraphT<SnapshotT>;
-
-// Generate a snapshot of a scene graph from that scene graph's state.
-//
-// The lifetime of the snapshot and its Resources has no influence on the
-// lifetime of the source scene graph or its Resources.
-FakeSceneGraph SceneGraphFromState(const FakeSceneGraphState& state);
-
-template <typename S>
-bool FakeEntityNodeT<S>::ClipPlane::operator==(
- const FakeEntityNodeT<S>::ClipPlane& other) const {
- return dir == other.dir && dist == other.dist;
-}
-
-template <typename S>
-bool FakeNodeT<S>::operator==(const FakeNodeT<S>& other) const {
- return children == other.children &&
- rotation_quaternion == other.rotation_quaternion &&
- scale_vector == other.scale_vector &&
- translation_vector == other.translation_vector &&
- anchor_vector == other.anchor_vector &&
- hit_testable == other.hit_testable &&
- semantically_visible == other.semantically_visible;
-}
-
-template <typename S>
-bool FakeEntityNodeT<S>::operator==(const FakeEntityNodeT<S>& other) const {
- return node_state == other.node_state && clip_planes == other.clip_planes;
-}
-
-template <typename S>
-bool FakeOpacityNodeT<S>::operator==(const FakeOpacityNodeT<S>& other) const {
- return node_state == other.node_state && opacity == other.opacity;
-}
-
-template <typename S>
-bool FakeShapeNodeT<S>::operator==(const FakeShapeNodeT<S>& other) const {
- return node_state == other.node_state && shape == other.shape &&
- material == other.material;
-}
-
-template <typename S>
-bool FakeViewT<S>::operator==(const FakeViewT<S>& other) const {
- return S::template HandlesAreEqual<fuchsia::ui::views::ViewToken>(
- token, other.token) &&
- S::template HandlesAreEqual<fuchsia::ui::views::ViewRefControl>(
- control_ref, other.control_ref) &&
- S::template HandlesAreEqual<fuchsia::ui::views::ViewRef>(
- view_ref, other.view_ref) &&
- children == other.children && debug_name == other.debug_name &&
- enable_debug_bounds == other.enable_debug_bounds;
-}
-
-template <typename S>
-bool FakeViewHolderT<S>::operator==(const FakeViewHolderT<S>& other) const {
- return FakeNodeT<S>::operator==(other) &&
- S::template HandlesAreEqual<fuchsia::ui::views::ViewHolderToken>(
- token, other.token) &&
- debug_name == other.debug_name && properties == other.properties &&
- bounds_color == other.bounds_color;
-}
-
-template <typename S>
-bool FakeShapeT<S>::CircleDef::operator==(
- const FakeShapeT<S>::CircleDef& other) const {
- return radius == other.radius;
-}
-
-template <typename S>
-bool FakeShapeT<S>::RectangleDef::operator==(
- const FakeShapeT<S>::RectangleDef& other) const {
- return width == other.width && height == other.height;
-}
-
-template <typename S>
-bool FakeShapeT<S>::RoundedRectangleDef::operator==(
- const FakeShapeT<S>::RoundedRectangleDef& other) const {
- return width == other.width && height == other.height &&
- top_left_radius == other.top_left_radius &&
- top_right_radius == other.top_right_radius &&
- bottom_right_radius == other.bottom_right_radius &&
- bottom_left_radius == other.bottom_left_radius;
-}
-
-template <typename S>
-bool FakeShapeT<S>::operator==(const FakeShapeT<S>& other) const {
- return shape_def == other.shape_def;
-}
-
-template <typename S>
-bool FakeMaterialT<S>::operator==(const FakeMaterialT<S>& other) const {
- return image == other.image && color == other.color;
-}
-
-template <typename S>
-bool FakeImageT<S>::ImageDef::operator==(
- const FakeImageT<S>::ImageDef& other) const {
- return info == other.info && memory_offset == other.memory_offset;
-}
-
-template <typename S>
-bool FakeImageT<S>::Image2Def::operator==(
- const FakeImageT<S>::Image2Def& other) const {
- return buffer_collection_id == other.buffer_collection_id &&
- buffer_collection_index == other.buffer_collection_index &&
- width == other.width && height == other.height;
-}
-
-template <typename S>
-bool FakeImageT<S>::Image3Def::operator==(
- const FakeImageT<S>::Image3Def& other) const {
- return S::template HandlesAreEqual<
- fuchsia::ui::composition::BufferCollectionImportToken>(
- import_token, other.import_token) &&
- buffer_collection_index == other.buffer_collection_index &&
- width == other.width && height == other.height;
-}
-
-template <typename S>
-bool FakeImageT<S>::ImagePipe2Def::operator==(
- const FakeImageT<S>::ImagePipe2Def& other) const {
- return S::template HandlesAreEqual<
- fidl::InterfaceRequest<fuchsia::images::ImagePipe2>>(
- image_pipe_request, other.image_pipe_request);
-}
-
-template <typename S>
-bool FakeImageT<S>::operator==(const FakeImageT<S>& other) const {
- return image_def == other.image_def && memory == other.memory;
-}
-
-template <typename S>
-bool FakeMemoryT<S>::operator==(const FakeMemoryT<S>& other) const {
- return S::template HandlesAreEqual<zx::vmo>(vmo, other.vmo) &&
- allocation_size == other.allocation_size &&
- is_device_memory == other.is_device_memory;
-}
-
-template <typename S>
-bool FakeResourceT<S>::operator==(const FakeResourceT<S>& other) const {
- return id == other.id && label == other.label &&
- event_mask == other.event_mask && state == other.state;
-}
-
-template <typename S>
-bool FakeSceneGraphT<S>::operator==(const FakeSceneGraphT<S>& other) const {
- return buffer_collection_map == other.buffer_collection_map &&
- resource_map ==
- other.resource_map && // labels_map == other.labels_map &&
- root_view_id == other.root_view_id;
-}
-
-} // namespace flutter_runner::testing
-
-#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_RESOURCES_H_
diff --git a/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_session.cc b/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_session.cc
deleted file mode 100644
index 133360a..0000000
--- a/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_session.cc
+++ /dev/null
@@ -1,1161 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "fake_session.h"
-
-#include <zircon/types.h>
-
-#include <algorithm> // For remove_if
-#include <iterator> // For make_move_iterator
-#include <memory>
-
-#include "flutter/fml/logging.h"
-#include "flutter/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_resources.h"
-#include "fuchsia/images/cpp/fidl.h"
-
-namespace flutter_runner::testing {
-namespace {
-
-template <typename T>
-constexpr bool is_node_v = std::is_same_v<T, FakeEntityNodeState> ||
- std::is_same_v<T, FakeOpacityNodeState> ||
- std::is_same_v<T, FakeShapeNodeState> ||
- std::is_same_v<T, FakeViewHolderState>;
-
-template <typename T>
-bool ResourceIs(const FakeResourceState& resource) {
- return std::holds_alternative<T>(resource.state);
-}
-
-bool ResourceIsNode(const FakeResourceState& resource) {
- return ResourceIs<FakeEntityNodeState>(resource) ||
- ResourceIs<FakeOpacityNodeState>(resource) ||
- ResourceIs<FakeShapeNodeState>(resource) ||
- ResourceIs<FakeViewHolderState>(resource);
-}
-
-zx_koid_t GetKoid(zx_handle_t handle) {
- if (handle == ZX_HANDLE_INVALID) {
- return ZX_KOID_INVALID;
- }
-
- zx_info_handle_basic_t info;
- zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info,
- sizeof(info), nullptr, nullptr);
- return status == ZX_OK ? info.koid : ZX_KOID_INVALID;
-}
-
-} // namespace
-
-FakeSession::FakeSession() : binding_(this) {}
-
-FakeSession::SessionAndListenerClientPair FakeSession::Bind(
- async_dispatcher_t* dispatcher) {
- FML_CHECK(!listener_.is_bound());
- FML_CHECK(!binding_.is_bound());
-
- fidl::InterfaceHandle<fuchsia::ui::scenic::Session> session;
- auto listener_request = listener_.NewRequest(dispatcher);
- binding_.Bind(session.NewRequest(), dispatcher);
-
- return std::make_pair(std::move(session), std::move(listener_request));
-}
-
-void FakeSession::SetPresentHandler(PresentHandler present_handler) {
- present_handler_ = std::move(present_handler);
-}
-
-void FakeSession::SetPresent2Handler(Present2Handler present2_handler) {
- present2_handler_ = std::move(present2_handler);
-}
-
-void FakeSession::SetRequestPresentationTimesHandler(
- RequestPresentationTimesHandler request_presentation_times_handler) {
- request_presentation_times_handler_ =
- std::move(request_presentation_times_handler);
-}
-
-void FakeSession::FireOnFramePresentedEvent(
- fuchsia::scenic::scheduling::FramePresentedInfo frame_presented_info) {
- FML_CHECK(is_bound());
-
- binding_.events().OnFramePresented(std::move(frame_presented_info));
-}
-
-void FakeSession::DisconnectSession() {
- // Unbind the channels and drop them on the floor, simulating Scenic behavior.
- binding_.Unbind();
- listener_.Unbind();
-}
-
-void FakeSession::NotImplemented_(const std::string& name) {
- FML_LOG(FATAL) << "FakeSession does not implement " << name;
-}
-
-void FakeSession::Enqueue(std::vector<fuchsia::ui::scenic::Command> cmds) {
- // Append `cmds` to the end of the command queue, preferring to move elements
- // when possible.
- command_queue_.insert(command_queue_.end(),
- std::make_move_iterator(cmds.begin()),
- std::make_move_iterator(cmds.end()));
-}
-
-void FakeSession::Present(uint64_t presentation_time,
- std::vector<zx::event> acquire_fences,
- std::vector<zx::event> release_fences,
- PresentCallback callback) {
- ApplyCommands();
-
- PresentHandler present_handler =
- present_handler_ ? present_handler_ : [](auto... args) -> auto {
- return fuchsia::images::PresentationInfo{};
- };
-
- auto present_info = present_handler_(
- presentation_time, std::move(acquire_fences), std::move(release_fences));
- if (callback) {
- callback(std::move(present_info));
- }
-}
-
-void FakeSession::Present2(fuchsia::ui::scenic::Present2Args args,
- Present2Callback callback) {
- ApplyCommands();
-
- Present2Handler present2_handler =
- present2_handler_ ? present2_handler_ : [](auto args) -> auto {
- return fuchsia::scenic::scheduling::FuturePresentationTimes{
- .future_presentations = {},
- .remaining_presents_in_flight_allowed = 1,
- };
- };
-
- auto future_presentation_times = present2_handler(std::move(args));
- if (callback) {
- callback(std::move(future_presentation_times));
- }
-}
-
-void FakeSession::RequestPresentationTimes(
- int64_t requested_prediction_span,
- RequestPresentationTimesCallback callback) {
- RequestPresentationTimesHandler request_presentation_times_handler =
- request_presentation_times_handler_ ? request_presentation_times_handler_
- : [](auto args) -> auto {
- return fuchsia::scenic::scheduling::FuturePresentationTimes{
- .future_presentations = {},
- .remaining_presents_in_flight_allowed = 1,
- };
- };
-
- auto future_presentation_times =
- request_presentation_times_handler(requested_prediction_span);
- if (callback) {
- callback(std::move(future_presentation_times));
- }
-}
-
-void FakeSession::RegisterBufferCollection(
- uint32_t buffer_id,
- fidl::InterfaceHandle<fuchsia::sysmem::BufferCollectionToken> token) {
- zx_koid_t token_koid = GetKoid(token.channel().get());
- auto [_, buffer_success] =
- scene_graph_.buffer_collection_map.emplace(std::make_pair(
- buffer_id,
- StateT::HandleT<
- fidl::InterfaceHandle<fuchsia::sysmem::BufferCollectionToken>>{
- std::move(token), token_koid}));
- FML_CHECK(buffer_success);
-}
-
-void FakeSession::DeregisterBufferCollection(uint32_t buffer_id) {
- size_t erased = scene_graph_.buffer_collection_map.erase(buffer_id);
- FML_CHECK(erased == 1);
-}
-
-void FakeSession::SetDebugName(std::string debug_name) {
- debug_name_ = std::move(debug_name);
-}
-
-std::shared_ptr<FakeResourceState> FakeSession::GetResource(FakeResourceId id) {
- FML_CHECK(id != kInvalidFakeResourceId);
- auto resource_it = scene_graph_.resource_map.find(id);
- FML_CHECK(resource_it != scene_graph_.resource_map.end());
- auto resource_ptr = resource_it->second;
- FML_CHECK(resource_ptr);
-
- return resource_ptr;
-}
-
-void FakeSession::AddResource(FakeResourceState&& resource) {
- const FakeResourceId resource_id = resource.id;
- FML_CHECK(resource_id != kInvalidFakeResourceId);
-
- // Track the view id if the resource is a view.
- if (ResourceIs<FakeViewState>(resource)) {
- // If there was already a View in the scene graph, scenic prints a warning
- // here but doesn't update the "root view" and allows the Session to
- // continue. See also: fxbug.dev/24450
- if (scene_graph_.root_view_id == kInvalidFakeResourceId) {
- scene_graph_.root_view_id = resource_id;
- }
- }
-
- // Add to initial spot in parents map.
- auto resource_ptr = std::make_shared<FakeResourceState>(
- std::forward<FakeResourceState>(resource));
- if (ResourceIsNode(*resource_ptr)) {
- auto [_, parents_success] = parents_map_.emplace(std::make_pair(
- resource_ptr.get(),
- std::make_pair(std::weak_ptr<FakeResourceState>(resource_ptr),
- std::weak_ptr<FakeResourceState>())));
- FML_CHECK(parents_success);
- }
-
- // Add to initial spot in labels map.
- auto empty_label_it = scene_graph_.label_map.find("");
- if (empty_label_it == scene_graph_.label_map.end()) {
- auto [emplace_it, empty_label_success] = scene_graph_.label_map.emplace(
- std::make_pair("", std::vector<std::weak_ptr<FakeResourceState>>()));
- FML_CHECK(empty_label_success);
- empty_label_it = emplace_it;
- }
- empty_label_it->second.emplace_back(resource_ptr);
-
- // Add to resource map.
- auto [__, resource_success] = scene_graph_.resource_map.emplace(
- std::make_pair(resource_id, std::move(resource_ptr)));
- FML_CHECK(resource_success);
-}
-
-void FakeSession::DetachResourceFromParent(
- std::shared_ptr<FakeResourceState> resource_ptr,
- std::shared_ptr<FakeResourceState> new_parent_ptr) {
- FML_CHECK(resource_ptr);
-
- // Remove reference from the parent's `children` array.
- auto parent_it = parents_map_.find(resource_ptr.get());
- FML_CHECK(parent_it != parents_map_.end());
- if (auto parent_ptr = parent_it->second.second.lock()) {
- std::visit(
- [&resource_ptr](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (is_node_v<T>) {
- auto erase_it =
- std::remove_if(state.node_state.children.begin(),
- state.node_state.children.end(),
- [&resource_ptr](const auto& resource) {
- return resource == resource_ptr;
- });
- FML_CHECK(erase_it != state.node_state.children.end());
- state.node_state.children.erase(erase_it);
- } else if constexpr (std::is_same_v<T, FakeViewState>) {
- auto erase_it =
- std::remove_if(state.children.begin(), state.children.end(),
- [&resource_ptr](const auto& resource) {
- return resource == resource_ptr;
- });
- FML_CHECK(erase_it != state.children.end());
- state.children.erase(erase_it);
- } else {
- FML_CHECK(false);
- }
- },
- parent_ptr->state);
- }
-
- // Fix up the parent ptr.
- if (new_parent_ptr) {
- parent_it->second.second = new_parent_ptr;
- } else {
- parent_it->second.second = std::weak_ptr<FakeResourceState>();
- }
-}
-
-void FakeSession::PruneDeletedResourceRefs() {
- // Remove expired resources from the parents map.
- for (auto parent_it = parents_map_.begin(), parent_end = parents_map_.end();
- parent_it != parent_end;) {
- if (parent_it->second.first.expired()) {
- parent_it = parents_map_.erase(parent_it);
- } else {
- ++parent_it;
- }
- }
-
- // Remove expired resurces from the labels map.
- for (auto scene_it = scene_graph_.label_map.begin(),
- scene_end = scene_graph_.label_map.end();
- scene_it != scene_end;) {
- auto erase_it = std::remove_if(
- scene_it->second.begin(), scene_it->second.end(),
- [](const auto& weak_resource) { return weak_resource.expired(); });
- if (erase_it != scene_it->second.end()) {
- scene_it->second.erase(erase_it);
- }
-
- if (scene_it->second.empty()) {
- scene_it = scene_graph_.label_map.erase(scene_it);
- } else {
- ++scene_it;
- }
- }
-}
-
-void FakeSession::ApplyCommands() {
- while (!command_queue_.empty()) {
- auto scenic_command = std::move(command_queue_.front());
- command_queue_.pop_front();
-
- if (!scenic_command.is_gfx()) {
- FML_LOG(FATAL) << "FakeSession: Unexpected non-gfx command (type "
- << scenic_command.Which() << ")";
- continue;
- }
-
- auto& command = scenic_command.gfx();
- switch (command.Which()) {
- case fuchsia::ui::gfx::Command::Tag::kCreateResource:
- ApplyCreateResourceCmd(std::move(command.create_resource()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kReleaseResource:
- ApplyReleaseResourceCmd(std::move(command.release_resource()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kAddChild:
- ApplyAddChildCmd(std::move(command.add_child()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kDetach:
- ApplyDetachCmd(std::move(command.detach()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kDetachChildren:
- ApplyDetachChildrenCmd(std::move(command.detach_children()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetTranslation:
- ApplySetTranslationCmd(std::move(command.set_translation()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetScale:
- ApplySetScaleCmd(std::move(command.set_scale()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetRotation:
- ApplySetRotationCmd(std::move(command.set_rotation()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetAnchor:
- ApplySetAnchorCmd(std::move(command.set_anchor()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetOpacity:
- ApplySetOpacityCmd(command.set_opacity());
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetShape:
- ApplySetShapeCmd(std::move(command.set_shape()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetMaterial:
- ApplySetMaterialCmd(std::move(command.set_material()));
- break;
- case ::fuchsia::ui::gfx::Command::Tag::kSetClipPlanes:
- ApplySetClipPlanesCmd(std::move(command.set_clip_planes()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetHitTestBehavior:
- ApplySetHitTestBehaviorCmd(std::move(command.set_hit_test_behavior()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetSemanticVisibility:
- ApplySetSemanticVisibilityCmd(
- std::move(command.set_semantic_visibility()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetViewProperties:
- ApplySetViewPropertiesCmd(std::move(command.set_view_properties()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetTexture:
- ApplySetTextureCmd(std::move(command.set_texture()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetColor:
- ApplySetColorCmd(std::move(command.set_color()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetEventMask:
- ApplySetEventMaskCmd(std::move(command.set_event_mask()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetLabel:
- ApplySetLabelCmd(std::move(command.set_label()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetEnableViewDebugBounds:
- ApplySetEnableViewDebugBoundsCmd(
- std::move(command.set_enable_view_debug_bounds()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetViewHolderBoundsColor:
- ApplySetViewHolderBoundsColorCmd(
- std::move(command.set_view_holder_bounds_color()));
- break;
- case fuchsia::ui::gfx::Command::Tag::kExportResource:
- NotImplemented_("ExportResourceCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kImportResource:
- NotImplemented_("ImportResourceCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetTag:
- NotImplemented_("SetTagCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetSize:
- NotImplemented_("SetSizeCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSendSizeChangeHintHack:
- NotImplemented_("SendSizeChangedHintHackCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kAddPart:
- NotImplemented_("AddPartCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetClip:
- NotImplemented_("SetClipCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetCamera:
- NotImplemented_("SetCameraCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetCameraTransform:
- NotImplemented_("SetCameraTransformCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetCameraProjection:
- NotImplemented_("SetCameraProjectionCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetStereoCameraProjection:
- NotImplemented_("SetStereoCameraProjectionCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetCameraClipSpaceTransform:
- NotImplemented_("SetCameraClipSpaceTransformCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetCameraPoseBuffer:
- NotImplemented_("SetCameraPoseBufferCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetLightColor:
- NotImplemented_("SetLightColorCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetLightDirection:
- NotImplemented_("SetLightDirectionCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetPointLightPosition:
- NotImplemented_("SetPointLightPositionCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetPointLightFalloff:
- NotImplemented_("SetPointLightFalloffCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kAddLight:
- NotImplemented_("AddLightCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kScene_AddAmbientLight:
- NotImplemented_("Scene_AddAmbientLightCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kScene_AddDirectionalLight:
- NotImplemented_("Scene_AddDirectionalLightCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kScene_AddPointLight:
- NotImplemented_("Scene_AddPointLightCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kDetachLight:
- NotImplemented_("DetachLightCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kDetachLights:
- NotImplemented_("DetachLightsCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kBindMeshBuffers:
- NotImplemented_("BindMeshBuffersCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kAddLayer:
- NotImplemented_("AddLayerCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kRemoveLayer:
- NotImplemented_("RemoveLayerCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kRemoveAllLayers:
- NotImplemented_("RemoveAllLayersCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetLayerStack:
- NotImplemented_("SetLayerStackCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetRenderer:
- NotImplemented_("SetRendererCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetRendererParam:
- NotImplemented_("SetRendererParamCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetDisableClipping:
- NotImplemented_("SetDisableClippingCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetImportFocus:
- NotImplemented_("SetImportFocusCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kTakeSnapshotCmd:
- NotImplemented_("TakeSnapshotCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetDisplayColorConversion:
- NotImplemented_("SetDisplayColorConversionCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetDisplayRotation:
- NotImplemented_("SetDisplayRotationCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::kSetDisplayMinimumRgb:
- NotImplemented_("SetDisplayMinimumRgbCmd");
- break;
- case fuchsia::ui::gfx::Command::Tag::Invalid:
- FML_LOG(FATAL) << "FakeSession found Invalid gfx command";
- break;
- }
- }
-
- // Clean up resource refs after processing commands.
- PruneDeletedResourceRefs();
-}
-
-void FakeSession::ApplyCreateResourceCmd(
- fuchsia::ui::gfx::CreateResourceCmd command) {
- const FakeResourceId resource_id = command.id;
- FML_CHECK(resource_id != 0);
-
- switch (command.resource.Which()) {
- case fuchsia::ui::gfx::ResourceArgs::Tag::kMemory:
- ApplyCreateMemory(resource_id, std::move(command.resource.memory()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kImage:
- ApplyCreateImage(resource_id, std::move(command.resource.image()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kImage2:
- ApplyCreateImage2(resource_id, std::move(command.resource.image2()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kImage3:
- ApplyCreateImage3(resource_id, std::move(command.resource.image3()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kImagePipe2:
- ApplyCreateImagePipe2(resource_id,
- std::move(command.resource.image_pipe2()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kRectangle:
- ApplyCreateRectangle(resource_id,
- std::move(command.resource.rectangle()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kRoundedRectangle:
- ApplyCreateRoundedRectangle(
- resource_id, std::move(command.resource.rounded_rectangle()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kCircle:
- ApplyCreateCircle(resource_id, std::move(command.resource.circle()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kMaterial:
- ApplyCreateMaterial(resource_id, std::move(command.resource.material()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kView:
- ApplyCreateView(resource_id, std::move(command.resource.view()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kView3:
- ApplyCreateView(resource_id, std::move(command.resource.view3()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kViewHolder:
- ApplyCreateViewHolder(resource_id,
- std::move(command.resource.view_holder()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kOpacityNode:
- ApplyCreateOpacityNode(resource_id, command.resource.opacity_node());
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kEntityNode:
- ApplyCreateEntityNode(resource_id,
- std::move(command.resource.entity_node()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kShapeNode:
- ApplyCreateShapeNode(resource_id,
- std::move(command.resource.shape_node()));
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kBuffer:
- NotImplemented_("CreateBufferResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kScene:
- NotImplemented_("CreateSceneResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kCamera:
- NotImplemented_("CreateCameraResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kStereoCamera:
- NotImplemented_("CreateStereoCameraResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kRenderer:
- NotImplemented_("CreateRendererResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kAmbientLight:
- NotImplemented_("CreateAmbientLightResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kDirectionalLight:
- NotImplemented_("CreateDirectionalLightResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kPointLight:
- NotImplemented_("CreatePointLightResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kMesh:
- NotImplemented_("CreateMeshResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kClipNode:
- NotImplemented_("CreateClipNodeResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kCompositor:
- NotImplemented_("CreateCompositorResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kDisplayCompositor:
- NotImplemented_("CreateDisplayCompositorResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kLayerStack:
- NotImplemented_("CreateLayerStackResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kLayer:
- NotImplemented_("CreateLayerResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::kVariable:
- NotImplemented_("CreateVariableResource");
- break;
- case fuchsia::ui::gfx::ResourceArgs::Tag::Invalid:
- FML_LOG(FATAL) << "FakeSession found Invalid CreateResource command";
- break;
- default:
- FML_UNREACHABLE();
- }
-}
-
-void FakeSession::ApplyReleaseResourceCmd(
- fuchsia::ui::gfx::ReleaseResourceCmd command) {
- auto resource_ptr = GetResource(command.id);
- if (ResourceIs<FakeViewState>(*resource_ptr)) {
- FML_CHECK(scene_graph_.root_view_id == resource_ptr->id);
- scene_graph_.root_view_id = kInvalidFakeResourceId;
- }
-
- scene_graph_.resource_map.erase(command.id);
-}
-
-void FakeSession::ApplyAddChildCmd(fuchsia::ui::gfx::AddChildCmd command) {
- auto parent_node_ptr = GetResource(command.node_id);
- FML_CHECK(ResourceIsNode(*parent_node_ptr) ||
- ResourceIs<FakeViewState>(*parent_node_ptr));
-
- auto child_node_ptr = GetResource(command.child_id);
- FML_CHECK(ResourceIsNode(*child_node_ptr));
-
- // Add the Node as a child of the new parent.
- std::visit(
- [&child_node_ptr](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (is_node_v<T>) {
- state.node_state.children.emplace_back(child_node_ptr);
- } else if constexpr (std::is_same_v<T, FakeViewState>) {
- state.children.emplace_back(child_node_ptr);
- } else {
- FML_CHECK(false);
- }
- },
- parent_node_ptr->state);
-
- // Remove the Node as a child of the old parent and fix up the parent ptr.
- DetachResourceFromParent(child_node_ptr, parent_node_ptr);
-}
-
-void FakeSession::ApplyDetachCmd(fuchsia::ui::gfx::DetachCmd command) {
- auto resource_ptr = GetResource(command.id);
- FML_CHECK(ResourceIsNode(*resource_ptr));
-
- DetachResourceFromParent(std::move(resource_ptr));
-}
-
-void FakeSession::ApplyDetachChildrenCmd(
- fuchsia::ui::gfx::DetachChildrenCmd command) {
- auto resource_ptr = GetResource(command.node_id);
- FML_CHECK(ResourceIsNode(*resource_ptr));
-
- std::visit(
- [this](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (is_node_v<T>) {
- for (auto& child : state.node_state.children) {
- DetachResourceFromParent(child);
- }
- state.node_state.children.clear();
- } else {
- FML_CHECK(false);
- }
- },
- resource_ptr->state);
-}
-
-void FakeSession::ApplySetTranslationCmd(
- fuchsia::ui::gfx::SetTranslationCmd command) {
- auto resource_ptr = GetResource(command.id);
- FML_CHECK(ResourceIsNode(*resource_ptr));
-
- const std::array<float, 3> translation = {
- command.value.value.x, command.value.value.y, command.value.value.z};
- std::visit(
- [&translation](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (is_node_v<T>) {
- state.node_state.translation_vector = translation;
- } else {
- FML_CHECK(false);
- }
- },
- resource_ptr->state);
-}
-
-void FakeSession::ApplySetScaleCmd(fuchsia::ui::gfx::SetScaleCmd command) {
- auto resource_ptr = GetResource(command.id);
- FML_CHECK(ResourceIsNode(*resource_ptr));
-
- const std::array<float, 3> scale = {
- command.value.value.x, command.value.value.y, command.value.value.z};
- std::visit(
- [&scale](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (is_node_v<T>) {
- state.node_state.scale_vector = scale;
- } else {
- FML_CHECK(false);
- }
- },
- resource_ptr->state);
-}
-
-void FakeSession::ApplySetRotationCmd(
- fuchsia::ui::gfx::SetRotationCmd command) {
- auto resource_ptr = GetResource(command.id);
- FML_CHECK(ResourceIsNode(*resource_ptr));
-
- const std::array<float, 4> rotation = {
- command.value.value.x, command.value.value.y, command.value.value.z,
- command.value.value.w};
- std::visit(
- [&rotation](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (is_node_v<T>) {
- state.node_state.rotation_quaternion = rotation;
- } else {
- FML_CHECK(false);
- }
- },
- resource_ptr->state);
-}
-
-void FakeSession::ApplySetAnchorCmd(fuchsia::ui::gfx::SetAnchorCmd command) {
- auto resource_ptr = GetResource(command.id);
- FML_CHECK(ResourceIsNode(*resource_ptr));
-
- const std::array<float, 3> anchor = {
- command.value.value.x, command.value.value.y, command.value.value.z};
- std::visit(
- [&anchor](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (is_node_v<T>) {
- state.node_state.anchor_vector = anchor;
- } else {
- FML_CHECK(false);
- }
- },
- resource_ptr->state);
-}
-
-void FakeSession::ApplySetOpacityCmd(fuchsia::ui::gfx::SetOpacityCmd command) {
- auto resource_ptr = GetResource(command.node_id);
- FML_CHECK(ResourceIs<FakeOpacityNodeState>(*resource_ptr));
-
- const bool opacity = command.opacity;
- std::visit(
- [opacity](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (std::is_same_v<T, FakeOpacityNodeState>) {
- state.opacity = opacity;
- } else {
- FML_CHECK(false);
- }
- },
- resource_ptr->state);
-}
-
-void FakeSession::ApplySetShapeCmd(fuchsia::ui::gfx::SetShapeCmd command) {
- auto shape_node_ptr = GetResource(command.node_id);
- FML_CHECK(ResourceIs<FakeShapeNodeState>(*shape_node_ptr));
- auto* shape_node_state =
- std::get_if<FakeShapeNodeState>(&shape_node_ptr->state);
- FML_CHECK(shape_node_state != nullptr);
- auto shape_ptr = GetResource(command.shape_id);
- FML_CHECK(ResourceIs<FakeShapeState>(*shape_ptr));
-
- shape_node_state->shape = shape_ptr;
-}
-
-void FakeSession::ApplySetMaterialCmd(
- fuchsia::ui::gfx::SetMaterialCmd command) {
- auto shape_node_ptr = GetResource(command.node_id);
- FML_CHECK(ResourceIs<FakeShapeNodeState>(*shape_node_ptr));
- auto* shape_node_state =
- std::get_if<FakeShapeNodeState>(&shape_node_ptr->state);
- FML_CHECK(shape_node_state != nullptr);
- auto material_ptr = GetResource(command.material_id);
- FML_CHECK(ResourceIs<FakeMaterialState>(*material_ptr));
-
- shape_node_state->material = material_ptr;
-}
-
-void FakeSession::ApplySetClipPlanesCmd(
- fuchsia::ui::gfx::SetClipPlanesCmd command) {
- auto node_ptr = GetResource(command.node_id);
- FML_CHECK(ResourceIs<FakeEntityNodeState>(*node_ptr));
-
- std::vector<FakeEntityNodeState::ClipPlane> clip_planes;
- for (auto& clip_plane : command.clip_planes) {
- clip_planes.emplace_back(FakeEntityNodeState::ClipPlane{
- .dir = {clip_plane.dir.x, clip_plane.dir.y, clip_plane.dir.z},
- .dist = clip_plane.dist,
- });
- }
- std::visit(
- [clip_planes = std::move(clip_planes)](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (std::is_same_v<T, FakeEntityNodeState>) {
- state.clip_planes = std::move(clip_planes);
- } else {
- FML_CHECK(false);
- }
- },
- node_ptr->state);
-}
-
-void FakeSession::ApplySetViewPropertiesCmd(
- fuchsia::ui::gfx::SetViewPropertiesCmd command) {
- auto view_holder_ptr = GetResource(command.view_holder_id);
- FML_CHECK(ResourceIs<FakeViewHolderState>(*view_holder_ptr));
- auto* view_holder_state =
- std::get_if<FakeViewHolderState>(&view_holder_ptr->state);
- FML_CHECK(view_holder_state != nullptr);
-
- view_holder_state->properties = command.properties;
-}
-
-void FakeSession::ApplySetHitTestBehaviorCmd(
- fuchsia::ui::gfx::SetHitTestBehaviorCmd command) {
- auto node_ptr = GetResource(command.node_id);
- FML_CHECK(ResourceIsNode(*node_ptr));
-
- const bool hit_testable =
- command.hit_test_behavior == fuchsia::ui::gfx::HitTestBehavior::kDefault;
- std::visit(
- [hit_testable](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (is_node_v<T>) {
- state.node_state.hit_testable = hit_testable;
- } else {
- FML_CHECK(false);
- }
- },
- node_ptr->state);
-}
-
-void FakeSession::ApplySetSemanticVisibilityCmd(
- fuchsia::ui::gfx::SetSemanticVisibilityCmd command) {
- auto node_ptr = GetResource(command.node_id);
- FML_CHECK(ResourceIsNode(*node_ptr));
-
- const bool semantic_visibility = command.visible;
- std::visit(
- [semantic_visibility](auto&& state) {
- using T = std::decay_t<decltype(state)>;
- if constexpr (is_node_v<T>) {
- state.node_state.semantically_visible = semantic_visibility;
- } else {
- FML_CHECK(false);
- }
- },
- node_ptr->state);
-}
-
-void FakeSession::ApplySetTextureCmd(fuchsia::ui::gfx::SetTextureCmd command) {
- auto material_ptr = GetResource(command.material_id);
- FML_CHECK(ResourceIs<FakeMaterialState>(*material_ptr));
- auto* material_state = std::get_if<FakeMaterialState>(&material_ptr->state);
- FML_CHECK(material_state != nullptr);
- auto image_ptr = GetResource(command.texture_id);
- FML_CHECK(ResourceIs<FakeImageState>(*image_ptr));
-
- material_state->image = image_ptr;
-}
-
-void FakeSession::ApplySetColorCmd(fuchsia::ui::gfx::SetColorCmd command) {
- auto material_ptr = GetResource(command.material_id);
- FML_CHECK(ResourceIs<FakeMaterialState>(*material_ptr));
- auto* material_state = std::get_if<FakeMaterialState>(&material_ptr->state);
- FML_CHECK(material_state != nullptr);
-
- material_state->color = {(command.color.value.red * 1.f) / 255.f,
- (command.color.value.green * 1.f) / 255.f,
- (command.color.value.blue * 1.f) / 255.f,
- (command.color.value.alpha * 1.f) / 255.f};
-}
-
-void FakeSession::ApplySetEventMaskCmd(
- fuchsia::ui::gfx::SetEventMaskCmd command) {
- auto resource_ptr = GetResource(command.id);
-
- resource_ptr->event_mask = command.event_mask;
-}
-
-void FakeSession::ApplySetLabelCmd(fuchsia::ui::gfx::SetLabelCmd command) {
- auto resource_ptr = GetResource(command.id);
-
- // Erase from old spot in the labels map.
- auto current_label_it = scene_graph_.label_map.find(resource_ptr->label);
- FML_CHECK(current_label_it != scene_graph_.label_map.end());
- auto current_erase_it = std::remove_if(
- current_label_it->second.begin(), current_label_it->second.end(),
- [&resource_ptr](const auto& weak_resource) {
- return resource_ptr == weak_resource.lock();
- });
- FML_CHECK(current_erase_it != current_label_it->second.end());
- current_label_it->second.erase(current_erase_it);
-
- // Add to new spot in labels map.
- auto new_label_it = scene_graph_.label_map.find(command.label);
- if (new_label_it == scene_graph_.label_map.end()) {
- auto [emplace_it, current_label_success] =
- scene_graph_.label_map.emplace(std::make_pair(
- command.label, std::vector<std::weak_ptr<FakeResourceState>>()));
- FML_CHECK(current_label_success);
- new_label_it = emplace_it;
- }
- new_label_it->second.emplace_back(resource_ptr);
-
- resource_ptr->label = std::move(command.label);
-}
-
-void FakeSession::ApplySetEnableViewDebugBoundsCmd(
- fuchsia::ui::gfx::SetEnableDebugViewBoundsCmd command) {
- auto view_ptr = GetResource(command.view_id);
- FML_CHECK(ResourceIs<FakeViewState>(*view_ptr));
- auto* view_state = std::get_if<FakeViewState>(&view_ptr->state);
- FML_CHECK(view_state != nullptr);
-
- view_state->enable_debug_bounds = command.enable;
-}
-
-void FakeSession::ApplySetViewHolderBoundsColorCmd(
- fuchsia::ui::gfx::SetViewHolderBoundsColorCmd command) {
- auto view_holder_ptr = GetResource(command.view_holder_id);
- FML_CHECK(ResourceIs<FakeViewHolderState>(*view_holder_ptr));
- auto* view_holder_state =
- std::get_if<FakeViewHolderState>(&view_holder_ptr->state);
- FML_CHECK(view_holder_state != nullptr);
-
- view_holder_state->bounds_color = {command.color.value.red,
- command.color.value.green,
- command.color.value.blue, 1.f};
-}
-
-void FakeSession::ApplyCreateMemory(FakeResourceId id,
- fuchsia::ui::gfx::MemoryArgs args) {
- zx_koid_t vmo_koid = GetKoid(args.vmo.get());
- AddResource(
- {.id = id,
- .state = FakeMemoryState{
- .vmo = {std::move(args.vmo), vmo_koid},
- .allocation_size = args.allocation_size,
- .is_device_memory = (args.memory_type ==
- fuchsia::images::MemoryType::VK_DEVICE_MEMORY),
- }});
-}
-
-void FakeSession::ApplyCreateImage(FakeResourceId id,
- fuchsia::ui::gfx::ImageArgs args) {
- AddResource({.id = id,
- .state = FakeImageState{
- .image_def =
- FakeImageState::ImageDef{
- .info = std::move(args.info),
- .memory_offset = args.memory_offset,
- },
- }});
-
- // Hook up the memory resource to the image
- auto image_ptr = GetResource(id);
- FML_CHECK(ResourceIs<FakeImageState>(*image_ptr));
- auto* image_state = std::get_if<FakeImageState>(&image_ptr->state);
- FML_CHECK(image_state != nullptr);
- auto memory_ptr = GetResource(args.memory_id);
- FML_CHECK(ResourceIs<FakeMemoryState>(*memory_ptr));
-
- image_state->memory = memory_ptr;
-}
-
-void FakeSession::ApplyCreateImage2(FakeResourceId id,
- fuchsia::ui::gfx::ImageArgs2 args) {
- AddResource(
- {.id = id,
- .state = FakeImageState{
- .image_def =
- FakeImageState::Image2Def{
- .buffer_collection_id = args.buffer_collection_id,
- .buffer_collection_index = args.buffer_collection_index,
- .width = args.width,
- .height = args.height,
- },
- }});
-}
-
-void FakeSession::ApplyCreateImage3(FakeResourceId id,
- fuchsia::ui::gfx::ImageArgs3 args) {
- zx_koid_t import_token_koid = GetKoid(args.import_token.value.get());
- AddResource(
- {.id = id,
- .state = FakeImageState{
- .image_def =
- FakeImageState::Image3Def{
- .import_token = {std::move(args.import_token),
- import_token_koid},
- .buffer_collection_index = args.buffer_collection_index,
- .width = args.width,
- .height = args.height,
- },
- }});
-}
-
-void FakeSession::ApplyCreateImagePipe2(FakeResourceId id,
- fuchsia::ui::gfx::ImagePipe2Args args) {
- zx_koid_t image_pipe_request_koid =
- GetKoid(args.image_pipe_request.channel().get());
- AddResource(
- {.id = id,
- .state = FakeImageState{
- .image_def =
- FakeImageState::ImagePipe2Def{
- .image_pipe_request = {std::move(args.image_pipe_request),
- image_pipe_request_koid},
- },
- }});
-}
-
-void FakeSession::ApplyCreateRectangle(FakeResourceId id,
- fuchsia::ui::gfx::RectangleArgs args) {
- FML_CHECK(args.width.is_vector1());
- FML_CHECK(args.height.is_vector1());
-
- AddResource({.id = id,
- .state = FakeShapeState{
- .shape_def =
- FakeShapeState::RectangleDef{
- .width = args.width.vector1(),
- .height = args.height.vector1(),
- },
- }});
-}
-
-void FakeSession::ApplyCreateRoundedRectangle(
- FakeResourceId id,
- fuchsia::ui::gfx::RoundedRectangleArgs args) {
- FML_CHECK(args.width.is_vector1());
- FML_CHECK(args.height.is_vector1());
- FML_CHECK(args.top_left_radius.is_vector1());
- FML_CHECK(args.top_right_radius.is_vector1());
- FML_CHECK(args.bottom_right_radius.is_vector1());
- FML_CHECK(args.bottom_left_radius.is_vector1());
-
- AddResource(
- {.id = id,
- .state = FakeShapeState{
- .shape_def =
- FakeShapeState::RoundedRectangleDef{
- .width = args.width.vector1(),
- .height = args.height.vector1(),
- .top_left_radius = args.top_left_radius.vector1(),
- .top_right_radius = args.top_right_radius.vector1(),
- .bottom_right_radius = args.bottom_right_radius.vector1(),
- .bottom_left_radius = args.bottom_left_radius.vector1(),
- },
- }});
-}
-
-void FakeSession::ApplyCreateCircle(FakeResourceId id,
- fuchsia::ui::gfx::CircleArgs args) {
- FML_CHECK(args.radius.is_vector1());
-
- AddResource({.id = id,
- .state = FakeShapeState{
- .shape_def =
- FakeShapeState::CircleDef{
- .radius = args.radius.vector1(),
- },
- }});
-}
-
-void FakeSession::ApplyCreateMaterial(FakeResourceId id,
- fuchsia::ui::gfx::MaterialArgs args) {
- AddResource({
- .id = id,
- .state = FakeMaterialState{},
- });
-}
-
-void FakeSession::ApplyCreateView(FakeResourceId id,
- fuchsia::ui::gfx::ViewArgs args) {
- FML_CHECK(scene_graph_.root_view_id == kInvalidFakeResourceId);
-
- zx_koid_t token_koid = GetKoid(args.token.value.get());
- AddResource({.id = id,
- .state = FakeViewState{
- .token = {std::move(args.token), token_koid},
- .debug_name = std::string(args.debug_name->c_str(),
- args.debug_name->length()),
- }});
-}
-
-void FakeSession::ApplyCreateView(FakeResourceId id,
- fuchsia::ui::gfx::ViewArgs3 args) {
- zx_koid_t token_koid = GetKoid(args.token.value.get());
- zx_koid_t control_ref_koid = GetKoid(args.control_ref.reference.get());
- zx_koid_t view_ref_koid = GetKoid(args.view_ref.reference.get());
- AddResource(
- {.id = id,
- .state = FakeViewState{
- .token = {std::move(args.token), token_koid},
- .control_ref = {std::move(args.control_ref), control_ref_koid},
- .view_ref = {std::move(args.view_ref), view_ref_koid},
- .debug_name =
- std::string(args.debug_name->c_str(), args.debug_name->length()),
- }});
-}
-
-void FakeSession::ApplyCreateViewHolder(FakeResourceId id,
- fuchsia::ui::gfx::ViewHolderArgs args) {
- zx_koid_t token_koid = GetKoid(args.token.value.get());
- AddResource({
- .id = id,
- .state =
- FakeViewHolderState{
- .token = {std::move(args.token), token_koid},
- .debug_name = std::string(args.debug_name->c_str(),
- args.debug_name->length()),
- },
- });
-}
-
-void FakeSession::ApplyCreateEntityNode(FakeResourceId id,
- fuchsia::ui::gfx::EntityNodeArgs args) {
- AddResource({
- .id = id,
- .state = FakeEntityNodeState{},
- });
-}
-
-void FakeSession::ApplyCreateOpacityNode(
- FakeResourceId id,
- fuchsia::ui::gfx::OpacityNodeArgsHACK args) {
- AddResource({
- .id = id,
- .state = FakeOpacityNodeState{},
- });
-}
-
-void FakeSession::ApplyCreateShapeNode(FakeResourceId id,
- fuchsia::ui::gfx::ShapeNodeArgs args) {
- AddResource({
- .id = id,
- .state = FakeShapeNodeState{},
- });
-}
-
-} // namespace flutter_runner::testing
diff --git a/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_session.h b/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_session.h
deleted file mode 100644
index 9f5ecd9..0000000
--- a/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_session.h
+++ /dev/null
@@ -1,240 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_SESSION_H_
-#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_SESSION_H_
-
-#include <fuchsia/images/cpp/fidl.h>
-#include <fuchsia/scenic/scheduling/cpp/fidl.h>
-#include <fuchsia/sysmem/cpp/fidl.h>
-#include <fuchsia/ui/gfx/cpp/fidl.h>
-#include <fuchsia/ui/scenic/cpp/fidl.h>
-#include <fuchsia/ui/scenic/cpp/fidl_test_base.h>
-#include <lib/async/dispatcher.h>
-#include <lib/fidl/cpp/binding.h>
-#include <lib/fidl/cpp/interface_handle.h>
-#include <lib/fidl/cpp/interface_request.h>
-
-#include <deque>
-#include <functional>
-#include <memory>
-#include <string>
-#include <unordered_map>
-#include <utility> // For std::pair
-#include <vector>
-
-#include "flutter/fml/macros.h"
-
-#include "fake_resources.h"
-
-namespace flutter_runner::testing {
-
-// A lightweight fake implementation of the scenic Session API, also called
-// the "gfx API". The fake has no side effects besides mutating its own
-// internal state.
-//
-// The fake allows tests to do a few things that would be difficult using either
-// a mock implementation or the real implementation:
-// + It allows the user to hook `Present` invocations and respond with
-// stubbed-out `FuturePresentationTimes`, but more crucially it mimics the
-// real scenic behavior of only processing commands when a `Present` is
-// invoked.
-// + It allows the user to inspect a snapshot of the session's local scene
-// graph at any moment in time, via the `SceneGraph()` accessor.
-// + The resources returned by `SceneGraph()` that the test uses for
-// inspection are decoupled from the resources managed internally by the
-// `FakeSession` itself -- they are a snapshot of the scene graph at that
-// moment in time, with all snapshot state being cloned from the underlying
-// scene graph state. This allows the `FakeSession` and test to naturally use
-// `shared_ptr` for reference counting and mimic the real scenic behavior
-// exactly, instead of an awkward index-based API.
-// + It stores the various session resources generated by commands into a
-// std::unordered_map, and also correctly manages the resource lifetimes via
-// reference counting. This allows a resource to stay alive if its parent
-// still holds a reference to it, in the same way the real scenic
-// implementation would.
-//
-// Limitations:
-// +Error handling / session disconnection is still WIP. FakeSession will
-// likely generate a CHECK in any place where the real scenic would disconnect
-// the session or send a ScenicError.
-// +Deprecated / obsolete commands are not handled.
-// +Input is not handled.
-// +Rendering is not handled.
-// +Cross-session links are not handled; the FakeSession only stores the
-// tokens provided to it in a FakeResourceState.
-class FakeSession : public fuchsia::ui::scenic::testing::Session_TestBase {
- public:
- using PresentHandler =
- std::function<fuchsia::images::PresentationInfo(uint64_t,
- std::vector<zx::event>,
- std::vector<zx::event>)>;
- using Present2Handler =
- std::function<fuchsia::scenic::scheduling::FuturePresentationTimes(
- fuchsia::ui::scenic::Present2Args)>;
- using RequestPresentationTimesHandler =
- std::function<fuchsia::scenic::scheduling::FuturePresentationTimes(
- int64_t)>;
- using SessionAndListenerClientPair =
- std::pair<fidl::InterfaceHandle<fuchsia::ui::scenic::Session>,
- fidl::InterfaceRequest<fuchsia::ui::scenic::SessionListener>>;
-
- FakeSession();
- ~FakeSession() override = default;
-
- bool is_bound() const { return binding_.is_bound() && listener_.is_bound(); }
-
- const std::string& debug_name() const { return debug_name_; }
-
- const std::deque<fuchsia::ui::scenic::Command>& command_queue() const {
- return command_queue_;
- }
-
- // Generate a snapshot of the underlying scene graph for test inspection.
- FakeSceneGraph SceneGraph() const {
- return SceneGraphFromState(scene_graph_);
- }
-
- // Bind this session's FIDL channels to the `dispatcher` and allow processing
- // of incoming FIDL requests.
- SessionAndListenerClientPair Bind(async_dispatcher_t* dispatcher = nullptr);
-
- // Set a handler for `Present`-related FIDL calls' return values.
- void SetPresentHandler(PresentHandler present_handler);
- void SetPresent2Handler(Present2Handler present2_handler);
- void SetRequestPresentationTimesHandler(
- RequestPresentationTimesHandler request_presentation_times_handler);
-
- // Call after a successful `Present` or `Present2` to fire an
- // `OnFramePresented` event, which simulates the frame being displayed.
- void FireOnFramePresentedEvent(
- fuchsia::scenic::scheduling::FramePresentedInfo frame_presented_info);
-
- // Disconnect the session with an error.
- // TODO: Call this internally upon command error, instead of CHECK'ing.
- void DisconnectSession();
-
- private:
- // |fuchsia::ui::scenic::testing::Session_TestBase|
- void NotImplemented_(const std::string& name) override;
-
- // |fuchsia::ui::scenic::Session|
- void Enqueue(std::vector<fuchsia::ui::scenic::Command> cmds) override;
-
- // |fuchsia::ui::scenic::Session|
- void Present(uint64_t presentation_time,
- std::vector<zx::event> acquire_fences,
- std::vector<zx::event> release_fences,
- PresentCallback callback) override;
-
- // |fuchsia::ui::scenic::Session|
- void Present2(fuchsia::ui::scenic::Present2Args args,
- Present2Callback callback) override;
-
- // |fuchsia::ui::scenic::Session|
- void RequestPresentationTimes(
- int64_t requested_prediction_span,
- RequestPresentationTimesCallback callback) override;
-
- // |fuchsia::ui::scenic::Session|
- void RegisterBufferCollection(
- uint32_t buffer_id,
- fidl::InterfaceHandle<fuchsia::sysmem::BufferCollectionToken> token)
- override;
-
- // |fuchsia::ui::scenic::Session|
- void DeregisterBufferCollection(uint32_t buffer_id) override;
-
- // |fuchsia::ui::scenic::Session|
- void SetDebugName(std::string debug_name) override;
-
- // Resource management.
- std::shared_ptr<FakeResourceState> GetResource(FakeResourceId id);
- void AddResource(FakeResourceState&& resource);
- void DetachResourceFromParent(
- std::shared_ptr<FakeResourceState> resource_ptr,
- std::shared_ptr<FakeResourceState> new_parent_ptr = nullptr);
- void PruneDeletedResourceRefs();
-
- // Apply queued commands and mutate the resource map.
- void ApplyCommands();
- void ApplyCreateResourceCmd(fuchsia::ui::gfx::CreateResourceCmd command);
- void ApplyReleaseResourceCmd(fuchsia::ui::gfx::ReleaseResourceCmd command);
- void ApplyAddChildCmd(fuchsia::ui::gfx::AddChildCmd command);
- void ApplyDetachCmd(fuchsia::ui::gfx::DetachCmd command);
- void ApplyDetachChildrenCmd(fuchsia::ui::gfx::DetachChildrenCmd command);
- void ApplySetTranslationCmd(fuchsia::ui::gfx::SetTranslationCmd command);
- void ApplySetScaleCmd(fuchsia::ui::gfx::SetScaleCmd command);
- void ApplySetRotationCmd(fuchsia::ui::gfx::SetRotationCmd command);
- void ApplySetAnchorCmd(fuchsia::ui::gfx::SetAnchorCmd command);
- void ApplySetOpacityCmd(fuchsia::ui::gfx::SetOpacityCmd command);
- void ApplySetShapeCmd(fuchsia::ui::gfx::SetShapeCmd command);
- void ApplySetMaterialCmd(fuchsia::ui::gfx::SetMaterialCmd command);
- void ApplySetClipPlanesCmd(fuchsia::ui::gfx::SetClipPlanesCmd command);
- void ApplySetViewPropertiesCmd(
- fuchsia::ui::gfx::SetViewPropertiesCmd command);
- void ApplySetHitTestBehaviorCmd(
- fuchsia::ui::gfx::SetHitTestBehaviorCmd command);
- void ApplySetSemanticVisibilityCmd(
- fuchsia::ui::gfx::SetSemanticVisibilityCmd command);
- void ApplySetTextureCmd(fuchsia::ui::gfx::SetTextureCmd command);
- void ApplySetColorCmd(fuchsia::ui::gfx::SetColorCmd command);
- void ApplySetEventMaskCmd(fuchsia::ui::gfx::SetEventMaskCmd command);
- void ApplySetLabelCmd(fuchsia::ui::gfx::SetLabelCmd command);
- void ApplySetEnableViewDebugBoundsCmd(
- fuchsia::ui::gfx::SetEnableDebugViewBoundsCmd command);
- void ApplySetViewHolderBoundsColorCmd(
- fuchsia::ui::gfx::SetViewHolderBoundsColorCmd command);
- void ApplyCreateMemory(FakeResourceId id, fuchsia::ui::gfx::MemoryArgs args);
- void ApplyCreateImage(FakeResourceId id, fuchsia::ui::gfx::ImageArgs args);
- void ApplyCreateImage2(FakeResourceId id, fuchsia::ui::gfx::ImageArgs2 args);
- void ApplyCreateImage3(FakeResourceId id, fuchsia::ui::gfx::ImageArgs3 args);
- void ApplyCreateImagePipe2(FakeResourceId id,
- fuchsia::ui::gfx::ImagePipe2Args args);
- void ApplyCreateRectangle(FakeResourceId id,
- fuchsia::ui::gfx::RectangleArgs args);
- void ApplyCreateRoundedRectangle(FakeResourceId id,
- fuchsia::ui::gfx::RoundedRectangleArgs args);
- void ApplyCreateCircle(FakeResourceId id, fuchsia::ui::gfx::CircleArgs args);
- void ApplyCreateMaterial(FakeResourceId id,
- fuchsia::ui::gfx::MaterialArgs args);
- void ApplyCreateView(FakeResourceId id, fuchsia::ui::gfx::ViewArgs args);
- void ApplyCreateViewHolder(FakeResourceId id,
- fuchsia::ui::gfx::ViewHolderArgs args);
- void ApplyCreateView(FakeResourceId id, fuchsia::ui::gfx::ViewArgs3 args);
- void ApplyCreateEntityNode(FakeResourceId id,
- fuchsia::ui::gfx::EntityNodeArgs args);
- void ApplyCreateOpacityNode(FakeResourceId id,
- fuchsia::ui::gfx::OpacityNodeArgsHACK args);
- void ApplyCreateShapeNode(FakeResourceId id,
- fuchsia::ui::gfx::ShapeNodeArgs args);
-
- fidl::Binding<fuchsia::ui::scenic::Session> binding_;
- fuchsia::ui::scenic::SessionListenerPtr listener_;
-
- std::string debug_name_;
-
- FakeSceneGraphState scene_graph_;
- std::deque<fuchsia::ui::scenic::Command> command_queue_;
-
- // This map is used to cache parent refs for `AddChildCmd`.
- //
- // Ideally we would like to map weak(parent) -> weak(child), but std::weak_ptr
- // cannot be the Key for an associative container. Instead we key on the raw
- // parent pointer and store pair(weak(parent), weak(child)) in the map.
- std::unordered_map<FakeResourceState*,
- std::pair<std::weak_ptr<FakeResourceState>,
- std::weak_ptr<FakeResourceState>>>
- parents_map_;
-
- PresentHandler present_handler_;
- Present2Handler present2_handler_;
- RequestPresentationTimesHandler request_presentation_times_handler_;
-
- FML_DISALLOW_COPY_AND_ASSIGN(FakeSession);
-};
-
-} // namespace flutter_runner::testing
-
-#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_SESSION_H_
diff --git a/shell/platform/fuchsia/flutter/tests/gfx_external_view_embedder_unittests.cc b/shell/platform/fuchsia/flutter/tests/gfx_external_view_embedder_unittests.cc
deleted file mode 100644
index eba9a2d..0000000
--- a/shell/platform/fuchsia/flutter/tests/gfx_external_view_embedder_unittests.cc
+++ /dev/null
@@ -1,866 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "flutter/shell/platform/fuchsia/flutter/gfx_external_view_embedder.h"
-
-#include <fuchsia/sysmem/cpp/fidl.h>
-#include <fuchsia/ui/gfx/cpp/fidl.h>
-#include <fuchsia/ui/scenic/cpp/fidl.h>
-#include <fuchsia/ui/views/cpp/fidl.h>
-#include <lib/async-testing/test_loop.h>
-#include <lib/async/dispatcher.h>
-#include <lib/fidl/cpp/interface_request.h>
-#include <lib/fidl/cpp/synchronous_interface_ptr.h>
-#include <lib/inspect/cpp/inspect.h>
-#include <lib/ui/scenic/cpp/commands.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
-#include <lib/ui/scenic/cpp/view_token_pair.h>
-
-#include <algorithm>
-#include <cstdint>
-#include <functional>
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "flutter/flow/embedded_views.h"
-#include "flutter/fml/logging.h"
-#include "flutter/fml/time/time_delta.h"
-#include "flutter/fml/time/time_point.h"
-#include "third_party/skia/include/core/SkSize.h"
-#include "third_party/skia/include/core/SkSurface.h"
-
-#include "fakes/scenic/fake_resources.h"
-#include "fakes/scenic/fake_session.h"
-#include "flutter/shell/platform/fuchsia/flutter/surface_producer.h"
-
-#include "gmock/gmock.h" // For EXPECT_THAT and matchers
-#include "gtest/gtest.h"
-
-using fuchsia::scenic::scheduling::FramePresentedInfo;
-using fuchsia::scenic::scheduling::FuturePresentationTimes;
-using fuchsia::scenic::scheduling::PresentReceivedInfo;
-using ::testing::_;
-using ::testing::ElementsAre;
-using ::testing::FieldsAre;
-using ::testing::IsEmpty;
-using ::testing::IsNull;
-using ::testing::Matcher;
-using ::testing::Pointee;
-using ::testing::SizeIs;
-using ::testing::VariantWith;
-
-namespace flutter_runner::testing {
-namespace {
-
-class FakeSurfaceProducerSurface : public SurfaceProducerSurface {
- public:
- explicit FakeSurfaceProducerSurface(scenic::Session* session,
- const SkISize& size,
- uint32_t buffer_id)
- : session_(session),
- surface_(SkSurfaces::Null(size.width(), size.height())),
- buffer_id_(buffer_id) {
- FML_CHECK(session_);
- FML_CHECK(buffer_id_ != 0);
-
- fuchsia::sysmem::BufferCollectionTokenSyncPtr token;
- buffer_binding_ = token.NewRequest();
-
- image_id_ = session_->AllocResourceId();
- session_->RegisterBufferCollection(buffer_id_, std::move(token));
- session_->Enqueue(scenic::NewCreateImage2Cmd(
- image_id_, surface_->width(), surface_->height(), buffer_id_, 0));
- }
- ~FakeSurfaceProducerSurface() override {
- session_->DeregisterBufferCollection(buffer_id_);
- session_->Enqueue(scenic::NewReleaseResourceCmd(image_id_));
- }
-
- bool IsValid() const override { return true; }
-
- SkISize GetSize() const override {
- return SkISize::Make(surface_->width(), surface_->height());
- }
-
- void SetImageId(uint32_t image_id) override { FAIL(); }
- uint32_t GetImageId() override { return image_id_; }
-
- sk_sp<SkSurface> GetSkiaSurface() const override { return surface_; }
-
- fuchsia::ui::composition::BufferCollectionImportToken
- GetBufferCollectionImportToken() override {
- return fuchsia::ui::composition::BufferCollectionImportToken{};
- }
-
- zx::event GetAcquireFence() override { return zx::event{}; }
-
- zx::event GetReleaseFence() override { return zx::event{}; }
-
- void SetReleaseImageCallback(
- ReleaseImageCallback release_image_callback) override {}
-
- size_t AdvanceAndGetAge() override { return 0; }
- bool FlushSessionAcquireAndReleaseEvents() override { return true; }
- void SignalWritesFinished(
- const std::function<void(void)>& on_writes_committed) override {}
-
- private:
- scenic::Session* session_;
-
- sk_sp<SkSurface> surface_;
-
- fidl::InterfaceRequest<fuchsia::sysmem::BufferCollectionToken>
- buffer_binding_;
- FakeResourceId image_id_{kInvalidFakeResourceId};
- uint32_t buffer_id_{0};
-};
-
-class FakeSurfaceProducer : public SurfaceProducer {
- public:
- explicit FakeSurfaceProducer(scenic::Session* session) : session_(session) {}
- ~FakeSurfaceProducer() override = default;
-
- // |SurfaceProducer|
- GrDirectContext* gr_context() const override { return nullptr; }
-
- // |SurfaceProducer|
- std::unique_ptr<SurfaceProducerSurface> ProduceOffscreenSurface(
- const SkISize& size) override {
- return nullptr;
- }
-
- // |SurfaceProducer|
- std::unique_ptr<SurfaceProducerSurface> ProduceSurface(
- const SkISize& size) override {
- return std::make_unique<FakeSurfaceProducerSurface>(session_, size,
- buffer_id_++);
- }
-
- // |SurfaceProducer|
- void SubmitSurfaces(
- std::vector<std::unique_ptr<SurfaceProducerSurface>> surfaces) override {}
-
- private:
- scenic::Session* session_;
-
- uint32_t buffer_id_{1};
-};
-
-std::string GetCurrentTestName() {
- return ::testing::UnitTest::GetInstance()->current_test_info()->name();
-}
-
-zx_koid_t GetKoid(zx_handle_t handle) {
- if (handle == ZX_HANDLE_INVALID) {
- return ZX_KOID_INVALID;
- }
-
- zx_info_handle_basic_t info;
- zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info,
- sizeof(info), nullptr, nullptr);
- return status == ZX_OK ? info.koid : ZX_KOID_INVALID;
-}
-
-zx_koid_t GetPeerKoid(zx_handle_t handle) {
- if (handle == ZX_HANDLE_INVALID) {
- return ZX_KOID_INVALID;
- }
-
- zx_info_handle_basic_t info;
- zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info,
- sizeof(info), nullptr, nullptr);
- return status == ZX_OK ? info.related_koid : ZX_KOID_INVALID;
-}
-
-MATCHER_P(MaybeIsEmpty, assert_empty, "") {
- return assert_empty ? ExplainMatchResult(IsEmpty(), arg, result_listener)
- : ExplainMatchResult(_, arg, result_listener);
-}
-
-Matcher<FakeSceneGraph> IsEmptySceneGraph() {
- return FieldsAre(IsEmpty(), IsEmpty(), IsEmpty(), kInvalidFakeResourceId);
-}
-
-void AssertRootSceneGraph(const FakeSceneGraph& scene_graph,
- bool assert_empty) {
- ASSERT_NE(scene_graph.root_view_id, kInvalidFakeResourceId);
- ASSERT_EQ(scene_graph.resource_map.count(scene_graph.root_view_id), 1u);
- auto scene_graph_root =
- scene_graph.resource_map.find(scene_graph.root_view_id);
- ASSERT_THAT(
- scene_graph_root->second,
- Pointee(FieldsAre(
- scene_graph.root_view_id, "", FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeView>(FieldsAre(
- _, _, _, _,
- ElementsAre(Pointee(FieldsAre(
- _, "Flutter::MetricsWatcher",
- fuchsia::ui::gfx::kMetricsEventMask,
- VariantWith<FakeEntityNode>(FieldsAre(
- FieldsAre(
- ElementsAre(Pointee(FieldsAre(
- _, "Flutter::LayerTree",
- FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeEntityNode>(FieldsAre(
- FieldsAre(MaybeIsEmpty(assert_empty),
- FakeNode::kDefaultZeroRotation,
- FakeNode::kDefaultOneScale,
- FakeNode::kDefaultZeroTranslation,
- FakeNode::kDefaultZeroAnchor,
- FakeNode::kIsHitTestable,
- FakeNode::kIsSemanticallyVisible),
- IsEmpty()))))),
- FakeNode::kDefaultZeroRotation,
- FakeNode::kDefaultOneScale,
- FakeNode::kDefaultZeroTranslation,
- FakeNode::kDefaultZeroAnchor,
- FakeNode::kIsHitTestable,
- FakeNode::kIsSemanticallyVisible),
- IsEmpty()))))),
- FakeView::kDebugBoundsDisbaled)))));
-}
-
-void ExpectRootSceneGraph(
- const FakeSceneGraph& scene_graph,
- const std::string& debug_name,
- const fuchsia::ui::views::ViewHolderToken& view_holder_token,
- const fuchsia::ui::views::ViewRef& view_ref) {
- AssertRootSceneGraph(scene_graph, true);
-
- // These are safe to do unchecked due to `AssertRootSceneGraph` above.
- auto root_view_it = scene_graph.resource_map.find(scene_graph.root_view_id);
- auto* root_view_state = std::get_if<FakeView>(&root_view_it->second->state);
- EXPECT_EQ(root_view_state->token, GetPeerKoid(view_holder_token.value.get()));
- EXPECT_EQ(root_view_state->control_ref,
- GetPeerKoid(view_ref.reference.get()));
- EXPECT_EQ(root_view_state->view_ref, GetKoid(view_ref.reference.get()));
- EXPECT_EQ(root_view_state->debug_name, debug_name);
- EXPECT_EQ(scene_graph.resource_map.size(), 3u);
-}
-
-/// Verifies the scene subgraph for a particular flutter embedder layer.
-///
-/// ARGUMENTS
-///
-/// scenic_node: The root of the layer's scenic subgraph.
-///
-/// layer_size: The expected dimensions of the layer's image.
-///
-/// flutter_layer_index: This layer's 0-indexed position in the list of
-/// flutter layers present in this frame, sorted in paint order.
-///
-/// paint_regions: List of non-overlapping rects, in canvas coordinate space,
-/// where content was drawn. For each "paint region" present in the frame, the
-/// embedder reports a corresponding "hit region" to scenic as a hittable
-/// ShapeNode. ShapeNodes are centered at (0, 0), by default, so they must be
-/// translated to match the locations of the corresopnding paint regions.
-void ExpectImageCompositorLayer(const FakeResource& scenic_node,
- const SkISize layer_size,
- size_t flutter_layer_index,
- std::vector<SkRect> paint_regions) {
- const SkSize float_layer_size =
- SkSize::Make(layer_size.width(), layer_size.height());
- const float views_under_layer_depth =
- flutter_layer_index *
- GfxExternalViewEmbedder::kScenicZElevationForPlatformView;
- const float layer_depth =
- flutter_layer_index *
- GfxExternalViewEmbedder::kScenicZElevationBetweenLayers +
- views_under_layer_depth;
- const float layer_opacity =
- (flutter_layer_index == 0)
- ? GfxExternalViewEmbedder::kBackgroundLayerOpacity / 255.f
- : GfxExternalViewEmbedder::kOverlayLayerOpacity / 255.f;
-
- EXPECT_THAT(
- scenic_node,
- FieldsAre(
- _, "Flutter::Layer", FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeEntityNode>(FieldsAre(
- FieldsAre(
- // Verify children separately below, since the
- // expected number of children may vary across
- // different test cases that call this method.
- _, FakeNode::kDefaultZeroRotation, FakeNode::kDefaultOneScale,
- FakeNode::kDefaultZeroTranslation,
- FakeNode::kDefaultZeroAnchor, FakeNode::kIsHitTestable,
- FakeNode::kIsSemanticallyVisible),
- _))));
-
- const auto* layer_node_state =
- std::get_if<FakeEntityNode>(&scenic_node.state);
- ASSERT_TRUE(layer_node_state);
-
- const auto& layer_node_children = layer_node_state->node_state.children;
-
- // The layer entity node should have a child node for the image, and
- // separate children for each of the hit regions.
- ASSERT_EQ(layer_node_children.size(), paint_regions.size() + 1);
-
- // Verify image node.
- EXPECT_THAT(
- layer_node_children[0],
- Pointee(FieldsAre(
- _, "Flutter::Layer::Image", FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeShapeNode>(FieldsAre(
- FieldsAre(IsEmpty(), FakeNode::kDefaultZeroRotation,
- FakeNode::kDefaultOneScale,
- std::array<float, 3>{float_layer_size.width() / 2.f,
- float_layer_size.height() / 2.f,
- -layer_depth},
- FakeNode::kDefaultZeroAnchor,
- FakeNode::kIsNotHitTestable,
- FakeNode::kIsNotSemanticallyVisible),
- Pointee(
- FieldsAre(_, "", FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeShape>(
- FieldsAre(VariantWith<FakeShape::RectangleDef>(
- FieldsAre(float_layer_size.width(),
- float_layer_size.height())))))),
- Pointee(FieldsAre(
- _, "", FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeMaterial>(FieldsAre(
- Pointee(FieldsAre(
- _, "", FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeImage>(FieldsAre(
- VariantWith<FakeImage::Image2Def>(
- FieldsAre(_, 0, float_layer_size.width(),
- float_layer_size.height())),
- IsNull())))),
- std::array<float, 4>{1.f, 1.f, 1.f,
- layer_opacity})))))))));
-
- // Verify hit regions.
- for (size_t i = 0; i < paint_regions.size(); ++i) {
- ASSERT_LT(i, layer_node_children.size());
- const auto& paint_region = paint_regions[i];
- EXPECT_THAT(
- layer_node_children[i + 1],
- Pointee(FieldsAre(
- _, "Flutter::Layer::HitRegion",
- FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeShapeNode>(FieldsAre(
- FieldsAre(IsEmpty(), FakeNode::kDefaultZeroRotation,
- FakeNode::kDefaultOneScale,
- std::array<float, 3>{
- paint_region.x() + paint_region.width() / 2.f,
- paint_region.y() + paint_region.height() / 2.f,
- -layer_depth},
- FakeNode::kDefaultZeroAnchor,
- FakeNode::kIsHitTestable,
- FakeNode::kIsSemanticallyVisible),
- Pointee(FieldsAre(
- _, "", FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeShape>(FieldsAre(
- VariantWith<FakeShape::RectangleDef>(FieldsAre(
- paint_region.width(), paint_region.height())))))),
- IsNull())))));
- }
-}
-
-void ExpectViewCompositorLayer(const FakeResource& scenic_node,
- const fuchsia::ui::views::ViewToken& view_token,
- const flutter::EmbeddedViewParams& view_params,
- size_t flutter_layer_index) {
- const float views_under_layer_depth =
- flutter_layer_index > 0
- ? (flutter_layer_index - 1) *
- GfxExternalViewEmbedder::kScenicZElevationForPlatformView
- : 0.f;
- const float layer_depth =
- flutter_layer_index *
- GfxExternalViewEmbedder::kScenicZElevationBetweenLayers +
- views_under_layer_depth;
- EXPECT_THAT(
- scenic_node,
- FieldsAre(
- _, _ /*"Flutter::PlatformView::OpacityMutator" */,
- FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeOpacityNode>(FieldsAre(
- FieldsAre(
- ElementsAre(Pointee(FieldsAre(
- _, _ /*"Flutter::PlatformView::TransformMutator" */,
- FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeEntityNode>(FieldsAre(
- FieldsAre(
- ElementsAre(Pointee(FieldsAre(
- _, "", FakeResource::kDefaultEmptyEventMask,
- VariantWith<FakeViewHolder>(FieldsAre(
- FieldsAre(
- IsEmpty(),
- FakeNode::kDefaultZeroRotation,
- FakeNode::kDefaultOneScale,
- FakeNode::kDefaultZeroTranslation,
- FakeNode::kDefaultZeroAnchor,
- FakeNode::kIsHitTestable,
- FakeNode::kIsSemanticallyVisible),
- GetPeerKoid(view_token.value.get()),
- "Flutter::PlatformView",
- fuchsia::ui::gfx::ViewProperties{
- .bounding_box =
- fuchsia::ui::gfx::BoundingBox{
- .min = {0.f, 0.f, -1000.f},
- .max =
- {view_params.sizePoints()
- .width(),
- view_params.sizePoints()
- .height(),
- 0.f},
- }},
- FakeViewHolder::
- kDefaultBoundsColorWhite))))),
- FakeNode::kDefaultZeroRotation,
- FakeNode::kDefaultOneScale,
- std::array<float, 3>{0.f, 0.f, -layer_depth},
- FakeNode::kDefaultZeroAnchor,
- FakeNode::kIsHitTestable,
- FakeNode::kIsSemanticallyVisible),
- IsEmpty()))))),
- FakeNode::kDefaultZeroRotation, FakeNode::kDefaultOneScale,
- FakeNode::kDefaultZeroTranslation,
- FakeNode::kDefaultZeroAnchor, FakeNode::kIsHitTestable,
- FakeNode::kIsSemanticallyVisible),
- FakeOpacityNode::kDefaultOneOpacity))));
-}
-
-std::vector<FakeResource> ExtractLayersFromSceneGraph(
- const FakeSceneGraph& scene_graph) {
- AssertRootSceneGraph(scene_graph, false);
-
- // These are safe to do unchecked due to `AssertRootSceneGraph` above.
- auto root_view_it = scene_graph.resource_map.find(scene_graph.root_view_id);
- auto* root_view_state = std::get_if<FakeView>(&root_view_it->second->state);
- auto* metrics_watcher_state =
- std::get_if<FakeEntityNode>(&root_view_state->children[0]->state);
- auto* layer_tree_state = std::get_if<FakeEntityNode>(
- &metrics_watcher_state->node_state.children[0]->state);
-
- std::vector<FakeResource> scenic_layers;
- for (auto& layer_resource : layer_tree_state->node_state.children) {
- scenic_layers.push_back(*layer_resource);
- }
-
- return scenic_layers;
-}
-
-void DrawSimpleFrame(GfxExternalViewEmbedder& external_view_embedder,
- SkISize frame_size,
- float frame_dpr,
- std::function<void(flutter::DlCanvas*)> draw_callback) {
- external_view_embedder.BeginFrame(frame_size, nullptr, frame_dpr, nullptr);
- {
- flutter::DlCanvas* root_canvas = external_view_embedder.GetRootCanvas();
- external_view_embedder.PostPrerollAction(nullptr);
- draw_callback(root_canvas);
- }
- external_view_embedder.EndFrame(false, nullptr);
- flutter::SurfaceFrame::FramebufferInfo framebuffer_info;
- external_view_embedder.SubmitFrame(
- nullptr, nullptr,
- std::make_unique<flutter::SurfaceFrame>(
- nullptr, framebuffer_info,
- [](const flutter::SurfaceFrame& surface_frame,
- flutter::DlCanvas* canvas) { return true; },
- frame_size));
-}
-
-void DrawFrameWithView(
- GfxExternalViewEmbedder& external_view_embedder,
- SkISize frame_size,
- float frame_dpr,
- int view_id,
- flutter::EmbeddedViewParams& view_params,
- std::function<void(flutter::DlCanvas*)> background_draw_callback,
- std::function<void(flutter::DlCanvas*)> overlay_draw_callback) {
- external_view_embedder.BeginFrame(frame_size, nullptr, frame_dpr, nullptr);
- {
- flutter::DlCanvas* root_canvas = external_view_embedder.GetRootCanvas();
- external_view_embedder.PrerollCompositeEmbeddedView(
- view_id, std::make_unique<flutter::EmbeddedViewParams>(view_params));
- external_view_embedder.PostPrerollAction(nullptr);
- background_draw_callback(root_canvas);
- flutter::DlCanvas* overlay_canvas =
- external_view_embedder.CompositeEmbeddedView(view_id);
- overlay_draw_callback(overlay_canvas);
- }
- external_view_embedder.EndFrame(false, nullptr);
- flutter::SurfaceFrame::FramebufferInfo framebuffer_info;
- external_view_embedder.SubmitFrame(
- nullptr, nullptr,
- std::make_unique<flutter::SurfaceFrame>(
- nullptr, framebuffer_info,
- [](const flutter::SurfaceFrame& surface_frame,
- flutter::DlCanvas* canvas) { return true; },
- frame_size));
-}
-
-FramePresentedInfo MakeFramePresentedInfoForOnePresent(
- int64_t latched_time,
- int64_t frame_presented_time) {
- std::vector<PresentReceivedInfo> present_infos;
- present_infos.emplace_back();
- present_infos.back().set_present_received_time(0);
- present_infos.back().set_latched_time(0);
- return FramePresentedInfo{
- .actual_presentation_time = 0,
- .presentation_infos = std::move(present_infos),
- .num_presents_allowed = 1,
- };
-}
-
-}; // namespace
-
-class GfxExternalViewEmbedderTest
- : public ::testing::Test,
- public fuchsia::ui::scenic::SessionListener {
- protected:
- GfxExternalViewEmbedderTest()
- : session_subloop_(loop_.StartNewLoop()),
- session_listener_(this),
- session_connection_(CreateSessionConnection()),
- fake_surface_producer_(
- std::make_shared<FakeSurfaceProducer>(session_connection_->get())) {
- }
- ~GfxExternalViewEmbedderTest() override = default;
-
- async::TestLoop& loop() { return loop_; }
-
- FakeSession& fake_session() { return fake_session_; }
-
- std::shared_ptr<FakeSurfaceProducer> fake_surface_producer() {
- return fake_surface_producer_;
- }
-
- std::shared_ptr<GfxSessionConnection> session_connection() {
- return session_connection_;
- }
-
- private:
- // |fuchsia::ui::scenic::SessionListener|
- void OnScenicError(std::string error) override { FAIL(); }
-
- // |fuchsia::ui::scenic::SessionListener|
- void OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) override {
- FAIL();
- }
-
- std::shared_ptr<GfxSessionConnection> CreateSessionConnection() {
- FML_CHECK(!fake_session_.is_bound());
- FML_CHECK(!session_listener_.is_bound());
-
- inspect::Node inspect_node =
- inspector_.GetRoot().CreateChild("GfxExternalViewEmbedderTest");
-
- auto [session, session_listener] =
- fake_session_.Bind(session_subloop_->dispatcher());
- session_listener_.Bind(std::move(session_listener));
-
- return std::make_shared<GfxSessionConnection>(
- GetCurrentTestName(), std::move(inspect_node), std::move(session),
- []() { FAIL(); }, [](auto...) {}, 1, fml::TimeDelta::Zero());
- }
-
- async::TestLoop loop_; // Must come before FIDL bindings.
- std::unique_ptr<async::LoopInterface> session_subloop_;
-
- fidl::Binding<fuchsia::ui::scenic::SessionListener> session_listener_;
-
- inspect::Inspector inspector_;
-
- FakeSession fake_session_;
-
- std::shared_ptr<GfxSessionConnection> session_connection_;
- std::shared_ptr<FakeSurfaceProducer> fake_surface_producer_;
-};
-
-// Tests the trivial case where flutter does not present any content to scenic.
-TEST_F(GfxExternalViewEmbedderTest, RootScene) {
- const std::string debug_name = GetCurrentTestName();
- auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
- auto view_ref_pair = scenic::ViewRefPair::New();
- fuchsia::ui::views::ViewRef view_ref;
- view_ref_pair.view_ref.Clone(&view_ref);
-
- GfxExternalViewEmbedder external_view_embedder(
- debug_name, std::move(view_token), std::move(view_ref_pair),
- session_connection(), fake_surface_producer());
- EXPECT_EQ(fake_session().debug_name(), "");
- EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
-
- // Pump the loop; the contents of the initial `Present` should be processed.
- loop().RunUntilIdle();
- EXPECT_EQ(fake_session().debug_name(), debug_name);
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-
- // Fire the `OnFramePresented` event associated with the first `Present`, then
- // pump the loop. The `OnFramePresented` event is resolved.
- //
- // The scene graph shouldn't change.
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-}
-
-// Tests the case where flutter renders a single image.
-TEST_F(GfxExternalViewEmbedderTest, SimpleScene) {
- const std::string debug_name = GetCurrentTestName();
- auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
- auto view_ref_pair = scenic::ViewRefPair::New();
- fuchsia::ui::views::ViewRef view_ref;
- view_ref_pair.view_ref.Clone(&view_ref);
-
- // Create the `GfxExternalViewEmbedder` and pump the message loop until
- // the initial scene graph is setup.
- GfxExternalViewEmbedder external_view_embedder(
- debug_name, std::move(view_token), std::move(view_ref_pair),
- session_connection(), fake_surface_producer());
- loop().RunUntilIdle();
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-
- // Draw the scene. The scene graph shouldn't change yet.
- const SkISize frame_size = SkISize::Make(512, 512);
- SkRect paint_region;
- DrawSimpleFrame(external_view_embedder, frame_size, 1.f,
- [&paint_region](flutter::DlCanvas* canvas) {
- const SkISize layer_size = canvas->GetBaseLayerSize();
- const SkSize canvas_size =
- SkSize::Make(layer_size.width(), layer_size.height());
- flutter::DlPaint rect_paint(flutter::DlColor::kGreen());
-
- paint_region = SkRect::MakeXYWH(
- canvas_size.width() / 4.f, canvas_size.height() / 2.f,
- canvas_size.width() / 32.f,
- canvas_size.height() / 32.f);
-
- canvas->DrawRect(paint_region, rect_paint);
- });
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-
- // Pump the message loop. The scene updates should propogate to Scenic.
- loop().RunUntilIdle();
- std::vector<FakeResource> scenic_layers =
- ExtractLayersFromSceneGraph(fake_session().SceneGraph());
- EXPECT_EQ(scenic_layers.size(), 1u);
- ExpectImageCompositorLayer(scenic_layers[0], frame_size,
- /* flutter layer index = */ 0, {paint_region});
-}
-
-// Tests the case where flutter embeds a platform view on top of an image layer.
-TEST_F(GfxExternalViewEmbedderTest, SceneWithOneView) {
- const std::string debug_name = GetCurrentTestName();
- auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
- auto view_ref_pair = scenic::ViewRefPair::New();
- fuchsia::ui::views::ViewRef view_ref;
- view_ref_pair.view_ref.Clone(&view_ref);
-
- // Create the `GfxExternalViewEmbedder` and pump the message loop until
- // the initial scene graph is setup.
- GfxExternalViewEmbedder external_view_embedder(
- debug_name, std::move(view_token), std::move(view_ref_pair),
- session_connection(), fake_surface_producer());
- loop().RunUntilIdle();
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-
- // Create the view before drawing the scene.
- const SkSize child_view_size = SkSize::Make(256.f, 512.f);
- auto [child_view_token, child_view_holder_token] =
- scenic::ViewTokenPair::New();
- const uint32_t child_view_id = child_view_holder_token.value.get();
- flutter::EmbeddedViewParams child_view_params(SkMatrix::I(), child_view_size,
- flutter::MutatorsStack());
- external_view_embedder.CreateView(
- child_view_id, []() {}, [](scenic::ResourceId) {});
-
- // Draw the scene. The scene graph shouldn't change yet.
- const SkISize frame_size = SkISize::Make(512, 512);
-
- SkRect main_surface_paint_region, overlay_paint_region;
-
- DrawFrameWithView(
- external_view_embedder, frame_size, 1.f, child_view_id, child_view_params,
- [&main_surface_paint_region](flutter::DlCanvas* canvas) {
- const SkISize layer_size = canvas->GetBaseLayerSize();
- const SkSize canvas_size =
- SkSize::Make(layer_size.width(), layer_size.height());
-
- main_surface_paint_region = SkRect::MakeXYWH(
- canvas_size.width() / 4.f, canvas_size.width() / 2.f,
- canvas_size.width() / 32.f, canvas_size.height() / 32.f);
-
- flutter::DlPaint rect_paint(flutter::DlColor::kGreen());
- canvas->DrawRect(main_surface_paint_region, rect_paint);
- },
- [&overlay_paint_region](flutter::DlCanvas* canvas) {
- const SkISize layer_size = canvas->GetBaseLayerSize();
- const SkSize canvas_size =
- SkSize::Make(layer_size.width(), layer_size.height());
- overlay_paint_region = SkRect::MakeXYWH(
- canvas_size.width() * 3.f / 4.f, canvas_size.height() / 2.f,
- canvas_size.width() / 32.f, canvas_size.height() / 32.f);
-
- flutter::DlPaint rect_paint(flutter::DlColor::kRed());
- canvas->DrawRect(overlay_paint_region, rect_paint);
- });
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-
- // Pump the message loop. The scene updates should propagate to Scenic.
- loop().RunUntilIdle();
- std::vector<FakeResource> scenic_layers =
- ExtractLayersFromSceneGraph(fake_session().SceneGraph());
- EXPECT_EQ(scenic_layers.size(), 3u);
- ExpectImageCompositorLayer(scenic_layers[0], frame_size,
- /* flutter layer index = */ 0,
- {main_surface_paint_region});
- ExpectViewCompositorLayer(scenic_layers[1], child_view_token,
- child_view_params,
- /* flutter layer index = */ 1);
- ExpectImageCompositorLayer(scenic_layers[2], frame_size,
- /* flutter layer index = */ 1,
- {overlay_paint_region});
-
- // Destroy the view.
- external_view_embedder.DestroyView(child_view_id, [](scenic::ResourceId) {});
-
- // Pump the message loop.
- loop().RunUntilIdle();
-}
-
-// Tests the case where flutter renders an image with two non-overlapping pieces
-// of content. In this case, the embedder should report two separate hit regions
-// to scenic.
-TEST_F(GfxExternalViewEmbedderTest, SimpleSceneDisjointHitRegions) {
- const std::string debug_name = GetCurrentTestName();
- auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
- auto view_ref_pair = scenic::ViewRefPair::New();
- fuchsia::ui::views::ViewRef view_ref;
- view_ref_pair.view_ref.Clone(&view_ref);
-
- // Create the `GfxExternalViewEmbedder` and pump the message loop until
- // the initial scene graph is setup.
- GfxExternalViewEmbedder external_view_embedder(
- debug_name, std::move(view_token), std::move(view_ref_pair),
- session_connection(), fake_surface_producer());
- loop().RunUntilIdle();
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-
- // Draw the scene. The scene graph shouldn't change yet.
- SkRect paint_region_1, paint_region_2;
- const SkISize frame_size = SkISize::Make(512, 512);
- DrawSimpleFrame(
- external_view_embedder, frame_size, 1.f,
- [&paint_region_1, &paint_region_2](flutter::DlCanvas* canvas) {
- const SkISize layer_size = canvas->GetBaseLayerSize();
- const SkSize canvas_size =
- SkSize::Make(layer_size.width(), layer_size.height());
-
- paint_region_1 = SkRect::MakeXYWH(
- canvas_size.width() / 4.f, canvas_size.height() / 2.f,
- canvas_size.width() / 32.f, canvas_size.height() / 32.f);
-
- flutter::DlPaint rect_paint(flutter::DlColor::kGreen());
- canvas->DrawRect(paint_region_1, rect_paint);
-
- paint_region_2 = SkRect::MakeXYWH(
- canvas_size.width() * 3.f / 4.f, canvas_size.height() / 2.f,
- canvas_size.width() / 32.f, canvas_size.height() / 32.f);
-
- rect_paint.setColor(flutter::DlColor::kRed());
- canvas->DrawRect(paint_region_2, rect_paint);
- });
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-
- // Pump the message loop. The scene updates should propogate to Scenic.
- loop().RunUntilIdle();
- std::vector<FakeResource> scenic_layers =
- ExtractLayersFromSceneGraph(fake_session().SceneGraph());
- EXPECT_EQ(scenic_layers.size(), 1u);
- ExpectImageCompositorLayer(scenic_layers[0], frame_size,
- /* flutter layer index = */ 0,
- {paint_region_1, paint_region_2});
-}
-
-// Tests the case where flutter renders an image with two overlapping pieces of
-// content. In this case, the embedder should report a single joint hit region
-// to scenic.
-TEST_F(GfxExternalViewEmbedderTest, SimpleSceneOverlappingHitRegions) {
- const std::string debug_name = GetCurrentTestName();
- auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
- auto view_ref_pair = scenic::ViewRefPair::New();
- fuchsia::ui::views::ViewRef view_ref;
- view_ref_pair.view_ref.Clone(&view_ref);
-
- // Create the `GfxExternalViewEmbedder` and pump the message loop until
- // the initial scene graph is setup.
- GfxExternalViewEmbedder external_view_embedder(
- debug_name, std::move(view_token), std::move(view_ref_pair),
- session_connection(), fake_surface_producer());
- loop().RunUntilIdle();
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-
- // Draw the scene. The scene graph shouldn't change yet.
- SkRect joined_paint_region = SkRect::MakeEmpty();
- const SkISize frame_size = SkISize::Make(512, 512);
- DrawSimpleFrame(external_view_embedder, frame_size, 1.f,
- [&joined_paint_region](flutter::DlCanvas* canvas) {
- const SkISize layer_size = canvas->GetBaseLayerSize();
- const SkSize canvas_size =
- SkSize::Make(layer_size.width(), layer_size.height());
-
- auto paint_region_1 = SkRect::MakeXYWH(
- canvas_size.width() / 4.f, canvas_size.height() / 4.f,
- canvas_size.width() / 2.f, canvas_size.height() / 2.f);
- flutter::DlPaint rect_paint(flutter::DlColor::kGreen());
- canvas->DrawRect(paint_region_1, rect_paint);
-
- auto paint_region_2 = SkRect::MakeXYWH(
- canvas_size.width() * 3.f / 8.f,
- canvas_size.height() / 4.f, canvas_size.width() / 2.f,
- canvas_size.height() / 2.f);
- rect_paint.setColor(flutter::DlColor::kRed());
- canvas->DrawRect(paint_region_2, rect_paint);
-
- joined_paint_region.join(paint_region_1);
- joined_paint_region.join(paint_region_2);
- });
- ExpectRootSceneGraph(fake_session().SceneGraph(), debug_name,
- view_holder_token, view_ref);
-
- EXPECT_EQ(joined_paint_region.x(), 128.f);
- EXPECT_EQ(joined_paint_region.y(), 128.f);
- EXPECT_EQ(joined_paint_region.width(), 320.f);
- EXPECT_EQ(joined_paint_region.height(), 256.f);
- // Pump the message loop. The scene updates should propogate to Scenic.
- loop().RunUntilIdle();
- std::vector<FakeResource> scenic_layers =
- ExtractLayersFromSceneGraph(fake_session().SceneGraph());
- EXPECT_EQ(scenic_layers.size(), 1u);
- ExpectImageCompositorLayer(scenic_layers[0], frame_size,
- /* flutter layer index = */ 0,
- {joined_paint_region});
-}
-
-} // namespace flutter_runner::testing
diff --git a/shell/platform/fuchsia/flutter/tests/gfx_session_connection_unittests.cc b/shell/platform/fuchsia/flutter/tests/gfx_session_connection_unittests.cc
deleted file mode 100644
index d8fdec5..0000000
--- a/shell/platform/fuchsia/flutter/tests/gfx_session_connection_unittests.cc
+++ /dev/null
@@ -1,1075 +0,0 @@
-// Copyright 2013 The Flutter Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "flutter/shell/platform/fuchsia/flutter/gfx_session_connection.h"
-
-#include <fuchsia/scenic/scheduling/cpp/fidl.h>
-#include <fuchsia/ui/scenic/cpp/fidl.h>
-#include <lib/async-testing/test_loop.h>
-#include <lib/inspect/cpp/inspect.h>
-
-#include <functional>
-#include <string>
-#include <vector>
-
-#include "flutter/fml/logging.h"
-#include "flutter/fml/time/time_delta.h"
-#include "flutter/fml/time/time_point.h"
-#include "gtest/gtest.h"
-
-#include "fakes/scenic/fake_session.h"
-
-using fuchsia::scenic::scheduling::FramePresentedInfo;
-using fuchsia::scenic::scheduling::FuturePresentationTimes;
-using fuchsia::scenic::scheduling::PresentReceivedInfo;
-
-namespace flutter_runner::testing {
-namespace {
-
-std::string GetCurrentTestName() {
- return ::testing::UnitTest::GetInstance()->current_test_info()->name();
-}
-
-fml::TimePoint TimePointFromInt(int64_t i) {
- return fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromNanoseconds(i));
-}
-
-fml::TimeDelta TimeDeltaFromInt(int64_t i) {
- return fml::TimeDelta::FromNanoseconds(i);
-}
-
-int64_t TimePointToInt(fml::TimePoint time) {
- return time.ToEpochDelta().ToNanoseconds();
-}
-
-fuchsia::scenic::scheduling::PresentationInfo CreatePresentationInfo(
- zx_time_t latch_point,
- zx_time_t presentation_time) {
- fuchsia::scenic::scheduling::PresentationInfo info;
-
- info.set_latch_point(latch_point);
- info.set_presentation_time(presentation_time);
- return info;
-}
-
-FramePresentedInfo MakeFramePresentedInfoForOnePresent(
- int64_t latched_time,
- int64_t frame_presented_time) {
- std::vector<PresentReceivedInfo> present_infos;
- present_infos.emplace_back();
- present_infos.back().set_present_received_time(0);
- present_infos.back().set_latched_time(0);
- return FramePresentedInfo{
- .actual_presentation_time = 0,
- .presentation_infos = std::move(present_infos),
- .num_presents_allowed = 1,
- };
-}
-
-void AwaitVsyncChecked(GfxSessionConnection& session_connection,
- bool& condition_variable,
- fml::TimeDelta expected_frame_start,
- fml::TimeDelta expected_frame_end) {
- session_connection.AwaitVsync(
- [&condition_variable,
- expected_frame_start = std::move(expected_frame_start),
- expected_frame_end = std::move(expected_frame_end)](
- fml::TimePoint frame_start, fml::TimePoint frame_end) {
- EXPECT_EQ(frame_start.ToEpochDelta(), expected_frame_start);
- EXPECT_EQ(frame_end.ToEpochDelta(), expected_frame_end);
- condition_variable = true;
- });
-}
-
-}; // namespace
-
-class GfxSessionConnectionTest : public ::testing::Test,
- public fuchsia::ui::scenic::SessionListener {
- protected:
- GfxSessionConnectionTest()
- : session_listener_(this), session_subloop_(loop_.StartNewLoop()) {
- auto [session, session_listener] =
- fake_session().Bind(session_subloop_->dispatcher());
-
- session_ = std::move(session);
- session_listener_.Bind(std::move(session_listener));
- }
- ~GfxSessionConnectionTest() override = default;
-
- async::TestLoop& loop() { return loop_; }
-
- FakeSession& fake_session() { return fake_session_; }
-
- inspect::Node GetInspectNode() {
- return inspector_.GetRoot().CreateChild("GfxSessionConnectionTest");
- }
-
- fidl::InterfaceHandle<fuchsia::ui::scenic::Session> TakeSessionHandle() {
- FML_CHECK(session_.is_valid());
- return std::move(session_);
- }
-
- private:
- // |fuchsia::ui::scenic::SessionListener|
- void OnScenicError(std::string error) override { FAIL(); }
-
- // |fuchsia::ui::scenic::SessionListener|
- void OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) override {
- FAIL();
- }
-
- async::TestLoop loop_;
-
- inspect::Inspector inspector_;
-
- fidl::InterfaceHandle<fuchsia::ui::scenic::Session> session_;
- fidl::Binding<fuchsia::ui::scenic::SessionListener> session_listener_;
-
- std::unique_ptr<async::LoopInterface> session_subloop_;
- FakeSession fake_session_;
-};
-
-TEST_F(GfxSessionConnectionTest, Initialization) {
- // Create the GfxSessionConnection but don't pump the loop. No FIDL calls are
- // completed yet.
- const std::string debug_name = GetCurrentTestName();
- flutter_runner::GfxSessionConnection session_connection(
- debug_name, GetInspectNode(), TakeSessionHandle(), []() { FAIL(); },
- [](auto...) { FAIL(); }, 1, fml::TimeDelta::Zero());
- EXPECT_EQ(fake_session().debug_name(), "");
- EXPECT_TRUE(fake_session().command_queue().empty());
-
- // Simulate an AwaitVsync that comes immediately, before
- // `RequestPresentationTimes` returns.
- bool await_vsync_fired = false;
- AwaitVsyncChecked(session_connection, await_vsync_fired,
- fml::TimeDelta::Zero(), kDefaultPresentationInterval);
- EXPECT_TRUE(await_vsync_fired);
-
- // Ensure the debug name is set.
- loop().RunUntilIdle();
- EXPECT_EQ(fake_session().debug_name(), debug_name);
- EXPECT_TRUE(fake_session().command_queue().empty());
-}
-
-TEST_F(GfxSessionConnectionTest, SessionDisconnect) {
- // Set up a callback which allows sensing of the session error state.
- bool session_error_fired = false;
- fml::closure on_session_error = [&session_error_fired]() {
- session_error_fired = true;
- };
-
- // Create the GfxSessionConnection but don't pump the loop. No FIDL calls are
- // completed yet.
- flutter_runner::GfxSessionConnection session_connection(
- GetCurrentTestName(), GetInspectNode(), TakeSessionHandle(),
- std::move(on_session_error), [](auto...) { FAIL(); }, 1,
- fml::TimeDelta::Zero());
- EXPECT_FALSE(session_error_fired);
-
- // Simulate a session disconnection, then Pump the loop. The session error
- // callback will fire.
- fake_session().DisconnectSession();
- loop().RunUntilIdle();
- EXPECT_TRUE(session_error_fired);
-}
-
-TEST_F(GfxSessionConnectionTest, BasicPresent) {
- // Set up callbacks which allow sensing of how many presents
- // (`RequestPresentationTimes` or `Present` calls) were handled.
- size_t request_times_called = 0u;
- size_t presents_called = 0u;
- fake_session().SetRequestPresentationTimesHandler(
- [&request_times_called](auto...) -> auto {
- request_times_called++;
- return FuturePresentationTimes{
- .future_presentations = {},
- .remaining_presents_in_flight_allowed = 1,
- };
- });
- fake_session().SetPresent2Handler([&presents_called](auto...) -> auto {
- presents_called++;
- return FuturePresentationTimes{
- .future_presentations = {},
- .remaining_presents_in_flight_allowed = 1,
- };
- });
-
- // Set up a callback which allows sensing of how many vsync's
- // (`OnFramePresented` events) were handled.
- size_t vsyncs_handled = 0u;
- on_frame_presented_event on_frame_presented = [&vsyncs_handled](auto...) {
- vsyncs_handled++;
- };
-
- // Create the GfxSessionConnection but don't pump the loop. No FIDL calls are
- // completed yet.
- flutter_runner::GfxSessionConnection session_connection(
- GetCurrentTestName(), GetInspectNode(), TakeSessionHandle(),
- []() { FAIL(); }, std::move(on_frame_presented), 1,
- fml::TimeDelta::Zero());
- EXPECT_TRUE(fake_session().command_queue().empty());
- EXPECT_EQ(request_times_called, 0u);
- EXPECT_EQ(presents_called, 0u);
- EXPECT_EQ(vsyncs_handled, 0u);
-
- // Pump the loop; `RequestPresentationTimes`, `Present`, and both of their
- // callbacks are called.
- loop().RunUntilIdle();
- EXPECT_TRUE(fake_session().command_queue().empty());
- EXPECT_EQ(request_times_called, 1u);
- EXPECT_EQ(presents_called, 1u);
- EXPECT_EQ(vsyncs_handled, 0u);
-
- // Fire the `OnFramePresented` event associated with the first `Present`, then
- // pump the loop. The `OnFramePresented` event is resolved.
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- EXPECT_TRUE(fake_session().command_queue().empty());
- EXPECT_EQ(request_times_called, 1u);
- EXPECT_EQ(presents_called, 1u);
- EXPECT_EQ(vsyncs_handled, 1u);
-
- // Simulate an AwaitVsync that comes after the first `OnFramePresented`
- // event.
- bool await_vsync_fired = false;
- AwaitVsyncChecked(session_connection, await_vsync_fired,
- fml::TimeDelta::Zero(), kDefaultPresentationInterval);
- EXPECT_TRUE(await_vsync_fired);
-
- // Call Present and Pump the loop; `Present` and its callback is called.
- await_vsync_fired = false;
- session_connection.Present();
- loop().RunUntilIdle();
- EXPECT_TRUE(fake_session().command_queue().empty());
- EXPECT_FALSE(await_vsync_fired);
- EXPECT_EQ(request_times_called, 1u);
- EXPECT_EQ(presents_called, 2u);
- EXPECT_EQ(vsyncs_handled, 1u);
-
- // Fire the `OnFramePresented` event associated with the second `Present`,
- // then pump the loop. The `OnFramePresented` event is resolved.
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- EXPECT_TRUE(fake_session().command_queue().empty());
- EXPECT_FALSE(await_vsync_fired);
- EXPECT_EQ(request_times_called, 1u);
- EXPECT_EQ(presents_called, 2u);
- EXPECT_EQ(vsyncs_handled, 2u);
-
- // Simulate an AwaitVsync that comes after the second `OnFramePresented`
- // event.
- await_vsync_fired = false;
- AwaitVsyncChecked(session_connection, await_vsync_fired,
- kDefaultPresentationInterval,
- kDefaultPresentationInterval * 2);
- EXPECT_TRUE(await_vsync_fired);
-}
-
-TEST_F(GfxSessionConnectionTest, AwaitVsyncBackpressure) {
- // Set up a callback which allows sensing of how many presents
- // (`Present` calls) were handled.
- size_t presents_called = 0u;
- fake_session().SetPresent2Handler([&presents_called](auto...) -> auto {
- presents_called++;
- return FuturePresentationTimes{
- .future_presentations = {},
- .remaining_presents_in_flight_allowed = 1,
- };
- });
-
- // Set up a callback which allows sensing of how many vsync's
- // (`OnFramePresented` events) were handled.
- size_t vsyncs_handled = 0u;
- on_frame_presented_event on_frame_presented = [&vsyncs_handled](auto...) {
- vsyncs_handled++;
- };
-
- // Create the GfxSessionConnection but don't pump the loop. No FIDL calls are
- // completed yet.
- flutter_runner::GfxSessionConnection session_connection(
- GetCurrentTestName(), GetInspectNode(), TakeSessionHandle(),
- []() { FAIL(); }, std::move(on_frame_presented), 1,
- fml::TimeDelta::Zero());
- EXPECT_EQ(presents_called, 0u);
- EXPECT_EQ(vsyncs_handled, 0u);
-
- // Pump the loop; `RequestPresentationTimes`, `Present`, and both of their
- // callbacks are called.
- loop().RunUntilIdle();
- EXPECT_EQ(presents_called, 1u);
- EXPECT_EQ(vsyncs_handled, 0u);
-
- // Simulate an AwaitVsync that comes before the first `OnFramePresented`
- // event.
- bool await_vsync_fired = false;
- AwaitVsyncChecked(session_connection, await_vsync_fired,
- fml::TimeDelta::Zero(), kDefaultPresentationInterval);
- EXPECT_FALSE(await_vsync_fired);
-
- // Fire the `OnFramePresented` event associated with the first `Present`, then
- // pump the loop. The `OnFramePresented` event is resolved. The AwaitVsync
- // callback is resolved.
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- EXPECT_TRUE(await_vsync_fired);
- EXPECT_EQ(presents_called, 1u);
- EXPECT_EQ(vsyncs_handled, 1u);
-
- // Simulate an AwaitVsync that comes before the second `Present`.
- await_vsync_fired = false;
- AwaitVsyncChecked(session_connection, await_vsync_fired,
- kDefaultPresentationInterval,
- kDefaultPresentationInterval * 2);
- EXPECT_TRUE(await_vsync_fired);
-
- // Call Present and Pump the loop; `Present` and its callback is called.
- await_vsync_fired = false;
- session_connection.Present();
- loop().RunUntilIdle();
- EXPECT_FALSE(await_vsync_fired);
- EXPECT_EQ(presents_called, 2u);
- EXPECT_EQ(vsyncs_handled, 1u);
-
- // Simulate an AwaitVsync that comes before the second `OnFramePresented`
- // event.
- await_vsync_fired = false;
- AwaitVsyncChecked(session_connection, await_vsync_fired,
- kDefaultPresentationInterval * 2,
- kDefaultPresentationInterval * 3);
- EXPECT_FALSE(await_vsync_fired);
-
- // Fire the `OnFramePresented` event associated with the second `Present`,
- // then pump the loop. The `OnFramePresented` event is resolved.
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- EXPECT_TRUE(await_vsync_fired);
- EXPECT_EQ(presents_called, 2u);
- EXPECT_EQ(vsyncs_handled, 2u);
-}
-
-TEST_F(GfxSessionConnectionTest, PresentBackpressure) {
- // Set up a callback which allows sensing of how many presents
- // (`Present` calls) were handled.
- size_t presents_called = 0u;
- fake_session().SetPresent2Handler([&presents_called](auto...) -> auto {
- presents_called++;
- return FuturePresentationTimes{
- .future_presentations = {},
- .remaining_presents_in_flight_allowed = 1,
- };
- });
-
- // Set up a callback which allows sensing of how many vsync's
- // (`OnFramePresented` events) were handled.
- size_t vsyncs_handled = 0u;
- on_frame_presented_event on_frame_presented = [&vsyncs_handled](auto...) {
- vsyncs_handled++;
- };
-
- // Create the GfxSessionConnection but don't pump the loop. No FIDL calls are
- // completed yet.
- flutter_runner::GfxSessionConnection session_connection(
- GetCurrentTestName(), GetInspectNode(), TakeSessionHandle(),
- []() { FAIL(); }, std::move(on_frame_presented), 1,
- fml::TimeDelta::Zero());
- EXPECT_EQ(presents_called, 0u);
- EXPECT_EQ(vsyncs_handled, 0u);
-
- // Pump the loop; `RequestPresentationTimes`, `Present`, and both of their
- // callbacks are called.
- loop().RunUntilIdle();
- EXPECT_EQ(presents_called, 1u);
- EXPECT_EQ(vsyncs_handled, 0u);
-
- // Call Present and Pump the loop; `Present` is not called due to backpressue.
- session_connection.Present();
- loop().RunUntilIdle();
- EXPECT_EQ(presents_called, 1u);
- EXPECT_EQ(vsyncs_handled, 0u);
-
- // Call Present again and Pump the loop; `Present` is not called due to
- // backpressue.
- session_connection.Present();
- loop().RunUntilIdle();
- EXPECT_EQ(presents_called, 1u);
- EXPECT_EQ(vsyncs_handled, 0u);
-
- // Fire the `OnFramePresented` event associated with the first `Present`, then
- // pump the loop. The `OnFramePresented` event is resolved. The pending
- // `Present` calls are resolved.
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- EXPECT_EQ(presents_called, 2u);
- EXPECT_EQ(vsyncs_handled, 1u);
-
- // Call Present and Pump the loop; `Present` is not called due to
- // backpressue.
- session_connection.Present();
- loop().RunUntilIdle();
- EXPECT_EQ(presents_called, 2u);
- EXPECT_EQ(vsyncs_handled, 1u);
-
- // Call Present again and Pump the loop; `Present` is not called due to
- // backpressue.
- session_connection.Present();
- loop().RunUntilIdle();
- EXPECT_EQ(presents_called, 2u);
- EXPECT_EQ(vsyncs_handled, 1u);
-
- // Fire the `OnFramePresented` event associated with the second `Present`,
- // then pump the loop. The `OnFramePresented` event is resolved. The pending
- // `Present` calls are resolved.
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- EXPECT_EQ(presents_called, 3u);
- EXPECT_EQ(vsyncs_handled, 2u);
-
- // Fire the `OnFramePresented` event associated with the third `Present`,
- // then pump the loop. The `OnFramePresented` event is resolved. No pending
- // `Present` calls exist, so none are resolved.
- fake_session().FireOnFramePresentedEvent(
- MakeFramePresentedInfoForOnePresent(0, 0));
- loop().RunUntilIdle();
- EXPECT_EQ(presents_called, 3u);
- EXPECT_EQ(vsyncs_handled, 3u);
-}
-
-// The first set of tests has an empty |future_presentation_infos| passed in.
-// Therefore these tests are to ensure that on startup and after not presenting
-// for some time that we have correct, reasonable behavior.
-TEST(CalculateNextLatchPointTest, PresentAsSoonAsPossible) {
- fml::TimePoint present_requested_time = TimePointFromInt(0);
- fml::TimePoint now = TimePointFromInt(0);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(0);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(0);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {};
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point), TimePointToInt(now));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + vsync_interval));
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-TEST(CalculateNextLatchPointTest, LongFrameBuildTime) {
- fml::TimePoint present_requested_time = TimePointFromInt(500);
- fml::TimePoint now = TimePointFromInt(600);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(0);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(2500);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {};
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- EXPECT_GT(flutter_frame_build_time, vsync_interval);
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 2)));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 3)));
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-TEST(CalculateNextLatchPointTest, DelayedPresentRequestWithLongFrameBuildTime) {
- fml::TimePoint present_requested_time = TimePointFromInt(0);
- fml::TimePoint now = TimePointFromInt(1500);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(0);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(2000);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {};
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- EXPECT_GT(flutter_frame_build_time, vsync_interval);
- EXPECT_GT(now, present_requested_time + vsync_interval);
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point), TimePointToInt(now));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + vsync_interval));
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-TEST(CalculateNextLatchPointTest, LastLastPointTargetedLate) {
- fml::TimePoint present_requested_time = TimePointFromInt(2000);
- fml::TimePoint now = TimePointFromInt(2000);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(2600);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(1000);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {};
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- EXPECT_GT(last_latch_point_targeted, present_requested_time);
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + vsync_interval));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 2)));
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-// This set of tests provides (latch_point, vsync_time) pairs in
-// |future_presentation_infos|. This tests steady state behavior where we're
-// presenting frames virtually every vsync interval.
-
-TEST(CalculateNextLatchPointTest, SteadyState_OnTimeFrames) {
- fml::TimePoint present_requested_time = TimePointFromInt(5000);
- fml::TimePoint now = TimePointFromInt(5000);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(4500);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(1000);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {
- {TimePointFromInt(3500), TimePointFromInt(4000)},
- {TimePointFromInt(4500), TimePointFromInt(5000)},
- {TimePointFromInt(5500), TimePointFromInt(6000)},
- {TimePointFromInt(6500), TimePointFromInt(7000)},
- {TimePointFromInt(7500), TimePointFromInt(8000)},
- };
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + vsync_interval));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 2)));
- EXPECT_EQ(TimePointToInt(calculated_latch_point), 6500);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-TEST(CalculateNextLatchPointTest, SteadyState_LongFrameBuildTimes) {
- fml::TimePoint present_requested_time = TimePointFromInt(5000);
- fml::TimePoint now = TimePointFromInt(5000);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(4500);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(2000);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {
- {TimePointFromInt(3500), TimePointFromInt(4000)},
- {TimePointFromInt(4500), TimePointFromInt(5000)},
- {TimePointFromInt(5500), TimePointFromInt(6000)},
- {TimePointFromInt(6500), TimePointFromInt(7000)},
- {TimePointFromInt(7500), TimePointFromInt(8000)},
- };
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- EXPECT_GT(flutter_frame_build_time, vsync_interval);
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 2)));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 3)));
- EXPECT_EQ(TimePointToInt(calculated_latch_point), 7500);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-TEST(CalculateNextLatchPointTest, SteadyState_LateLastLatchPointTargeted) {
- fml::TimePoint present_requested_time = TimePointFromInt(5000);
- fml::TimePoint now = TimePointFromInt(5000);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(6500);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(1000);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {
- {TimePointFromInt(4500), TimePointFromInt(5000)},
- {TimePointFromInt(5500), TimePointFromInt(6000)},
- {TimePointFromInt(6500), TimePointFromInt(7000)},
- {TimePointFromInt(7500), TimePointFromInt(8000)},
- {TimePointFromInt(8500), TimePointFromInt(9000)},
- };
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- EXPECT_GT(last_latch_point_targeted, now + vsync_interval);
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + vsync_interval));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 2)));
- EXPECT_EQ(TimePointToInt(calculated_latch_point), 6500);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-TEST(CalculateNextLatchPointTest,
- SteadyState_DelayedPresentRequestWithLongFrameBuildTime) {
- fml::TimePoint present_requested_time = TimePointFromInt(4000);
- fml::TimePoint now = TimePointFromInt(5500);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(3500);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(2000);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {
- {TimePointFromInt(4500), TimePointFromInt(5000)},
- {TimePointFromInt(5500), TimePointFromInt(6000)},
- {TimePointFromInt(6500), TimePointFromInt(7000)},
- };
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- EXPECT_GT(flutter_frame_build_time, vsync_interval);
- EXPECT_GT(now, present_requested_time + vsync_interval);
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + vsync_interval));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 2)));
- EXPECT_EQ(TimePointToInt(calculated_latch_point), 6500);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-TEST(CalculateNextLatchPointTest, SteadyState_FuzzyLatchPointsBeforeTarget) {
- fml::TimePoint present_requested_time = TimePointFromInt(4000);
- fml::TimePoint now = TimePointFromInt(4000);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(5490);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(1000);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {
- {TimePointFromInt(4510), TimePointFromInt(5000)},
- {TimePointFromInt(5557), TimePointFromInt(6000)},
- {TimePointFromInt(6482), TimePointFromInt(7000)},
- {TimePointFromInt(7356), TimePointFromInt(8000)},
- };
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + vsync_interval));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 2)));
- EXPECT_EQ(TimePointToInt(calculated_latch_point), 5557);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-TEST(CalculateNextLatchPointTest, SteadyState_FuzzyLatchPointsAfterTarget) {
- fml::TimePoint present_requested_time = TimePointFromInt(4000);
- fml::TimePoint now = TimePointFromInt(4000);
- fml::TimePoint last_latch_point_targeted = TimePointFromInt(5557);
- fml::TimeDelta flutter_frame_build_time = TimeDeltaFromInt(1000);
- fml::TimeDelta vsync_interval = TimeDeltaFromInt(1000);
- std::deque<std::pair<fml::TimePoint, fml::TimePoint>>
- future_presentation_infos = {
- {TimePointFromInt(4510), TimePointFromInt(5000)},
- {TimePointFromInt(5490), TimePointFromInt(6000)},
- {TimePointFromInt(6482), TimePointFromInt(7000)},
- {TimePointFromInt(7356), TimePointFromInt(8000)},
- };
-
- // Assertions about given values.
- EXPECT_GE(now, present_requested_time);
- EXPECT_GE(flutter_frame_build_time, TimeDeltaFromInt(0));
- EXPECT_GT(vsync_interval, TimeDeltaFromInt(0));
-
- fml::TimePoint calculated_latch_point =
- GfxSessionConnection::CalculateNextLatchPoint(
- present_requested_time, now, last_latch_point_targeted,
- flutter_frame_build_time, vsync_interval, future_presentation_infos);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 2)));
- EXPECT_LE(TimePointToInt(calculated_latch_point),
- TimePointToInt(now + (vsync_interval * 3)));
- EXPECT_EQ(TimePointToInt(calculated_latch_point), 6482);
-
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(present_requested_time + flutter_frame_build_time));
- EXPECT_GE(TimePointToInt(calculated_latch_point),
- TimePointToInt(last_latch_point_targeted));
-}
-
-TEST(SnapToNextPhaseTest, SnapOverlapsWithNow) {
- const auto now = fml::TimePoint::Now();
- const auto last_presentation_time = now - fml::TimeDelta::FromNanoseconds(10);
- const auto delta = fml::TimeDelta::FromNanoseconds(10);
- const auto next_vsync = flutter_runner::GfxSessionConnection::SnapToNextPhase(
- now, last_presentation_time, delta);
-
- EXPECT_EQ(now + delta, next_vsync);
-}
-
-TEST(SnapToNextPhaseTest, SnapAfterNow) {
- const auto now = fml::TimePoint::Now();
- const auto last_presentation_time = now - fml::TimeDelta::FromNanoseconds(9);
- const auto delta = fml::TimeDelta::FromNanoseconds(10);
- const auto next_vsync = flutter_runner::GfxSessionConnection::SnapToNextPhase(
- now, last_presentation_time, delta);
-
- // math here: 10 - 9 = 1
- EXPECT_EQ(now + fml::TimeDelta::FromNanoseconds(1), next_vsync);
-}
-
-TEST(SnapToNextPhaseTest, SnapAfterNowMultiJump) {
- const auto now = fml::TimePoint::Now();
- const auto last_presentation_time = now - fml::TimeDelta::FromNanoseconds(34);
- const auto delta = fml::TimeDelta::FromNanoseconds(10);
- const auto next_vsync = flutter_runner::GfxSessionConnection::SnapToNextPhase(
- now, last_presentation_time, delta);
-
- // zeroes: -34, -24, -14, -4, 6, ...
- EXPECT_EQ(now + fml::TimeDelta::FromNanoseconds(6), next_vsync);
-}
-
-TEST(SnapToNextPhaseTest, SnapAfterNowMultiJumpAccountForCeils) {
- const auto now = fml::TimePoint::Now();
- const auto last_presentation_time = now - fml::TimeDelta::FromNanoseconds(20);
- const auto delta = fml::TimeDelta::FromNanoseconds(16);
- const auto next_vsync = flutter_runner::GfxSessionConnection::SnapToNextPhase(
- now, last_presentation_time, delta);
-
- // zeroes: -20, -4, 12, 28, ...
- EXPECT_EQ(now + fml::TimeDelta::FromNanoseconds(12), next_vsync);
-}
-
-TEST(GetTargetTimesTest, ScheduleForNextVsync) {
- const fml::TimeDelta vsync_offset = TimeDeltaFromInt(0);
- const fml::TimeDelta vsync_interval = TimeDeltaFromInt(10);
- const fml::TimePoint last_targeted_vsync = TimePointFromInt(10);
- const fml::TimePoint now = TimePointFromInt(9);
- const fml::TimePoint next_vsync = TimePointFromInt(10);
-
- const auto target_times =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync, now, next_vsync);
-
- EXPECT_EQ(TimePointToInt(target_times.frame_start), 10);
- EXPECT_EQ(TimePointToInt(target_times.frame_target), 20);
-}
-
-TEST(GetTargetTimesTest, ScheduleForCurrentVsync_DueToOffset) {
- const fml::TimeDelta vsync_offset = TimeDeltaFromInt(3);
- const fml::TimeDelta vsync_interval = TimeDeltaFromInt(10);
- const fml::TimePoint last_targeted_vsync = TimePointFromInt(0);
- const fml::TimePoint now = TimePointFromInt(6);
- const fml::TimePoint next_vsync = TimePointFromInt(10);
-
- const auto target_times =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync, now, next_vsync);
-
- EXPECT_EQ(TimePointToInt(target_times.frame_start), 7);
- EXPECT_EQ(TimePointToInt(target_times.frame_target), 10);
-}
-
-TEST(GetTargetTimesTest, ScheduleForFollowingVsync_BecauseOfNow) {
- const fml::TimeDelta vsync_offset = TimeDeltaFromInt(0);
- const fml::TimeDelta vsync_interval = TimeDeltaFromInt(10);
- const fml::TimePoint last_targeted_vsync = TimePointFromInt(10);
- const fml::TimePoint now = TimePointFromInt(15);
- const fml::TimePoint next_vsync = TimePointFromInt(10);
-
- const auto target_times =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync, now, next_vsync);
-
- EXPECT_EQ(TimePointToInt(target_times.frame_start), 20);
- EXPECT_EQ(TimePointToInt(target_times.frame_target), 30);
-}
-
-TEST(GetTargetTimesTest, ScheduleForFollowingVsync_BecauseOfTargettedTime) {
- const fml::TimeDelta vsync_offset = TimeDeltaFromInt(0);
- const fml::TimeDelta vsync_interval = TimeDeltaFromInt(10);
- const fml::TimePoint last_targeted_vsync = TimePointFromInt(20);
- const fml::TimePoint now = TimePointFromInt(9);
- const fml::TimePoint next_vsync = TimePointFromInt(10);
-
- const auto target_times =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync, now, next_vsync);
-
- EXPECT_EQ(TimePointToInt(target_times.frame_start), 20);
- EXPECT_EQ(TimePointToInt(target_times.frame_target), 30);
-}
-
-TEST(GetTargetTimesTest, ScheduleForDistantVsync_BecauseOfTargettedTime) {
- const fml::TimeDelta vsync_offset = TimeDeltaFromInt(0);
- const fml::TimeDelta vsync_interval = TimeDeltaFromInt(10);
- const fml::TimePoint last_targeted_vsync = TimePointFromInt(60);
- const fml::TimePoint now = TimePointFromInt(9);
- const fml::TimePoint next_vsync = TimePointFromInt(10);
-
- const auto target_times =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync, now, next_vsync);
-
- EXPECT_EQ(TimePointToInt(target_times.frame_start), 60);
- EXPECT_EQ(TimePointToInt(target_times.frame_target), 70);
-}
-
-TEST(GetTargetTimesTest, ScheduleForFollowingVsync_WithSlightVsyncDrift) {
- const fml::TimeDelta vsync_offset = TimeDeltaFromInt(0);
- const fml::TimeDelta vsync_interval = TimeDeltaFromInt(10);
-
- // Even though it appears as if the next vsync is at time 40, we should still
- // present at time 50.
- const fml::TimePoint last_targeted_vsync = TimePointFromInt(37);
- const fml::TimePoint now = TimePointFromInt(9);
- const fml::TimePoint next_vsync = TimePointFromInt(10);
-
- const auto target_times =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync, now, next_vsync);
-
- EXPECT_EQ(TimePointToInt(target_times.frame_start), 40);
- EXPECT_EQ(TimePointToInt(target_times.frame_target), 50);
-}
-
-TEST(GetTargetTimesTest, ScheduleForAnOffsetFromVsync) {
- const fml::TimeDelta vsync_offset = TimeDeltaFromInt(4);
- const fml::TimeDelta vsync_interval = TimeDeltaFromInt(10);
- const fml::TimePoint last_targeted_vsync = TimePointFromInt(10);
- const fml::TimePoint now = TimePointFromInt(9);
- const fml::TimePoint next_vsync = TimePointFromInt(10);
-
- const auto target_times =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync, now, next_vsync);
-
- EXPECT_EQ(TimePointToInt(target_times.frame_start), 16);
- EXPECT_EQ(TimePointToInt(target_times.frame_target), 20);
-}
-
-TEST(GetTargetTimesTest, ScheduleMultipleTimes) {
- const fml::TimeDelta vsync_offset = TimeDeltaFromInt(0);
- const fml::TimeDelta vsync_interval = TimeDeltaFromInt(10);
-
- fml::TimePoint last_targeted_vsync = TimePointFromInt(0);
- fml::TimePoint now = TimePointFromInt(5);
- fml::TimePoint next_vsync = TimePointFromInt(10);
-
- for (int i = 0; i < 100; ++i) {
- const auto target_times =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync, now, next_vsync);
-
- EXPECT_EQ(TimePointToInt(target_times.frame_start), 10 * (i + 1));
- EXPECT_EQ(TimePointToInt(target_times.frame_target), 10 * (i + 2));
-
- // Simulate the passage of time.
- now = now + vsync_interval;
- next_vsync = next_vsync + vsync_interval;
- last_targeted_vsync = target_times.frame_target;
- }
-}
-
-TEST(GetTargetTimesTest, ScheduleMultipleTimes_WithDelayedWakeups) {
- // It is often the case that Flutter does not wake up when it intends to due
- // to CPU contention. This test has GfxSessionConnection wake up to
- // schedule 0-4ns after when |now| should be - and we verify that the results
- // should be the same as if there were no delay.
- const fml::TimeDelta vsync_offset = TimeDeltaFromInt(0);
- const fml::TimeDelta vsync_interval = TimeDeltaFromInt(10);
-
- fml::TimePoint last_targeted_vsync = TimePointFromInt(0);
- fml::TimePoint now = TimePointFromInt(5);
- fml::TimePoint next_vsync = TimePointFromInt(10);
-
- for (int i = 0; i < 100; ++i) {
- const auto target_times =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync, now, next_vsync);
-
- const auto target_times_delay =
- flutter_runner::GfxSessionConnection::GetTargetTimes(
- vsync_offset, vsync_interval, last_targeted_vsync,
- now + TimeDeltaFromInt(i % 5), next_vsync);
-
- EXPECT_EQ(TimePointToInt(target_times.frame_start),
- TimePointToInt(target_times_delay.frame_start));
- EXPECT_EQ(TimePointToInt(target_times.frame_target),
- TimePointToInt(target_times_delay.frame_target));
-
- // Simulate the passage of time.
- now = now + vsync_interval;
- next_vsync = next_vsync + vsync_interval;
- last_targeted_vsync = target_times.frame_target;
- }
-}
-
-TEST(UpdatePresentationInfoTest, SingleUpdate) {
- std::vector<fuchsia::scenic::scheduling::PresentationInfo>
- future_presentations = {};
-
- // Update the |vsync_info|.
- future_presentations.push_back(
- CreatePresentationInfo(/*latch_point=*/5, /*presentation_time=*/10));
-
- fuchsia::scenic::scheduling::FuturePresentationTimes future_info;
- future_info.future_presentations = std::move(future_presentations);
- future_info.remaining_presents_in_flight_allowed = 1;
-
- fuchsia::scenic::scheduling::PresentationInfo presentation_info;
- presentation_info.set_presentation_time(0);
-
- fuchsia::scenic::scheduling::PresentationInfo new_presentation_info =
- flutter_runner::GfxSessionConnection::UpdatePresentationInfo(
- std::move(future_info), presentation_info);
-
- EXPECT_EQ(new_presentation_info.presentation_time(), 10);
-}
-
-TEST(UpdatePresentationInfoTest, MultipleUpdates) {
- std::vector<fuchsia::scenic::scheduling::PresentationInfo>
- future_presentations = {};
-
- // Update the |vsync_info|.
- future_presentations.push_back(
- CreatePresentationInfo(/*latch_point=*/15, /*presentation_time=*/20));
- future_presentations.push_back(
- CreatePresentationInfo(/*latch_point=*/25, /*presentation_time=*/30));
- fuchsia::scenic::scheduling::FuturePresentationTimes future_info;
- future_info.future_presentations = std::move(future_presentations);
- future_info.remaining_presents_in_flight_allowed = 1;
-
- fuchsia::scenic::scheduling::PresentationInfo presentation_info;
- presentation_info.set_presentation_time(0);
-
- fuchsia::scenic::scheduling::PresentationInfo new_presentation_info =
- flutter_runner::GfxSessionConnection::UpdatePresentationInfo(
- std::move(future_info), presentation_info);
-
- EXPECT_EQ(new_presentation_info.presentation_time(), 20);
-
- // Clear and re-try with more future times!
- future_presentations.clear();
- future_presentations.push_back(
- CreatePresentationInfo(/*latch_point=*/15, /*presentation_time=*/20));
- future_presentations.push_back(
- CreatePresentationInfo(/*latch_point=*/25, /*presentation_time=*/30));
- future_presentations.push_back(
- CreatePresentationInfo(/*latch_point=*/35, /*presentation_time=*/40));
- future_presentations.push_back(
- CreatePresentationInfo(/*latch_point=*/45, /*presentation_time=*/50));
- future_info.future_presentations = std::move(future_presentations);
- future_info.remaining_presents_in_flight_allowed = 1;
-
- new_presentation_info =
- flutter_runner::GfxSessionConnection::UpdatePresentationInfo(
- std::move(future_info), new_presentation_info);
-
- EXPECT_EQ(new_presentation_info.presentation_time(), 30);
-}
-
-} // namespace flutter_runner::testing
diff --git a/shell/platform/fuchsia/flutter/tests/platform_view_unittest.cc b/shell/platform/fuchsia/flutter/tests/platform_view_unittest.cc
index 2869c15..c6b8f7c 100644
--- a/shell/platform/fuchsia/flutter/tests/platform_view_unittest.cc
+++ b/shell/platform/fuchsia/flutter/tests/platform_view_unittest.cc
@@ -7,13 +7,12 @@
#include <fuchsia/ui/input/cpp/fidl.h>
#include <fuchsia/ui/input3/cpp/fidl.h>
#include <fuchsia/ui/input3/cpp/fidl_test_base.h>
-#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/async/default.h>
#include <lib/fidl/cpp/binding_set.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
+#include <lib/zx/eventpair.h>
#include <memory>
#include <ostream>
@@ -244,9 +243,17 @@
void GetViewRef(GetViewRefCallback callback) override {
// GetViewRef only returns once as per flatland.fidl comments
ASSERT_FALSE(control_ref_.reference);
- auto pair = scenic::ViewRefPair::New();
- control_ref_ = std::move(pair.control_ref);
- callback(std::move(pair.view_ref));
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ control_ref_ = std::move(view_ref_control);
+ callback(std::move(view_ref));
}
void NotImplemented_(const std::string& name) override { FAIL(); }
@@ -332,9 +339,20 @@
public:
PlatformViewBuilder(flutter::PlatformView::Delegate& delegate,
flutter::TaskRunners task_runners)
- : delegate_(delegate),
- task_runners_(task_runners),
- view_ref_pair_(scenic::ViewRefPair::New()) {}
+ : delegate_(delegate), task_runners_(task_runners) {
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref_control.reference.replace(
+ ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
+ &view_ref_control.reference);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
+ auto view_ref_pair =
+ std::make_pair(std::move(view_ref_control), std::move(view_ref));
+ view_ref_pair_ = std::move(view_ref_pair);
+ }
PlatformViewBuilder& SetExternalViewEmbedder(
std::shared_ptr<flutter::ExternalViewEmbedder> embedder) {
@@ -428,7 +446,7 @@
EXPECT_FALSE(std::exchange(built_, true))
<< "Build() was already called, this builder is good for one use only.";
return PlatformView(
- delegate_, task_runners_, std::move(view_ref_pair_.view_ref),
+ delegate_, task_runners_, std::move(view_ref_pair_.second),
external_external_view_embedder_, std::move(ime_service_),
std::move(keyboard_), std::move(touch_source_),
std::move(mouse_source_), std::move(focuser_),
@@ -450,7 +468,8 @@
flutter::PlatformView::Delegate& delegate_;
flutter::TaskRunners task_runners_;
- scenic::ViewRefPair view_ref_pair_;
+ std::pair<fuchsia::ui::views::ViewRefControl, fuchsia::ui::views::ViewRef>
+ view_ref_pair_;
std::shared_ptr<flutter::ExternalViewEmbedder>
external_external_view_embedder_;
@@ -653,7 +672,6 @@
EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics());
MockParentViewportWatcher watcher;
- std::vector<fuchsia::ui::scenic::Event> events;
flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr,
nullptr);
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
diff --git a/shell/platform/fuchsia/flutter/text_delegate_unittests.cc b/shell/platform/fuchsia/flutter/text_delegate_unittests.cc
index 29835d0..b56e076 100644
--- a/shell/platform/fuchsia/flutter/text_delegate_unittests.cc
+++ b/shell/platform/fuchsia/flutter/text_delegate_unittests.cc
@@ -12,7 +12,7 @@
#include <lib/async-loop/default.h>
#include <lib/fidl/cpp/binding.h>
#include <lib/fidl/cpp/binding_set.h>
-#include <lib/ui/scenic/cpp/view_ref_pair.h>
+#include <lib/zx/eventpair.h>
#include "tests/fakes/platform_message.h"
@@ -89,10 +89,15 @@
fidl::InterfaceHandle<fuchsia::ui::input::ImeService> ime_service_handle;
ime_service_binding_.Bind(ime_service_handle.NewRequest().TakeChannel());
- auto fake_view_ref_pair = scenic::ViewRefPair::New();
+ fuchsia::ui::views::ViewRefControl view_ref_control;
+ fuchsia::ui::views::ViewRef view_ref;
+ auto status = zx::eventpair::create(
+ /*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
+ ZX_ASSERT(status == ZX_OK);
+ view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
text_delegate_ = std::make_unique<TextDelegate>(
- std::move(fake_view_ref_pair.view_ref), std::move(ime_service_handle),
+ std::move(view_ref), std::move(ime_service_handle),
std::move(keyboard_handle),
// Should this be accessed through a weak pointer?
[this](std::unique_ptr<flutter::PlatformMessage> message) {
diff --git a/shell/platform/fuchsia/flutter/vulkan_surface.cc b/shell/platform/fuchsia/flutter/vulkan_surface.cc
index 7d0f526..a3d7078 100644
--- a/shell/platform/fuchsia/flutter/vulkan_surface.cc
+++ b/shell/platform/fuchsia/flutter/vulkan_surface.cc
@@ -6,7 +6,6 @@
#include <fuchsia/sysmem/cpp/fidl.h>
#include <lib/async/default.h>
-#include <lib/ui/scenic/cpp/commands.h>
#include <algorithm>