From 482c08216e961aafcd0f2879fbd3225e8961fe8d Mon Sep 17 00:00:00 2001 From: Jaeheon Yi Date: Sun, 26 Sep 2021 07:43:05 -0700 Subject: [PATCH] fuchsia.ui.pointer.TouchSource implementation for fuchsia platform view (flutter/engine#28242) --- .../ci/licenses_golden/licenses_flutter | 3 + .../shell/platform/fuchsia/flutter/BUILD.gn | 8 +- .../shell/platform/fuchsia/flutter/engine.cc | 6 + .../fuchsia/flutter/flatland_platform_view.cc | 2 + .../fuchsia/flutter/flatland_platform_view.h | 1 + .../fuchsia/flutter/focus_delegate.cc | 9 +- .../platform/fuchsia/flutter/focus_delegate.h | 8 +- .../flutter/focus_delegate_unittests.cc | 53 +- .../fuchsia/flutter/gfx_platform_view.cc | 5 +- .../fuchsia/flutter/gfx_platform_view.h | 55 +- .../platform/fuchsia/flutter/platform_view.cc | 46 +- .../platform/fuchsia/flutter/platform_view.h | 55 +- .../fuchsia/flutter/platform_view_unittest.cc | 119 +++- .../fuchsia/flutter/pointer_delegate.cc | 239 +++++++ .../fuchsia/flutter/pointer_delegate.h | 105 +++ .../flutter/pointer_delegate_unittests.cc | 669 ++++++++++++++++++ .../fuchsia/flutter/tests/fakes/BUILD.gn | 1 + .../flutter/tests/fakes/touch_source.h | 60 ++ .../flutter/tests/pointer_event_utility.cc | 80 +++ .../flutter/tests/pointer_event_utility.h | 45 ++ 20 files changed, 1477 insertions(+), 92 deletions(-) create mode 100644 engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.cc create mode 100644 engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.h create mode 100644 engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc create mode 100644 engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/touch_source.h create mode 100644 engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.cc create mode 100644 engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.h diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 1a98f0b56e..b776f69941 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1457,6 +1457,9 @@ FILE: ../../../flutter/shell/platform/fuchsia/flutter/meta/jit_runtime FILE: ../../../flutter/shell/platform/fuchsia/flutter/platform_view.cc FILE: ../../../flutter/shell/platform/fuchsia/flutter/platform_view.h FILE: ../../../flutter/shell/platform/fuchsia/flutter/platform_view_unittest.cc +FILE: ../../../flutter/shell/platform/fuchsia/flutter/pointer_delegate.cc +FILE: ../../../flutter/shell/platform/fuchsia/flutter/pointer_delegate.h +FILE: ../../../flutter/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc FILE: ../../../flutter/shell/platform/fuchsia/flutter/runner.cc FILE: ../../../flutter/shell/platform/fuchsia/flutter/runner.h FILE: ../../../flutter/shell/platform/fuchsia/flutter/runner_tzdata_unittest.cc diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn b/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn index 40677a962e..8ee40e4d43 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn @@ -86,6 +86,8 @@ template("runner_sources") { "logging.h", "platform_view.cc", "platform_view.h", + "pointer_delegate.cc", + "pointer_delegate.h", "runner.cc", "runner.h", "surface.cc", @@ -142,6 +144,8 @@ template("runner_sources") { "$fuchsia_sdk_root/fidl:fuchsia.sys", "$fuchsia_sdk_root/fidl:fuchsia.ui.app", "$fuchsia_sdk_root/fidl:fuchsia.ui.composition", + "$fuchsia_sdk_root/fidl:fuchsia.ui.pointer", + "$fuchsia_sdk_root/fidl:fuchsia.ui.views", "$fuchsia_sdk_root/fidl:fuchsia.ui.scenic", "$fuchsia_sdk_root/pkg:async-cpp", "$fuchsia_sdk_root/pkg:async-default", @@ -463,12 +467,15 @@ executable("flutter_runner_unittests") { "fuchsia_intl_unittest.cc", "keyboard_unittest.cc", "platform_view_unittest.cc", + "pointer_delegate_unittests.cc", "runner_unittest.cc", "tests/engine_unittests.cc", "tests/fake_session_unittests.cc", "tests/flutter_runner_product_configuration_unittests.cc", "tests/fuchsia_external_view_embedder_unittests.cc", "tests/gfx_session_connection_unittests.cc", + "tests/pointer_event_utility.cc", + "tests/pointer_event_utility.h", ] # This is needed for //third_party/googletest for linking zircon symbols. @@ -490,7 +497,6 @@ executable("flutter_runner_unittests") { "tests/fakes", ":flutter_runner_fixtures", ":flutter_runner_sources", - "tests/fakes", "//build/fuchsia/pkg:async-testing", "//build/fuchsia/pkg:sys_cpp_testing", "//flutter/testing", diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc index 95d4624b0e..caf4785407 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc @@ -136,6 +136,9 @@ void Engine::Initialize( endpoints.set_view_focuser(focuser.NewRequest()); fidl::InterfaceHandle view_ref_focused; endpoints.set_view_ref_focused(view_ref_focused.NewRequest()); + fidl::InterfaceHandle touch_source; + // TODO(fxbug.dev/85125): Enable TouchSource for GFX. + // endpoints.set_touch_source(touch_source.NewRequest()); scenic->CreateSessionT(std::move(endpoints), [] {}); // Make clones of the `ViewRef` before sending it down to Scenic, since the @@ -322,6 +325,7 @@ void Engine::Initialize( parent_viewport_watcher = std::move(parent_viewport_watcher), focuser = std::move(focuser), view_ref_focused = std::move(view_ref_focused), + touch_source = std::move(touch_source), on_session_listener_error_callback = std::move(on_session_listener_error_callback), on_enable_wireframe_callback = @@ -399,6 +403,7 @@ void Engine::Initialize( parent_environment_service_provider), // services std::move(parent_viewport_watcher), std::move(view_ref_focused), std::move(focuser), + std::move(touch_source), // Server-side part of the // fuchsia.ui.input3.KeyboardListener connection. std::move(keyboard_listener_request), @@ -424,6 +429,7 @@ void Engine::Initialize( std::move(parent_environment_service_provider), // services std::move(session_listener_request), // session listener std::move(view_ref_focused), std::move(focuser), + std::move(touch_source), // Server-side part of the fuchsia.ui.input3.KeyboardListener // connection. std::move(keyboard_listener_request), diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.cc index 57206e1fd7..d62eaf9817 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.cc @@ -19,6 +19,7 @@ FlatlandPlatformView::FlatlandPlatformView( fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher, fidl::InterfaceHandle vrf, fidl::InterfaceHandle focuser, + fidl::InterfaceHandle touch_source, fidl::InterfaceRequest keyboard_listener, OnEnableWireframe wireframe_enabled_callback, @@ -41,6 +42,7 @@ FlatlandPlatformView::FlatlandPlatformView( std::move(parent_environment_service_provider), std::move(vrf), std::move(focuser), + std::move(touch_source), std::move(keyboard_listener), std::move(wireframe_enabled_callback), std::move(on_create_view_callback), diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.h b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.h index c2607d0d08..b2fa8357b1 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.h +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.h @@ -24,6 +24,7 @@ class FlatlandPlatformView final : public flutter_runner::PlatformView { parent_viewport_watcher, fidl::InterfaceHandle vrf, fidl::InterfaceHandle focuser, + fidl::InterfaceHandle touch_source, fidl::InterfaceRequest keyboard_listener, OnEnableWireframe wireframe_enabled_callback, diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.cc index 6e1307e5d4..645bc18f78 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.cc @@ -10,17 +10,18 @@ namespace flutter_runner { void FocusDelegate::WatchLoop(std::function callback) { if (watch_loop_) { - FML_LOG(ERROR) << "FocusDelegate::WatchLoop() cannot be called twice."; + FML_LOG(ERROR) << "FocusDelegate::WatchLoop() must be called once."; return; } - watch_loop_ = [this, callback = std::move(callback)](auto focus_state) { + watch_loop_ = [this, /*copy*/ callback](auto focus_state) { callback(is_focused_ = focus_state.focused()); Complete(std::exchange(next_focus_request_, nullptr), is_focused_ ? "[true]" : "[false]"); - view_ref_focused_->Watch(watch_loop_); + view_ref_focused_->Watch(/*copy*/ watch_loop_); }; - view_ref_focused_->Watch(watch_loop_); + + view_ref_focused_->Watch(/*copy*/ watch_loop_); } bool FocusDelegate::HandlePlatformMessage( diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.h b/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.h index 851498d63c..2d58579789 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.h +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate.h @@ -24,7 +24,11 @@ class FocusDelegate { /// Continuously watches the host viewRef for focus events, invoking a /// callback each time. /// - /// This can only be called once. + /// The callback is invoked on each Watch() call, which consumes the callback + /// argument. Hence, the callback argument must be copyable, so that a copy + /// can be freely moved into the Watch() call. + /// + /// This method can only be called once. void WatchLoop(std::function callback); /// Handles the following focus-related platform message requests: @@ -50,7 +54,7 @@ class FocusDelegate { fuchsia::ui::views::FocuserPtr focuser_; std::function watch_loop_; - bool is_focused_; + bool is_focused_ = false; fml::RefPtr next_focus_request_; void Complete(fml::RefPtr response, diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc index 940763b452..62f8a7bc0f 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc @@ -28,22 +28,17 @@ rapidjson::Value ParsePlatformMessage(std::string json) { namespace flutter_runner::testing { class FocusDelegateTest : public ::testing::Test { - public: - std::unique_ptr vrf; - std::unique_ptr focuser; - std::unique_ptr focus_delegate; - - void RunLoopUntilIdle() { loop_.RunUntilIdle(); } - protected: FocusDelegateTest() : loop_(&kAsyncLoopConfigAttachToCurrentThread) {} + void RunLoopUntilIdle() { loop_.RunUntilIdle(); } + void SetUp() override { - vrf = std::make_unique(); - focuser = std::make_unique(); - focus_delegate = std::make_unique( - vrf_bindings.AddBinding(vrf.get()), - focuser_bindings.AddBinding(focuser.get())); + vrf_ = std::make_unique(); + focuser_ = std::make_unique(); + focus_delegate_ = std::make_unique( + vrf_bindings.AddBinding(vrf_.get()), + focuser_bindings.AddBinding(focuser_.get())); } void TearDown() override { @@ -53,6 +48,10 @@ class FocusDelegateTest : public ::testing::Test { loop_.ResetQuit(); } + std::unique_ptr vrf_; + std::unique_ptr focuser_; + std::unique_ptr focus_delegate_; + private: async::Loop loop_; fidl::BindingSet vrf_bindings; @@ -68,7 +67,7 @@ TEST_F(FocusDelegateTest, WatchCallbackSeries) { true, false, true, true}; std::size_t vrf_index = 0; std::size_t callback_index = 0; - focus_delegate->WatchLoop([&](bool focus_state) { + focus_delegate_->WatchLoop([&](bool focus_state) { // Make sure the focus state that FocusDelegate gives us is consistent with // what was fired from the vrf. EXPECT_EQ(vrf_states[callback_index], focus_state); @@ -76,39 +75,39 @@ TEST_F(FocusDelegateTest, WatchCallbackSeries) { // View.focus.getCurrent should complete with the current (up to date) focus // state. auto response = FakePlatformMessageResponse::Create(); - EXPECT_TRUE(focus_delegate->HandlePlatformMessage( + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( ParsePlatformMessage("{\"method\":\"View.focus.getCurrent\"}"), response)); response->ExpectCompleted(focus_state ? "[true]" : "[false]"); // Ensure this callback always happens in lockstep with - // vrf->ScheduleCallback. + // vrf_->ScheduleCallback. EXPECT_EQ(vrf_index, callback_index++); }); // Subsequent WatchLoop calls should not be respected. - focus_delegate->WatchLoop([](bool _) { + focus_delegate_->WatchLoop([](bool _) { ADD_FAILURE() << "Subsequent WatchLoops should not be respected!"; }); do { // Ensure the next focus state is handled correctly. auto response1 = FakePlatformMessageResponse::Create(); - EXPECT_TRUE(focus_delegate->HandlePlatformMessage( + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( ParsePlatformMessage("{\"method\":\"View.focus.getNext\"}"), response1)); // Since there's already an outstanding PlatformMessageResponse, this one // should be completed null. auto response2 = FakePlatformMessageResponse::Create(); - EXPECT_TRUE(focus_delegate->HandlePlatformMessage( + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( ParsePlatformMessage("{\"method\":\"View.focus.getNext\"}"), response2)); response2->ExpectCompleted("[null]"); // Post watch events and trigger the next vrf event. RunLoopUntilIdle(); - vrf->ScheduleCallback(vrf_states[vrf_index]); + vrf_->ScheduleCallback(vrf_states[vrf_index]); RunLoopUntilIdle(); // Next focus state should be completed by now. @@ -117,14 +116,14 @@ TEST_F(FocusDelegateTest, WatchCallbackSeries) { // Check View.focus.getCurrent again, and increment vrf_index since we move // on to the next focus state. auto response3 = FakePlatformMessageResponse::Create(); - EXPECT_TRUE(focus_delegate->HandlePlatformMessage( + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( ParsePlatformMessage("{\"method\":\"View.focus.getCurrent\"}"), response3)); response3->ExpectCompleted(vrf_states[vrf_index++] ? "[true]" : "[false]"); - // vrf->times_watched should always be 1 more than the amount of vrf events + // vrf_->times_watched should always be 1 more than the amount of vrf events // emitted. - EXPECT_EQ(vrf_index + 1, vrf->times_watched); + EXPECT_EQ(vrf_index + 1, vrf_->times_watched); } while (vrf_index < vrf_states.size()); } @@ -144,12 +143,12 @@ TEST_F(FocusDelegateTest, RequestFocusTest) { // Dispatch the plaform message request with an expected completion response. auto response = FakePlatformMessageResponse::Create(); - EXPECT_TRUE(focus_delegate->HandlePlatformMessage( + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( ParsePlatformMessage(message.str()), response)); RunLoopUntilIdle(); response->ExpectCompleted("[0]"); - EXPECT_TRUE(focuser->request_focus_called()); + EXPECT_TRUE(focuser_->request_focus_called()); } // Tests that HandlePlatformMessage() completes a "View.focus.request" response @@ -158,7 +157,7 @@ TEST_F(FocusDelegateTest, RequestFocusFailTest) { // This "Mock" ViewRef serves as the target for the RequestFocus operation. auto mock_view_ref_pair = scenic::ViewRefPair::New(); // We're testing the focus failure case. - focuser->fail_request_focus(); + focuser_->fail_request_focus(); // Create the platform message request. std::ostringstream message; message << "{" @@ -170,7 +169,7 @@ TEST_F(FocusDelegateTest, RequestFocusFailTest) { // Dispatch the plaform message request with an expected completion response. auto response = FakePlatformMessageResponse::Create(); - EXPECT_TRUE(focus_delegate->HandlePlatformMessage( + EXPECT_TRUE(focus_delegate_->HandlePlatformMessage( ParsePlatformMessage(message.str()), response)); RunLoopUntilIdle(); @@ -180,7 +179,7 @@ TEST_F(FocusDelegateTest, RequestFocusFailTest) { static_cast>( fuchsia::ui::views::Error::DENIED)) + "]"); - EXPECT_TRUE(focuser->request_focus_called()); + EXPECT_TRUE(focuser_->request_focus_called()); } } // namespace flutter_runner::testing diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.cc index e89a06ef46..c4eaa77744 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.cc @@ -20,6 +20,7 @@ GfxPlatformView::GfxPlatformView( session_listener_request, fidl::InterfaceHandle vrf, fidl::InterfaceHandle focuser, + fidl::InterfaceHandle touch_source, fidl::InterfaceRequest keyboard_listener, fit::closure on_session_listener_error_callback, @@ -43,6 +44,7 @@ GfxPlatformView::GfxPlatformView( std::move(parent_environment_service_provider), std::move(vrf), std::move(focuser), + std::move(touch_source), std::move(keyboard_listener), std::move(wireframe_enabled_callback), std::move(on_create_view_callback), @@ -165,8 +167,9 @@ void GfxPlatformView::OnScenicEvent( case fuchsia::ui::scenic::Event::Tag::kInput: switch (event.input().Which()) { case fuchsia::ui::input::InputEvent::Tag::kFocus: - break; + break; // Focus handled elsewhere. case fuchsia::ui::input::InputEvent::Tag::kPointer: { + // Only received when TouchSource not plugged in. OnHandlePointerEvent(event.input().pointer()); break; } diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.h b/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.h index d1b6601344..45e36d6c7c 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.h +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.h @@ -8,6 +8,7 @@ #include "platform_view.h" #include +#include namespace flutter_runner { @@ -17,32 +18,34 @@ namespace flutter_runner { class GfxPlatformView final : public flutter_runner::PlatformView, private fuchsia::ui::scenic::SessionListener { public: - GfxPlatformView(flutter::PlatformView::Delegate& delegate, - std::string debug_label, - fuchsia::ui::views::ViewRef view_ref, - flutter::TaskRunners task_runners, - std::shared_ptr runner_services, - fidl::InterfaceHandle - parent_environment_service_provider, - fidl::InterfaceRequest - session_listener_request, - fidl::InterfaceHandle vrf, - fidl::InterfaceHandle focuser, - fidl::InterfaceRequest - keyboard_listener, - fit::closure on_session_listener_error_callback, - OnEnableWireframe wireframe_enabled_callback, - OnCreateView on_create_view_callback, - OnUpdateView on_update_view_callback, - OnDestroyView on_destroy_view_callback, - OnCreateSurface on_create_surface_callback, - OnSemanticsNodeUpdate on_semantics_node_update_callback, - OnRequestAnnounce on_request_announce_callback, - OnShaderWarmup on_shader_warmup, - std::shared_ptr view_embedder, - AwaitVsyncCallback await_vsync_callback, - AwaitVsyncForSecondaryCallbackCallback - await_vsync_for_secondary_callback_callback); + GfxPlatformView( + flutter::PlatformView::Delegate& delegate, + std::string debug_label, + fuchsia::ui::views::ViewRef view_ref, + flutter::TaskRunners task_runners, + std::shared_ptr runner_services, + fidl::InterfaceHandle + parent_environment_service_provider, + fidl::InterfaceRequest + session_listener_request, + fidl::InterfaceHandle vrf, + fidl::InterfaceHandle focuser, + fidl::InterfaceHandle touch_source, + fidl::InterfaceRequest + keyboard_listener, + fit::closure on_session_listener_error_callback, + OnEnableWireframe wireframe_enabled_callback, + OnCreateView on_create_view_callback, + OnUpdateView on_update_view_callback, + OnDestroyView on_destroy_view_callback, + OnCreateSurface on_create_surface_callback, + OnSemanticsNodeUpdate on_semantics_node_update_callback, + OnRequestAnnounce on_request_announce_callback, + OnShaderWarmup on_shader_warmup, + std::shared_ptr view_embedder, + AwaitVsyncCallback await_vsync_callback, + AwaitVsyncForSecondaryCallbackCallback + await_vsync_for_secondary_callback_callback); ~GfxPlatformView(); private: diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.cc index cbd16ed9bf..2e1ab444c7 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.cc @@ -60,6 +60,7 @@ PlatformView::PlatformView( parent_environment_service_provider_handle, fidl::InterfaceHandle vrf, fidl::InterfaceHandle focuser, + fidl::InterfaceHandle touch_source, fidl::InterfaceRequest keyboard_listener_request, OnEnableWireframe wireframe_enabled_callback, @@ -79,6 +80,8 @@ PlatformView::PlatformView( view_ref_(std::move(view_ref)), focus_delegate_( std::make_shared(std::move(vrf), std::move(focuser))), + pointer_delegate_( + std::make_shared(std::move(touch_source))), wireframe_enabled_callback_(std::move(wireframe_enabled_callback)), on_create_view_callback_(std::move(on_create_view_callback)), on_update_view_callback_(std::move(on_update_view_callback)), @@ -110,16 +113,46 @@ PlatformView::PlatformView( fuchsia::ui::input::ImeService::Name_, text_sync_service_.NewRequest().TakeChannel()); - focus_delegate_->WatchLoop([&](bool focused) { + focus_delegate_->WatchLoop([weak = weak_factory_.GetWeakPtr()](bool focused) { + if (!weak) { + FML_LOG(WARNING) << "PlatformView use-after-free attempted. Ignoring."; + return; + } + // Ensure last_text_state_ is set to make sure Flutter actually wants // an IME. - if (focused && last_text_state_ != nullptr) { - ActivateIme(); + if (focused && weak->last_text_state_) { + weak->ActivateIme(); } else if (!focused) { - DeactivateIme(); + weak->DeactivateIme(); } }); + pointer_delegate_->WatchLoop([weak = weak_factory_.GetWeakPtr()]( + std::vector events) { + if (!weak) { + FML_LOG(WARNING) << "PlatformView use-after-free attempted. Ignoring."; + return; + } + + if (events.size() == 0) { + return; // No work, bounce out. + } + + // If pixel ratio hasn't been set, use a default value of 1. + const float pixel_ratio = weak->view_pixel_ratio_.value_or(1.f); + auto packet = std::make_unique(events.size()); + for (size_t i = 0; i < events.size(); ++i) { + auto& event = events[i]; + // Translate logical to physical coordinates, as per flutter::PointerData + // contract. Done here because pixel ratio comes from the graphics API. + event.physical_x = event.physical_x * pixel_ratio; + event.physical_y = event.physical_y * pixel_ratio; + packet->SetPointerData(i, event); + } + weak->DispatchPointerDataPacket(std::move(packet)); + }); + // Finally! Register the native platform message handlers. RegisterPlatformMessageHandlers(); } @@ -484,7 +517,7 @@ void PlatformView::OnKeyEvent( } void PlatformView::ActivateIme() { - DEBUG_CHECK(last_text_state_ != nullptr, LOG_TAG, ""); + DEBUG_CHECK(last_text_state_, LOG_TAG, ""); text_sync_service_->GetInputMethodEditor( fuchsia::ui::input::KeyboardType::TEXT, // keyboard type @@ -769,8 +802,7 @@ bool PlatformView::HandleFlutterPlatformViewsChannelPlatformMessage( const int64_t view_id_raw = view_id->value.GetUint64(); auto on_view_created = fml::MakeCopyable( - [weak = weak_factory_.GetWeakPtr(), - platform_task_runner = task_runners_.GetPlatformTaskRunner(), + [platform_task_runner = task_runners_.GetPlatformTaskRunner(), message = std::move(message)]() { // The client is waiting for view creation. Send an empty response // back to signal the view was created. diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.h b/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.h index 34aaf8c83d..7ff209bdca 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.h +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -15,9 +16,13 @@ #include #include +#include #include +#include #include +#include #include +#include #include "flow/embedded_views.h" #include "flutter/fml/macros.h" @@ -28,6 +33,7 @@ #include "flutter/shell/platform/fuchsia/flutter/keyboard.h" #include "flutter/shell/platform/fuchsia/flutter/vsync_waiter.h" #include "focus_delegate.h" +#include "pointer_delegate.h" namespace flutter_runner { @@ -60,29 +66,31 @@ class PlatformView : public flutter::PlatformView, private fuchsia::ui::input3::KeyboardListener, private fuchsia::ui::input::InputMethodEditorClient { public: - PlatformView(flutter::PlatformView::Delegate& delegate, - std::string debug_label, - fuchsia::ui::views::ViewRef view_ref, - flutter::TaskRunners task_runners, - std::shared_ptr runner_services, - fidl::InterfaceHandle - parent_environment_service_provider, - fidl::InterfaceHandle vrf, - fidl::InterfaceHandle focuser, - fidl::InterfaceRequest - keyboard_listener, - OnEnableWireframe wireframe_enabled_callback, - OnCreateView on_create_view_callback, - OnUpdateView on_update_view_callback, - OnDestroyView on_destroy_view_callback, - OnCreateSurface on_create_surface_callback, - OnSemanticsNodeUpdate on_semantics_node_update_callback, - OnRequestAnnounce on_request_announce_callback, - OnShaderWarmup on_shader_warmup, - std::shared_ptr view_embedder, - AwaitVsyncCallback await_vsync_callback, - AwaitVsyncForSecondaryCallbackCallback - await_vsync_for_secondary_callback_callback); + PlatformView( + flutter::PlatformView::Delegate& delegate, + std::string debug_label, + fuchsia::ui::views::ViewRef view_ref, + flutter::TaskRunners task_runners, + std::shared_ptr runner_services, + fidl::InterfaceHandle + parent_environment_service_provider, + fidl::InterfaceHandle vrf, + fidl::InterfaceHandle focuser, + fidl::InterfaceHandle touch_source, + fidl::InterfaceRequest + keyboard_listener, + OnEnableWireframe wireframe_enabled_callback, + OnCreateView on_create_view_callback, + OnUpdateView on_update_view_callback, + OnDestroyView on_destroy_view_callback, + OnCreateSurface on_create_surface_callback, + OnSemanticsNodeUpdate on_semantics_node_update_callback, + OnRequestAnnounce on_request_announce_callback, + OnShaderWarmup on_shader_warmup, + std::shared_ptr view_embedder, + AwaitVsyncCallback await_vsync_callback, + AwaitVsyncForSecondaryCallbackCallback + await_vsync_for_secondary_callback_callback); virtual ~PlatformView(); @@ -178,6 +186,7 @@ class PlatformView : public flutter::PlatformView, // alive there const fuchsia::ui::views::ViewRef view_ref_; std::shared_ptr focus_delegate_; + std::shared_ptr pointer_delegate_; // Logical size and origin, and logical->physical ratio. These are optional // to provide an "unset" state during program startup, before Scenic has sent diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view_unittest.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view_unittest.cc index 6db634d165..8cbebd8575 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view_unittest.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view_unittest.cc @@ -29,7 +29,9 @@ #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 { @@ -207,6 +209,12 @@ class PlatformViewBuilder { return *this; } + PlatformViewBuilder& SetTouchSource( + fidl::InterfaceHandle touch_source) { + touch_source_ = std::move(touch_source); + return *this; + } + PlatformViewBuilder& SetDestroyViewCallback(OnDestroyView callback) { on_destroy_view_callback_ = std::move(callback); return *this; @@ -263,7 +271,8 @@ class PlatformViewBuilder { delegate_, debug_label_, std::move(view_ref_), task_runners_, runner_services_, std::move(parent_environment_service_provider_), std::move(session_listener_request_), std::move(vrf_), - std::move(focuser_), std::move(keyboard_listener_), + std::move(focuser_), std::move(touch_source_), + std::move(keyboard_listener_), std::move(on_session_listener_error_callback_), std::move(wireframe_enabled_callback_), std::move(on_create_view_callback_), @@ -295,6 +304,8 @@ class PlatformViewBuilder { session_listener_request_{nullptr}; fidl::InterfaceHandle vrf_{nullptr}; fidl::InterfaceHandle focuser_{nullptr}; + fidl::InterfaceHandle touch_source_{ + nullptr}; fidl::InterfaceRequest keyboard_listener_{nullptr}; fit::closure on_session_listener_error_callback_{nullptr}; @@ -1374,6 +1385,112 @@ TEST_F(PlatformViewTests, OnShaderWarmup) { EXPECT_EQ(expected_result_string, response->result_string); } +TEST_F(PlatformViewTests, TouchSource_LogicalToPhysicalConversion) { + // Names and constants + using fup_EventPhase = fuchsia::ui::pointer::EventPhase; + using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; + using fup_TouchIxnId = fuchsia::ui::pointer::TouchInteractionId; + using fup_TouchIxnStatus = fuchsia::ui::pointer::TouchInteractionStatus; + + constexpr std::array, 2> kRect = {{{0, 0}, {20, 20}}}; + constexpr std::array kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1}; + constexpr fup_TouchIxnId kIxnOne = { + .device_id = 0u, .pointer_id = 1u, .interaction_id = 2u}; + constexpr float valid_pixel_ratio = 2.f; + + // Setup + sys::testing::ServiceDirectoryProvider services_provider(dispatcher()); + MockPlatformViewDelegate delegate; + flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr, + nullptr); + + FakeTouchSource touch_server; + fidl::BindingSet touch_bindings; + auto touch_handle = touch_bindings.AddBinding(&touch_server); + + fuchsia::ui::scenic::SessionListenerPtr session_listener; + + flutter_runner::GfxPlatformView platform_view = + PlatformViewBuilder(delegate, std::move(task_runners), + services_provider.service_directory()) + .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 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)); + + // Inject + std::vector events = + TouchEventBuilder::New() + .AddTime(/* in nanoseconds */ 1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_server.ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + // Unpack + std::vector> packets = + delegate.TakePointerDataPackets(); + ASSERT_EQ(packets.size(), 1u); + std::vector 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); +} + TEST_F(PlatformViewTests, DownPointerNumericNudge) { using ScenicEvent = fuchsia::ui::scenic::Event; using GfxEvent = fuchsia::ui::gfx::Event; diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.cc new file mode 100644 index 0000000000..72b2789bac --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.cc @@ -0,0 +1,239 @@ +// 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 "pointer_delegate.h" + +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" + +namespace fuchsia::ui::pointer { +// For using TouchInteractionId as a map key. +bool operator==(const fuchsia::ui::pointer::TouchInteractionId& a, + const fuchsia::ui::pointer::TouchInteractionId& b) { + return a.device_id == b.device_id && a.pointer_id == b.pointer_id && + a.interaction_id == b.interaction_id; +} +} // namespace fuchsia::ui::pointer + +namespace flutter_runner { + +using fup_EventPhase = fuchsia::ui::pointer::EventPhase; +using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; +using fup_TouchIxnStatus = fuchsia::ui::pointer::TouchInteractionStatus; +using fup_TouchResponse = fuchsia::ui::pointer::TouchResponse; +using fup_TouchResponseType = fuchsia::ui::pointer::TouchResponseType; +using fup_ViewParameters = fuchsia::ui::pointer::ViewParameters; + +namespace { +void MaybeIssueTraceEvent(const fup_TouchEvent& event) { + if (event.has_trace_flow_id()) { + TRACE_FLOW_END("input", "dispatch_event_to_client", event.trace_flow_id()); + } +} + +bool HasValidatedPointerSample(const fup_TouchEvent& event) { + if (!event.has_pointer_sample()) { + return false; + } + FML_DCHECK(event.pointer_sample().has_interaction()) << "API guarantee"; + FML_DCHECK(event.pointer_sample().has_phase()) << "API guarantee"; + FML_DCHECK(event.pointer_sample().has_position_in_viewport()) + << "API guarantee"; + return true; +} + +std::array ViewportToViewCoordinates( + std::array viewport_coordinates, + const std::array& viewport_to_view_transform) { + // The transform matrix is a FIDL array with matrix data in column-major + // order. For a matrix with data [a b c d e f g h i], and with the viewport + // coordinates expressed as homogeneous coordinates, the logical view + // coordinates are obtained with the following formula: + // |a d g| |x| |x'| + // |b e h| * |y| = |y'| + // |c f i| |1| |w'| + // which we then normalize based on the w component: + // if z' not zero: (x'/w', y'/w') + // else (x', y') + const auto& M = viewport_to_view_transform; + const float x = viewport_coordinates[0]; + const float y = viewport_coordinates[1]; + const float xp = M[0] * x + M[3] * y + M[6]; + const float yp = M[1] * x + M[4] * y + M[7]; + const float wp = M[2] * x + M[5] * y + M[8]; + if (wp != 0) { + return {xp / wp, yp / wp}; + } else { + return {xp, yp}; + } +} + +flutter::PointerData::Change GetChangeFromPointerEventPhase( + fup_EventPhase phase) { + switch (phase) { + case fup_EventPhase::ADD: + return flutter::PointerData::Change::kAdd; + case fup_EventPhase::CHANGE: + return flutter::PointerData::Change::kMove; + case fup_EventPhase::REMOVE: + return flutter::PointerData::Change::kRemove; + case fup_EventPhase::CANCEL: + return flutter::PointerData::Change::kCancel; + default: + return flutter::PointerData::Change::kCancel; + } +} + +std::array ClampToViewSpace(const float x, + const float y, + const fup_ViewParameters& p) { + const float min_x = p.view.min[0]; + const float min_y = p.view.min[1]; + const float max_x = p.view.max[0]; + const float max_y = p.view.max[1]; + if (min_x <= x && x < max_x && min_y <= y && y < max_y) { + return {x, y}; // No clamping to perform. + } + + // View boundary is [min_x, max_x) x [min_y, max_y). Note that min is + // inclusive, but max is exclusive - so we subtract epsilon. + const float max_x_inclusive = max_x - std::numeric_limits::epsilon(); + const float max_y_inclusive = max_y - std::numeric_limits::epsilon(); + const float& clamped_x = std::clamp(x, min_x, max_x_inclusive); + const float& clamped_y = std::clamp(y, min_y, max_y_inclusive); + FML_LOG(INFO) << "Clamped (" << x << ", " << y << ") to (" << clamped_x + << ", " << clamped_y << ")."; + return {clamped_x, clamped_y}; +} + +// It returns a "draft" because the coordinates are logical. Later, view pixel +// ratio is applied to obtain physical coordinates. +// +// The flutter pointerdata state machine has extra phases, which this function +// synthesizes on the fly. Hence the return data is a flutter pointerdata, and +// optionally a second synthesized one. +// For example: , , . +// +// Flutter gestures expect a gesture to start within the logical view space, and +// is not tolerant of floating point drift. This function coerces just the DOWN +// event's coordinate to start within the logical view. +std::pair> +CreatePointerDraft(const fup_TouchEvent& event, + const fup_ViewParameters& view_parameters) { + FML_DCHECK(HasValidatedPointerSample(event)) << "precondition"; + const auto& sample = event.pointer_sample(); + flutter::PointerData ptr; + ptr.Clear(); + ptr.time_stamp = event.timestamp() / 1000; // in microseconds + ptr.change = GetChangeFromPointerEventPhase(sample.phase()); + ptr.kind = flutter::PointerData::DeviceKind::kTouch; + ptr.device = sample.interaction().device_id; + ptr.pointer_identifier = sample.interaction().pointer_id; + // View parameters can change mid-interaction; apply transform on the fly. + auto logical = + ViewportToViewCoordinates(sample.position_in_viewport(), + view_parameters.viewport_to_view_transform); + ptr.physical_x = logical[0]; // Not yet physical; adjusted in PlatformView. + ptr.physical_y = logical[1]; // Not yet physical; adjusted in PlatformView. + + // Match Flutter pointer's state machine with synthesized events. + if (ptr.change == flutter::PointerData::Change::kAdd) { + flutter::PointerData down; + memcpy(&down, &ptr, sizeof(flutter::PointerData)); + down.change = flutter::PointerData::Change::kDown; + { // DOWN event needs to start in the logical view space. + auto [x, y] = + ClampToViewSpace(down.physical_x, down.physical_y, view_parameters); + down.physical_x = x; + down.physical_y = y; + } + return {std::move(ptr), std::move(down)}; + } else if (ptr.change == flutter::PointerData::Change::kRemove) { + flutter::PointerData up; + memcpy(&up, &ptr, sizeof(flutter::PointerData)); + up.change = flutter::PointerData::Change::kUp; + return {std::move(up), std::move(ptr)}; + } else { + return {std::move(ptr), std::nullopt}; + } +} + +// Helper to insert one or two events into a vector buffer. +void InsertIntoBuffer( + std::pair> events, + std::vector* buffer) { + FML_DCHECK(buffer); + buffer->emplace_back(std::move(events.first)); + if (events.second.has_value()) { + buffer->emplace_back(std::move(events.second.value())); + } +} +} // namespace + +// Core logic of this class. +void PointerDelegate::WatchLoop( + std::function)> callback) { + FML_LOG(INFO) << "Flutter - PointerDelegate started."; + if (watch_loop_) { + FML_LOG(ERROR) << "PointerDelegate::WatchLoop() must be called once."; + return; + } + + watch_loop_ = [this, callback](std::vector events) { + TRACE_EVENT0("flutter", "PointerDelegate::TouchHandler"); + FML_DCHECK(responses_.empty()) << "precondition"; + std::vector to_client; + for (const fup_TouchEvent& event : events) { + MaybeIssueTraceEvent(event); + fup_TouchResponse + response; // Response per event, matched on event's index. + if (event.has_view_parameters()) { + view_parameters_ = std::move(event.view_parameters()); + } + if (HasValidatedPointerSample(event)) { + const auto& sample = event.pointer_sample(); + const auto& ixn = sample.interaction(); + if (sample.phase() == fup_EventPhase::ADD && + !event.has_interaction_result()) { + buffer_.emplace(ixn, std::vector()); + } + + FML_DCHECK(view_parameters_.has_value()) << "API guarantee"; + auto events = CreatePointerDraft(event, view_parameters_.value()); + if (buffer_.count(ixn) > 0) { + InsertIntoBuffer(std::move(events), &buffer_[ixn]); + } else { + InsertIntoBuffer(std::move(events), &to_client); + } + // For this simple client, always claim we want the gesture. + response.set_response_type(fup_TouchResponseType::YES_PRIORITIZE); + } + if (event.has_interaction_result()) { + const auto& result = event.interaction_result(); + const auto& ixn = result.interaction; + if (result.status == fup_TouchIxnStatus::GRANTED && + buffer_.count(ixn) > 0) { + FML_DCHECK(to_client.empty()) << "invariant"; + to_client.insert(to_client.end(), buffer_[ixn].begin(), + buffer_[ixn].end()); + } + buffer_.erase(ixn); // Result seen, delete the buffer. + } + responses_.push_back(std::move(response)); + } + callback(std::move(to_client)); // Notify client of touch events, if any. + + touch_source_->Watch(std::move(responses_), /*copy*/ watch_loop_); + responses_.clear(); + }; + + touch_source_->Watch(std::move(responses_), /*copy*/ watch_loop_); + responses_.clear(); +} + +} // namespace flutter_runner diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.h b/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.h new file mode 100644 index 0000000000..6de02e8032 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate.h @@ -0,0 +1,105 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_POINTER_DELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_POINTER_DELEGATE_H_ + +#include + +#include +#include +#include +#include + +#include "flutter/lib/ui/window/pointer_data.h" + +namespace flutter_runner { + +// Helper class for keying into a map. +struct IxnHasher { + std::size_t operator()( + const fuchsia::ui::pointer::TouchInteractionId& ixn) const { + return std::hash()(ixn.device_id) ^ + std::hash()(ixn.pointer_id) ^ + std::hash()(ixn.interaction_id); + } +}; + +// Channel processor for fuchsia.ui.pointer.TouchSource protocol. It manages the +// channel state, collects touch events, and surfaces them to PlatformView as +// flutter::PointerData events for further processing and dispatch. +class PointerDelegate { + public: + PointerDelegate( + fidl::InterfaceHandle touch_source) + : touch_source_(touch_source.Bind()) {} + + // Each TouchEvent must carry a TouchPointerSample, and the supplied callback + // will translate each to a flutter::PointerData, and the vector of + // PointerData placed in a PointerDataPacket for transport to the Engine. + void WatchLoop( + std::function)> callback); + + private: + // Channel for touch events from Scenic. + fuchsia::ui::pointer::TouchSourcePtr touch_source_; + + // Receive touch events from Scenic. Must be copyable. + std::function)> + watch_loop_; + + // Per-interaction buffer of touch events from Scenic. When an interaction + // starts with event.pointer_sample.phase == ADD, we allocate a buffer and + // store samples. When interaction ownership becomes + // event.interaction_result.status == GRANTED, we flush the buffer to client, + // delete the buffer, and all future events in this interaction are flushed + // direct to client. When interaction ownership becomes DENIED, we delete the + // buffer, and the client does not get any previous or future events in this + // interaction. + // + // There are three basic interaction forms that we need to handle, and the API + // guarantees we see only these three forms. S=sample, R(g)=result-granted, + // R(d)=result-denied, and + means packaged in the same table. Time flows from + // left to right. Samples start with ADD, and end in REMOVE or CANCEL. Each + // interaction receives just one ownership result. + // (1) Late grant. S S S R(g) S S S + // (1-a) Combo. S S S+R(g) S S S + // (2) Early grant. S+R(g) S S S S S + // (3) Late deny. S S S R(d) + // (3-a) Combo. S S S+R(d) + // + // This results in the following high-level algorithm to correctly deal with + // buffer allocation and deletion, and event flushing or event dropping based + // on ownership. + // if event.sample.phase == ADD && !event.result + // allocate buffer[event.sample.interaction] + // if buffer[event.sample.interaction] + // buffer[event.sample.interaction].push(event.sample) + // else + // flush_to_client(event.sample) + // if event.result + // if event.result == GRANTED + // flush_to_client(buffer[event.result.interaction]) + // delete buffer[event.result.interaction] + std::unordered_map, + IxnHasher> + buffer_; + + // The fuchsia.ui.pointer.TouchSource protocol allows one in-flight + // hanging-get Watch() call to gather touch events, and the client is expected + // to respond with consumption intent on the following hanging-get Watch() + // call. Store responses here for the next call. + std::vector responses_; + + // The fuchsia.ui.pointer.TouchSource protocol issues a channel-global view + // parameters on connection and on change. Events must apply these view + // parameters to correctly map to logical view coordinates. The "nullopt" + // state represents the absence of view parameters, early in the protocol + // lifecycle. + std::optional view_parameters_; +}; + +} // namespace flutter_runner +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_POINTER_DELEGATE_H_ diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc new file mode 100644 index 0000000000..daaa15e0a6 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/pointer_delegate_unittests.cc @@ -0,0 +1,669 @@ +// 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 +#include +#include +#include +#include + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" +#include "pointer_delegate.h" +#include "tests/fakes/touch_source.h" +#include "tests/pointer_event_utility.h" + +namespace flutter_runner::testing { + +using fup_EventPhase = fuchsia::ui::pointer::EventPhase; +using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; +using fup_TouchIxnId = fuchsia::ui::pointer::TouchInteractionId; +using fup_TouchIxnResult = fuchsia::ui::pointer::TouchInteractionResult; +using fup_TouchIxnStatus = fuchsia::ui::pointer::TouchInteractionStatus; +using fup_TouchPointerSample = fuchsia::ui::pointer::TouchPointerSample; +using fup_TouchResponse = fuchsia::ui::pointer::TouchResponse; +using fup_TouchResponseType = fuchsia::ui::pointer::TouchResponseType; +using fup_ViewParameters = fuchsia::ui::pointer::ViewParameters; + +constexpr std::array, 2> kRect = {{{0, 0}, {20, 20}}}; +constexpr std::array kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1}; +constexpr fup_TouchIxnId kIxnOne = {.device_id = 0u, + .pointer_id = 1u, + .interaction_id = 2u}; + +// Fixture to exercise Flutter runner's implementation for +// fuchsia.ui.pointer.TouchSource. +class PointerDelegateTest : public ::testing::Test { + protected: + PointerDelegateTest() : loop_(&kAsyncLoopConfigAttachToCurrentThread) { + touch_source_ = std::make_unique(); + pointer_delegate_ = std::make_unique( + touch_source_bindings_.AddBinding(touch_source_.get())); + } + + void RunLoopUntilIdle() { loop_.RunUntilIdle(); } + + std::unique_ptr touch_source_; + std::unique_ptr pointer_delegate_; + + private: + async::Loop loop_; + fidl::BindingSet touch_source_bindings_; + + FML_DISALLOW_COPY_AND_ASSIGN(PointerDelegateTest); +}; + +TEST_F(PointerDelegateTest, Data_FuchsiaTimeVersusFlutterTime) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD -> Flutter ADD+DOWN + std::vector events = + TouchEventBuilder::New() + .AddTime(/* in nanoseconds */ 1111789u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + EXPECT_EQ((*pointers)[0].time_stamp, /* in microseconds */ 1111u); + EXPECT_EQ((*pointers)[1].time_stamp, /* in microseconds */ 1111u); +} + +TEST_F(PointerDelegateTest, Phase_FlutterPhasesAreSynthesized) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD -> Flutter ADD+DOWN + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ((*pointers)[1].change, flutter::PointerData::Change::kDown); + + // Fuchsia CHANGE -> Flutter MOVE + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 1u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kMove); + + // Fuchsia REMOVE -> Flutter UP+REMOVE + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddSample(kIxnOne, fup_EventPhase::REMOVE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kUp); + EXPECT_EQ((*pointers)[1].change, flutter::PointerData::Change::kRemove); +} + +TEST_F(PointerDelegateTest, Phase_FuchsiaCancelBecomesFlutterCancel) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD -> Flutter ADD+DOWN + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ((*pointers)[1].change, flutter::PointerData::Change::kDown); + + // Fuchsia CANCEL -> Flutter CANCEL + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CANCEL, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 1u); + EXPECT_EQ((*pointers)[0].change, flutter::PointerData::Change::kCancel); +} + +TEST_F(PointerDelegateTest, Coordinates_CorrectMapping) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD event, with a view parameter that maps the viewport identically + // to the view. Then the center point of the viewport should map to the center + // of the view, (10.f, 10.f). + std::vector events = + TouchEventBuilder::New() + .AddTime(2222000u) + .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, + /*viewport*/ {{{0, 0}, {20, 20}}}, + /*matrix*/ {1, 0, 0, 0, 1, 0, 0, 0, 1}) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); // ADD - DOWN + EXPECT_FLOAT_EQ((*pointers)[0].physical_x, 10.f); + EXPECT_FLOAT_EQ((*pointers)[0].physical_y, 10.f); + pointers = {}; + + // Fuchsia CHANGE event, with a view parameter that translates the viewport by + // (10, 10) within the view. Then the minimal point in the viewport (its + // origin) should map to the center of the view, (10.f, 10.f). + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, + /*viewport*/ {{{0, 0}, {20, 20}}}, + /*matrix*/ {1, 0, 0, 0, 1, 0, 10, 10, 1}) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {0.f, 0.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 1u); // MOVE + EXPECT_FLOAT_EQ((*pointers)[0].physical_x, 10.f); + EXPECT_FLOAT_EQ((*pointers)[0].physical_y, 10.f); + + // Fuchsia CHANGE event, with a view parameter that scales the viewport by + // (0.5, 0.5) within the view. Then the maximal point in the viewport should + // map to the center of the view, (10.f, 10.f). + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddViewParameters(/*view*/ {{{0, 0}, {20, 20}}}, + /*viewport*/ {{{0, 0}, {20, 20}}}, + /*matrix*/ {0.5f, 0, 0, 0, 0.5f, 0, 0, 0, 1}) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {20.f, 20.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 1u); // MOVE + EXPECT_FLOAT_EQ((*pointers)[0].physical_x, 10.f); + EXPECT_FLOAT_EQ((*pointers)[0].physical_y, 10.f); +} + +TEST_F(PointerDelegateTest, Coordinates_DownEventClampedToView) { + const float kSmallDiscrepancy = -0.00003f; + + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, kSmallDiscrepancy}) + .AddResult( + {.interaction = kIxnOne, .status = fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers->size(), 2u); + + const auto& add_event = (*pointers)[0]; + EXPECT_FLOAT_EQ(add_event.physical_x, 10.f); + EXPECT_FLOAT_EQ(add_event.physical_y, kSmallDiscrepancy); + + const auto& down_event = (*pointers)[1]; + EXPECT_FLOAT_EQ(down_event.physical_x, 10.f); + EXPECT_EQ(down_event.physical_y, 0.f); +} + +TEST_F(PointerDelegateTest, Protocol_FirstResponseIsEmpty) { + bool called = false; + pointer_delegate_->WatchLoop( + [&called](std::vector events) { called = true; }); + RunLoopUntilIdle(); // Server gets Watch call. + + EXPECT_FALSE(called); // No events yet received to forward to client. + // Server sees an initial "response" from client, which is empty, by contract. + const auto responses = touch_source_->UploadedResponses(); + ASSERT_TRUE(responses.has_value()); + ASSERT_EQ(responses->size(), 0u); +} + +TEST_F(PointerDelegateTest, Protocol_ResponseMatchesEarlierEvents) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia view parameter only. Empty response. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .BuildAsVector(); + + // Fuchsia ptr 1 ADD sample. Yes response. + fup_TouchEvent e1 = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample({.device_id = 0u, .pointer_id = 1u, .interaction_id = 3u}, + fup_EventPhase::ADD, {10.f, 10.f}) + .Build(); + events.emplace_back(std::move(e1)); + + // Fuchsia ptr 2 ADD sample. Yes response. + fup_TouchEvent e2 = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddSample({.device_id = 0u, .pointer_id = 2u, .interaction_id = 3u}, + fup_EventPhase::ADD, {5.f, 5.f}) + .Build(); + events.emplace_back(std::move(e2)); + + // Fuchsia ptr 3 ADD sample. Yes response. + fup_TouchEvent e3 = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddSample({.device_id = 0u, .pointer_id = 3u, .interaction_id = 3u}, + fup_EventPhase::ADD, {1.f, 1.f}) + .Build(); + events.emplace_back(std::move(e3)); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + const auto responses = touch_source_->UploadedResponses(); + ASSERT_TRUE(responses.has_value()); + ASSERT_EQ(responses.value().size(), 4u); + // Event 0 did not carry a sample, so no response. + EXPECT_FALSE(responses.value()[0].has_response_type()); + // Events 1-3 had a sample, must have a response. + EXPECT_TRUE(responses.value()[1].has_response_type()); + EXPECT_EQ(responses.value()[1].response_type(), + fup_TouchResponseType::YES_PRIORITIZE); + EXPECT_TRUE(responses.value()[2].has_response_type()); + EXPECT_EQ(responses.value()[2].response_type(), + fup_TouchResponseType::YES_PRIORITIZE); + EXPECT_TRUE(responses.value()[3].has_response_type()); + EXPECT_EQ(responses.value()[3].response_type(), + fup_TouchResponseType::YES_PRIORITIZE); +} + +TEST_F(PointerDelegateTest, Protocol_LateGrant) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, no grant result - buffer it. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, no grant result - buffer it. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia result: ownership granted. Buffered pointers released. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 3u); // ADD - DOWN - MOVE + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + EXPECT_EQ(pointers.value()[2].change, flutter::PointerData::Change::kMove); + pointers = {}; + + // Fuchsia CHANGE, grant result - release immediately. + events = TouchEventBuilder::New() + .AddTime(/* in nanoseconds */ 4444000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kMove); + EXPECT_EQ(pointers.value()[0].time_stamp, /* in microseconds */ 4444u); + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_LateGrantCombo) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, no grant result - buffer it. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, no grant result - buffer it. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, with grant result - release buffered events. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 4u); // ADD - DOWN - MOVE - MOVE + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[0].time_stamp, 1111u); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + EXPECT_EQ(pointers.value()[1].time_stamp, 1111u); + EXPECT_EQ(pointers.value()[2].change, flutter::PointerData::Change::kMove); + EXPECT_EQ(pointers.value()[2].time_stamp, 2222u); + EXPECT_EQ(pointers.value()[3].change, flutter::PointerData::Change::kMove); + EXPECT_EQ(pointers.value()[3].time_stamp, 3333u); + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_EarlyGrant) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, with grant result - release immediately. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 2u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + pointers = {}; + + // Fuchsia CHANGE, after grant result - release immediately. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 1u); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kMove); + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_LateDeny) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, no grant result - buffer it. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, no grant result - buffer it. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia result: ownership denied. Buffered pointers deleted. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddResult({kIxnOne, fup_TouchIxnStatus::DENIED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 0u); // Do not release to client! + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_LateDenyCombo) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + // Fuchsia ADD, no grant result - buffer it. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia CHANGE, no grant result - buffer it. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddSample(kIxnOne, fup_EventPhase::CHANGE, {10.f, 10.f}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Fuchsia result: ownership denied. Buffered pointers deleted. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddSample(kIxnOne, fup_EventPhase::CANCEL, {10.f, 10.f}) + .AddResult({kIxnOne, fup_TouchIxnStatus::DENIED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 0u); // Do not release to client! + pointers = {}; +} + +TEST_F(PointerDelegateTest, Protocol_PointersAreIndependent) { + std::optional> pointers; + pointer_delegate_->WatchLoop( + [&pointers](std::vector events) { + pointers = std::move(events); + }); + RunLoopUntilIdle(); // Server gets watch call. + + constexpr fup_TouchIxnId kIxnTwo = { + .device_id = 0u, .pointer_id = 2u, .interaction_id = 2u}; + + // Fuchsia ptr1 ADD and ptr2 ADD, no grant result for either - buffer them. + std::vector events = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddViewParameters(kRect, kRect, kIdentity) + .AddSample(kIxnOne, fup_EventPhase::ADD, {10.f, 10.f}) + .BuildAsVector(); + fup_TouchEvent ptr2 = + TouchEventBuilder::New() + .AddTime(1111000u) + .AddSample(kIxnTwo, fup_EventPhase::ADD, {15.f, 15.f}) + .Build(); + events.emplace_back(std::move(ptr2)); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + EXPECT_EQ(pointers.value().size(), 0u); + pointers = {}; + + // Server grants win to pointer 2. + events = TouchEventBuilder::New() + .AddTime(2222000u) + .AddResult({kIxnTwo, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 2u); + EXPECT_EQ(pointers.value()[0].pointer_identifier, 2); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[1].pointer_identifier, 2); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + pointers = {}; + + // Server grants win to pointer 1. + events = TouchEventBuilder::New() + .AddTime(3333000u) + .AddResult({kIxnOne, fup_TouchIxnStatus::GRANTED}) + .BuildAsVector(); + touch_source_->ScheduleCallback(std::move(events)); + RunLoopUntilIdle(); + + ASSERT_TRUE(pointers.has_value()); + ASSERT_EQ(pointers.value().size(), 2u); + EXPECT_EQ(pointers.value()[0].pointer_identifier, 1); + EXPECT_EQ(pointers.value()[0].change, flutter::PointerData::Change::kAdd); + EXPECT_EQ(pointers.value()[1].pointer_identifier, 1); + EXPECT_EQ(pointers.value()[1].change, flutter::PointerData::Change::kDown); + pointers = {}; +} + +} // namespace flutter_runner::testing diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/BUILD.gn b/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/BUILD.gn index 3ab5ab00f6..259ded8020 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/BUILD.gn +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/BUILD.gn @@ -19,6 +19,7 @@ source_set("focus") { sources = [ "focuser.h", "platform_message.h", + "touch_source.h", "view_ref_focused.h", ] diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/touch_source.h b/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/touch_source.h new file mode 100644 index 0000000000..99cfc050d4 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/tests/fakes/touch_source.h @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_TESTS_FAKES_TOUCH_SOURCE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_TESTS_FAKES_TOUCH_SOURCE_H_ + +#include + +#include +#include + +#include "flutter/fml/logging.h" + +namespace flutter_runner::testing { + +// A test stub to act as the protocol server. A test can control what is sent +// back by this server implementation, via the ScheduleCallback call. +class FakeTouchSource : public fuchsia::ui::pointer::TouchSource { + public: + // |fuchsia.ui.pointer.TouchSource| + void Watch(std::vector responses, + TouchSource::WatchCallback callback) override { + responses_ = std::move(responses); + callback_ = std::move(callback); + } + + // Have the server issue events to the client's hanging-get Watch call. + void ScheduleCallback(std::vector events) { + FML_CHECK(callback_) << "require a valid WatchCallback"; + callback_(std::move(events)); + } + + // Allow the test to observe what the client uploaded on the next Watch call. + std::optional> + UploadedResponses() { + auto responses = std::move(responses_); + responses_.reset(); + return responses; + } + + private: + // |fuchsia.ui.pointer.TouchSource| + void UpdateResponse(fuchsia::ui::pointer::TouchInteractionId ixn, + fuchsia::ui::pointer::TouchResponse response, + TouchSource::UpdateResponseCallback callback) override { + FML_UNREACHABLE(); + } + + // Client uploads responses to server. + std::optional> responses_; + + // Client-side logic to invoke on Watch() call's return. A test triggers it + // with ScheduleCallback(). + TouchSource::WatchCallback callback_; +}; + +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_TESTS_FAKES_TOUCH_SOURCE_H_ diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.cc new file mode 100644 index 0000000000..6e003bfea0 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.cc @@ -0,0 +1,80 @@ +// 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 "pointer_event_utility.h" + +namespace flutter_runner::testing { + +using fup_EventPhase = fuchsia::ui::pointer::EventPhase; +using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; +using fup_TouchIxnId = fuchsia::ui::pointer::TouchInteractionId; +using fup_TouchIxnResult = fuchsia::ui::pointer::TouchInteractionResult; +using fup_TouchPointerSample = fuchsia::ui::pointer::TouchPointerSample; +using fup_ViewParameters = fuchsia::ui::pointer::ViewParameters; + +TouchEventBuilder TouchEventBuilder::New() { + return TouchEventBuilder(); +} + +TouchEventBuilder& TouchEventBuilder::AddTime(zx_time_t time) { + time_ = time; + return *this; +} + +TouchEventBuilder& TouchEventBuilder::AddSample(fup_TouchIxnId id, + fup_EventPhase phase, + std::array position) { + sample_ = std::make_optional(); + sample_->set_interaction(id); + sample_->set_phase(phase); + sample_->set_position_in_viewport(position); + return *this; +} + +TouchEventBuilder& TouchEventBuilder::AddViewParameters( + std::array, 2> view, + std::array, 2> viewport, + std::array transform) { + params_ = std::make_optional(); + fuchsia::ui::pointer::Rectangle view_rect; + view_rect.min = view[0]; + view_rect.max = view[1]; + params_->view = view_rect; + fuchsia::ui::pointer::Rectangle viewport_rect; + viewport_rect.min = viewport[0]; + viewport_rect.max = viewport[1]; + params_->viewport = viewport_rect; + params_->viewport_to_view_transform = transform; + return *this; +} + +TouchEventBuilder& TouchEventBuilder::AddResult(fup_TouchIxnResult result) { + result_ = result; + return *this; +} + +fup_TouchEvent TouchEventBuilder::Build() { + fup_TouchEvent event; + if (time_) { + event.set_timestamp(time_.value()); + } + if (params_) { + event.set_view_parameters(std::move(params_.value())); + } + if (sample_) { + event.set_pointer_sample(std::move(sample_.value())); + } + if (result_) { + event.set_interaction_result(std::move(result_.value())); + } + return event; +} + +std::vector TouchEventBuilder::BuildAsVector() { + std::vector events; + events.emplace_back(Build()); + return events; +} + +} // namespace flutter_runner::testing diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.h b/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.h new file mode 100644 index 0000000000..f1702a74c6 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/tests/pointer_event_utility.h @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_TESTS_POINTER_EVENT_UTILITY_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_TESTS_POINTER_EVENT_UTILITY_H_ + +#include +#include + +#include +#include +#include + +namespace flutter_runner::testing { + +// A helper class for crafting a fuchsia.ui.pointer.TouchEvent table. +class TouchEventBuilder { + public: + static TouchEventBuilder New(); + + TouchEventBuilder& AddTime(zx_time_t time); + TouchEventBuilder& AddSample(fuchsia::ui::pointer::TouchInteractionId id, + fuchsia::ui::pointer::EventPhase phase, + std::array position); + TouchEventBuilder& AddViewParameters( + std::array, 2> view, + std::array, 2> viewport, + std::array transform); + TouchEventBuilder& AddResult( + fuchsia::ui::pointer::TouchInteractionResult result); + + fuchsia::ui::pointer::TouchEvent Build(); + std::vector BuildAsVector(); + + private: + std::optional time_; + std::optional params_; + std::optional sample_; + std::optional result_; +}; + +} // namespace flutter_runner::testing + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_TESTS_POINTER_EVENT_UTILITY_H_