diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 0084c7ed21..0600745f17 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1399,6 +1399,12 @@ FILE: ../../../flutter/shell/platform/fuchsia/flutter/component.h FILE: ../../../flutter/shell/platform/fuchsia/flutter/component_unittest.cc FILE: ../../../flutter/shell/platform/fuchsia/flutter/engine.cc FILE: ../../../flutter/shell/platform/fuchsia/flutter/engine.h +FILE: ../../../flutter/shell/platform/fuchsia/flutter/flatland_connection.cc +FILE: ../../../flutter/shell/platform/fuchsia/flutter/flatland_connection.h +FILE: ../../../flutter/shell/platform/fuchsia/flutter/flatland_external_view_embedder.cc +FILE: ../../../flutter/shell/platform/fuchsia/flutter/flatland_external_view_embedder.h +FILE: ../../../flutter/shell/platform/fuchsia/flutter/flatland_platform_view.cc +FILE: ../../../flutter/shell/platform/fuchsia/flutter/flatland_platform_view.h FILE: ../../../flutter/shell/platform/fuchsia/flutter/flutter_runner_fakes.h FILE: ../../../flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.cc FILE: ../../../flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.h @@ -1410,6 +1416,8 @@ FILE: ../../../flutter/shell/platform/fuchsia/flutter/fuchsia_external_view_embe FILE: ../../../flutter/shell/platform/fuchsia/flutter/fuchsia_intl.cc FILE: ../../../flutter/shell/platform/fuchsia/flutter/fuchsia_intl.h FILE: ../../../flutter/shell/platform/fuchsia/flutter/fuchsia_intl_unittest.cc +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 diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn b/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn index c4d126e84a..d39289fde5 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/BUILD.gn @@ -59,6 +59,12 @@ template("runner_sources") { "component.h", "engine.cc", "engine.h", + "flatland_connection.cc", + "flatland_connection.h", + "flatland_external_view_embedder.cc", + "flatland_external_view_embedder.h", + "flatland_platform_view.cc", + "flatland_platform_view.h", "flutter_runner_product_configuration.cc", "flutter_runner_product_configuration.h", "focus_delegate.cc", @@ -67,6 +73,8 @@ template("runner_sources") { "fuchsia_external_view_embedder.h", "fuchsia_intl.cc", "fuchsia_intl.h", + "gfx_platform_view.cc", + "gfx_platform_view.h", "gfx_session_connection.cc", "gfx_session_connection.h", "isolate_configurator.cc", @@ -129,6 +137,7 @@ template("runner_sources") { "$fuchsia_sdk_root/fidl:fuchsia.io", "$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.scenic", "$fuchsia_sdk_root/pkg:async-cpp", "$fuchsia_sdk_root/pkg:async-default", diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/component.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/component.cc index c7efd208b5..0cd0c183f0 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/component.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/component.cc @@ -639,6 +639,29 @@ void Application::CreateViewWithViewRef( )); } +void Application::CreateView2(fuchsia::ui::app::CreateView2Args view_args) { + if (!svc_) { + FML_DLOG(ERROR) + << "Component incoming services was invalid when attempting to " + "create a shell for a view provider request."; + return; + } + + shell_holders_.emplace(std::make_unique( + *this, // delegate + debug_label_, // thread label + svc_, // Component incoming services + runner_incoming_services_, // Runner incoming services + settings_, // settings + std::move( + *view_args.mutable_view_creation_token()), // view creation token + scenic::ViewRefPair::New(), // view ref pair + std::move(fdio_ns_), // FDIO namespace + std::move(directory_request_), // outgoing request + product_config_ // product configuration + )); +} + #if !defined(DART_PRODUCT) void Application::WriteProfileToTrace() const { for (const auto& engine : shell_holders_) { diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/component.h b/engine/src/flutter/shell/platform/fuchsia/flutter/component.h index 7955c10225..8812b33c16 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/component.h +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/component.h @@ -128,6 +128,9 @@ class Application final : public Engine::Delegate, fuchsia::ui::views::ViewRefControl control_ref, fuchsia::ui::views::ViewRef view_ref) override; + // |fuchsia::ui::app::ViewProvider| + void CreateView2(fuchsia::ui::app::CreateView2Args view_args) override; + // |flutter::Engine::Delegate| void OnEngineTerminate(const Engine* holder) override; diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc index 502b799535..62ba6362be 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/engine.cc @@ -6,6 +6,7 @@ #include #include +#include #include "flutter/common/graphics/persistent_cache.h" #include "flutter/common/task_runners.h" @@ -23,9 +24,10 @@ #include "../runtime/dart/utils/files.h" #include "../runtime/dart/utils/root_inspect_node.h" +#include "flatland_platform_view.h" #include "focus_delegate.h" #include "fuchsia_intl.h" -#include "platform_view.h" +#include "gfx_platform_view.h" #include "surface.h" #include "vsync_waiter.h" @@ -61,8 +63,50 @@ Engine::Engine(Delegate& delegate, : delegate_(delegate), thread_label_(std::move(thread_label)), thread_host_(CreateThreadHost(thread_label_)), + view_token_(std::move(view_token)), + view_ref_pair_(std::move(view_ref_pair)), intercept_all_input_(product_config.get_intercept_all_input()), weak_factory_(this) { + Initialize(/*=use_flatland*/ false, std::move(svc), + std::move(runner_services), std::move(settings), + std::move(fdio_ns), std::move(directory_request), + std::move(product_config)); +} + +Engine::Engine(Delegate& delegate, + std::string thread_label, + std::shared_ptr svc, + std::shared_ptr runner_services, + flutter::Settings settings, + fuchsia::ui::views::ViewCreationToken view_creation_token, + scenic::ViewRefPair view_ref_pair, + UniqueFDIONS fdio_ns, + fidl::InterfaceRequest directory_request, + FlutterRunnerProductConfiguration product_config) + : delegate_(delegate), + thread_label_(std::move(thread_label)), + thread_host_(CreateThreadHost(thread_label_)), + view_creation_token_(std::move(view_creation_token)), + view_ref_pair_(std::move(view_ref_pair)), + intercept_all_input_(product_config.get_intercept_all_input()), + weak_factory_(this) { + Initialize(/*=use_flatland*/ true, std::move(svc), std::move(runner_services), + std::move(settings), std::move(fdio_ns), + std::move(directory_request), std::move(product_config)); +} + +void Engine::Initialize( + bool use_flatland, + std::shared_ptr svc, + std::shared_ptr runner_services, + flutter::Settings settings, + UniqueFDIONS fdio_ns, + fidl::InterfaceRequest directory_request, + FlutterRunnerProductConfiguration product_config) { + // Flatland uses |view_creation_token_| for linking. Gfx uses |view_token_|. + FML_CHECK((use_flatland && view_creation_token_.value.is_valid()) || + (!use_flatland && view_token_.value.is_valid())); + // Get the task runners from the managed threads. The current thread will be // used as the "platform" thread. fml::RefPtr platform_task_runner = @@ -93,15 +137,15 @@ Engine::Engine(Delegate& delegate, // Make clones of the `ViewRef` before sending it down to Scenic, since the // refs are not copyable, and multiple consumers need view refs. fuchsia::ui::views::ViewRef platform_view_ref; - view_ref_pair.view_ref.Clone(&platform_view_ref); + view_ref_pair_.view_ref.Clone(&platform_view_ref); fuchsia::ui::views::ViewRef accessibility_bridge_view_ref; - view_ref_pair.view_ref.Clone(&accessibility_bridge_view_ref); + view_ref_pair_.view_ref.Clone(&accessibility_bridge_view_ref); fuchsia::ui::views::ViewRef isolate_view_ref; - view_ref_pair.view_ref.Clone(&isolate_view_ref); + view_ref_pair_.view_ref.Clone(&isolate_view_ref); // Input3 keyboard listener registration requires a ViewRef as an event // filter. So we clone it here, as ViewRefs can not be reused, only cloned. fuchsia::ui::views::ViewRef keyboard_view_ref; - view_ref_pair.view_ref.Clone(&keyboard_view_ref); + view_ref_pair_.view_ref.Clone(&keyboard_view_ref); // Session is terminated on the raster thread, but we must terminate ourselves // on the platform thread. @@ -118,6 +162,8 @@ Engine::Engine(Delegate& delegate, }); }; + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher; + // Set up the session connection and other Scenic helpers on the raster // thread. We also need to wait for the external view embedder to be set up // before creating the shell. @@ -128,20 +174,36 @@ Engine::Engine(Delegate& delegate, [this, &view_embedder_latch, session_inspect_node = std::move(session_inspect_node), session = std::move(session), - session_error_callback = std::move(session_error_callback), - view_token = std::move(view_token), - view_ref_pair = std::move(view_ref_pair), + session_error_callback = std::move(session_error_callback), use_flatland, + view_token = std::move(view_token_), + view_creation_token = std::move(view_creation_token_), + request = parent_viewport_watcher.NewRequest(), + view_ref_pair = std::move(view_ref_pair_), max_frames_in_flight = product_config.get_max_frames_in_flight(), vsync_offset = product_config.get_vsync_offset()]() mutable { - session_connection_ = std::make_shared( - thread_label_, std::move(session_inspect_node), std::move(session), - std::move(session_error_callback), [](auto) {}, - max_frames_in_flight, vsync_offset); - surface_producer_.emplace(session_connection_->get()); - external_view_embedder_ = std::make_shared( - thread_label_, std::move(view_token), std::move(view_ref_pair), - *session_connection_.get(), surface_producer_.value(), - intercept_all_input_); + if (use_flatland) { + flatland_connection_ = std::make_shared( + thread_label_, std::move(session_error_callback), [](auto) {}, + max_frames_in_flight, vsync_offset); + surface_producer_.emplace(/*scenic_session=*/nullptr); + flatland_view_embedder_ = + std::make_shared( + thread_label_, std::move(view_creation_token), + std::move(view_ref_pair), std::move(request), + *flatland_connection_.get(), surface_producer_.value(), + intercept_all_input_); + } else { + session_connection_ = std::make_shared( + thread_label_, std::move(session_inspect_node), + std::move(session), std::move(session_error_callback), + [](auto) {}, max_frames_in_flight, vsync_offset); + surface_producer_.emplace(session_connection_->get()); + external_view_embedder_ = + std::make_shared( + thread_label_, std::move(view_token), + std::move(view_ref_pair), *session_connection_.get(), + surface_producer_.value(), intercept_all_input_); + } view_embedder_latch.Signal(); })); view_embedder_latch.Wait(); @@ -248,11 +310,12 @@ Engine::Engine(Delegate& delegate, // Setup the callback that will instantiate the platform view. flutter::Shell::CreateCallback on_create_platform_view = fml::MakeCopyable( - [this, debug_label = thread_label_, + [this, use_flatland, debug_label = thread_label_, view_ref = std::move(platform_view_ref), runner_services, parent_environment_service_provider = std::move(parent_environment_service_provider), session_listener_request = std::move(session_listener_request), + parent_viewport_watcher = std::move(parent_viewport_watcher), focuser = std::move(focuser), view_ref_focused = std::move(view_ref_focused), on_session_listener_error_callback = @@ -270,12 +333,20 @@ Engine::Engine(Delegate& delegate, external_view_embedder = GetExternalViewEmbedder(), keyboard_listener_request = std::move(keyboard_listener_request), await_vsync_callback = - [this](FireCallbackCallback cb) { - session_connection_->AwaitVsync(cb); + [this, use_flatland](FireCallbackCallback cb) { + if (use_flatland) { + flatland_connection_->AwaitVsync(cb); + } else { + session_connection_->AwaitVsync(cb); + } }, await_vsync_for_secondary_callback_callback = - [this](FireCallbackCallback cb) { - session_connection_->AwaitVsyncForSecondaryCallback(cb); + [this, use_flatland](FireCallbackCallback cb) { + if (use_flatland) { + flatland_connection_->AwaitVsyncForSecondaryCallback(cb); + } else { + session_connection_->AwaitVsyncForSecondaryCallback(cb); + } }, product_config](flutter::Shell& shell) mutable { OnShaderWarmup on_shader_warmup = nullptr; @@ -311,30 +382,62 @@ Engine::Engine(Delegate& delegate, } } - return std::make_unique( - shell, // delegate - debug_label, // debug label - std::move(view_ref), // view ref - shell.GetTaskRunners(), // task runners - std::move(runner_services), - std::move(parent_environment_service_provider), // services - std::move(session_listener_request), // session listener - std::move(view_ref_focused), std::move(focuser), - // Server-side part of the fuchsia.ui.input3.KeyboardListener - // connection. - std::move(keyboard_listener_request), - std::move(on_session_listener_error_callback), - std::move(on_enable_wireframe_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), external_view_embedder, - // Callbacks for VsyncWaiter to call into GfxSessionConnection. - await_vsync_callback, - await_vsync_for_secondary_callback_callback); + std::unique_ptr platform_view; + if (use_flatland) { + platform_view = + std::make_unique( + shell, // delegate + debug_label, // debug label + std::move(view_ref), // view ref + shell.GetTaskRunners(), // task runners + std::move(runner_services), + std::move( + parent_environment_service_provider), // services + std::move(parent_viewport_watcher), + std::move(view_ref_focused), std::move(focuser), + // Server-side part of the + // fuchsia.ui.input3.KeyboardListener connection. + std::move(keyboard_listener_request), + std::move(on_enable_wireframe_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), external_view_embedder, + // Callbacks for VsyncWaiter to call into + // FlatlandConnection. + await_vsync_callback, + await_vsync_for_secondary_callback_callback); + } else { + platform_view = std::make_unique( + shell, // delegate + debug_label, // debug label + std::move(view_ref), // view ref + shell.GetTaskRunners(), // task runners + std::move(runner_services), + std::move(parent_environment_service_provider), // services + std::move(session_listener_request), // session listener + std::move(view_ref_focused), std::move(focuser), + // Server-side part of the fuchsia.ui.input3.KeyboardListener + // connection. + std::move(keyboard_listener_request), + std::move(on_session_listener_error_callback), + std::move(on_enable_wireframe_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), external_view_embedder, + // Callbacks for VsyncWaiter to call into + // GfxSessionConnection. + await_vsync_callback, + await_vsync_for_secondary_callback_callback); + } + return platform_view; }); // Setup the callback that will instantiate the rasterizer. @@ -517,9 +620,12 @@ void Engine::Terminate() { void Engine::DebugWireframeSettingsChanged(bool enabled) { FML_CHECK(shell_); + // TODO(fxbug.dev/64201): Investigate if we can add flatland wireframe code + // for debugging. shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask([this, enabled]() { - FML_CHECK(external_view_embedder_); - external_view_embedder_->EnableWireframe(enabled); + if (external_view_embedder_) { + external_view_embedder_->EnableWireframe(enabled); + } }); } @@ -530,6 +636,8 @@ void Engine::CreateView(int64_t view_id, bool focusable) { FML_CHECK(shell_); + // TODO(fxbug.dev/64201): Add flatland hookup. |view_id| may be interpreted + // based on use_flatland from the initializer. shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask( [this, view_id, hit_testable, focusable, on_view_created = std::move(on_view_created), @@ -548,6 +656,8 @@ void Engine::UpdateView(int64_t view_id, bool focusable) { FML_CHECK(shell_); + // TODO(fxbug.dev/64201): Add flatland hookup. |view_id| may be interpreted + // based on use_flatland from the initializer. shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask( [this, view_id, occlusion_hint, hit_testable, focusable]() { FML_CHECK(external_view_embedder_); @@ -559,6 +669,8 @@ void Engine::UpdateView(int64_t view_id, void Engine::DestroyView(int64_t view_id, ViewIdCallback on_view_unbound) { FML_CHECK(shell_); + // TODO(fxbug.dev/64201): Add flatland hookup. |view_id| may be interpreted + // based on use_flatland from the initializer. shell_->GetTaskRunners().GetRasterTaskRunner()->PostTask( [this, view_id, on_view_unbound = std::move(on_view_unbound)]() { FML_CHECK(external_view_embedder_); @@ -574,9 +686,12 @@ std::unique_ptr Engine::CreateSurface() { std::shared_ptr Engine::GetExternalViewEmbedder() { - FML_CHECK(external_view_embedder_); + FML_CHECK(external_view_embedder_ || flatland_view_embedder_); - return external_view_embedder_; + if (external_view_embedder_) { + return external_view_embedder_; + } + return flatland_view_embedder_; } #if !defined(DART_PRODUCT) diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/engine.h b/engine/src/flutter/shell/platform/fuchsia/flutter/engine.h index 5108b030b9..86fbc1ecf8 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/engine.h +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/engine.h @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -24,6 +25,8 @@ #include "flutter/shell/common/thread_host.h" #include "flutter/shell/platform/fuchsia/flutter/accessibility_bridge.h" +#include "flatland_connection.h" +#include "flatland_external_view_embedder.h" #include "flutter_runner_product_configuration.h" #include "fuchsia_external_view_embedder.h" #include "gfx_session_connection.h" @@ -47,6 +50,7 @@ class Engine final { static flutter::ThreadHost CreateThreadHost(const std::string& name_prefix); + // Gfx connection ctor. Engine(Delegate& delegate, std::string thread_label, std::shared_ptr svc, @@ -57,6 +61,19 @@ class Engine final { UniqueFDIONS fdio_ns, fidl::InterfaceRequest directory_request, FlutterRunnerProductConfiguration product_config); + + // Flatland connection ctor. + Engine(Delegate& delegate, + std::string thread_label, + std::shared_ptr svc, + std::shared_ptr runner_services, + flutter::Settings settings, + fuchsia::ui::views::ViewCreationToken view_creation_token, + scenic::ViewRefPair view_ref_pair, + UniqueFDIONS fdio_ns, + fidl::InterfaceRequest directory_request, + FlutterRunnerProductConfiguration product_config); + ~Engine(); // Returns the Dart return code for the root isolate if one is present. This @@ -73,10 +90,20 @@ class Engine final { const std::string thread_label_; flutter::ThreadHost thread_host_; - std::shared_ptr session_connection_; std::optional surface_producer_; + + // Gfx specific classes. + fuchsia::ui::views::ViewToken view_token_; + std::shared_ptr session_connection_; std::shared_ptr external_view_embedder_; + // Flatland specific classes. + fuchsia::ui::views::ViewCreationToken view_creation_token_; + std::shared_ptr flatland_connection_; + std::shared_ptr flatland_view_embedder_; + + scenic::ViewRefPair view_ref_pair_; + std::unique_ptr isolate_configurator_; std::unique_ptr shell_; std::unique_ptr accessibility_bridge_; @@ -89,6 +116,15 @@ class Engine final { fml::WeakPtrFactory weak_factory_; + void Initialize( + bool use_flatland, + std::shared_ptr svc, + std::shared_ptr runner_services, + flutter::Settings settings, + UniqueFDIONS fdio_ns, + fidl::InterfaceRequest directory_request, + FlutterRunnerProductConfiguration product_config); + static void WarmupSkps( fml::BasicTaskRunner* concurrent_task_runner, fml::BasicTaskRunner* raster_task_runner, diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.cc new file mode 100644 index 0000000000..7c4651df4d --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.cc @@ -0,0 +1,98 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flatland_connection.h" + +#include + +#include "flutter/fml/logging.h" + +namespace flutter_runner { + +FlatlandConnection::FlatlandConnection( + std::string debug_label, + fml::closure error_callback, + on_frame_presented_event on_frame_presented_callback, + uint64_t max_frames_in_flight, + fml::TimeDelta vsync_offset) + : error_callback_(error_callback), + on_frame_presented_callback_(std::move(on_frame_presented_callback)) { + zx_status_t status = + fdio_service_connect("/svc/fuchsia.ui.composition.Flatland", + flatland_.NewRequest().TakeChannel().release()); + FML_DCHECK(status == ZX_OK); + + flatland_->SetDebugName(debug_label); + flatland_.events().OnError = + fit::bind_member(this, &FlatlandConnection::OnError); + flatland_.events().OnFramePresented = + fit::bind_member(this, &FlatlandConnection::OnFramePresented); + flatland_.events().OnNextFrameBegin = + fit::bind_member(this, &FlatlandConnection::OnNextFrameBegin); +} + +FlatlandConnection::~FlatlandConnection() = default; + +void FlatlandConnection::Present() { + // TODO(fxbug.dev/64201): Consider a more complex presentation loop that + // accumulates Present calls until OnNextFrameBegin. + if (present_credits_ == 0) + return; + + --present_credits_; + fuchsia::ui::composition::PresentArgs present_args; + present_args.set_requested_presentation_time(0); + present_args.set_acquire_fences(std::move(acquire_fences_)); + present_args.set_release_fences(std::move(release_fences_)); + present_args.set_unsquashable(false); + flatland_->Present(std::move(present_args)); + + acquire_fences_.clear(); + release_fences_.clear(); +} + +void FlatlandConnection::AwaitVsync(FireCallbackCallback callback) { + if (first_call) { + fml::TimePoint now = fml::TimePoint::Now(); + callback(now, now + fml::TimeDelta::FromMilliseconds(5)); + first_call = false; + return; + } + fire_callback_ = callback; +} + +void FlatlandConnection::AwaitVsyncForSecondaryCallback( + FireCallbackCallback callback) {} + +void FlatlandConnection::OnError( + fuchsia::ui::composition::FlatlandError error) { + FML_LOG(ERROR) << "Flatland error: " << static_cast(error); + error_callback_(); +} + +void FlatlandConnection::OnNextFrameBegin( + fuchsia::ui::composition::OnNextFrameBeginValues values) { + present_credits_ += values.additional_present_credits(); + + if (fire_callback_) { + fml::TimePoint now = fml::TimePoint::Now(); + // TODO(fxbug.dev/64201): Calculate correct frame times. + fire_callback_(now, now + fml::TimeDelta::FromMilliseconds(5)); + } +} + +void FlatlandConnection::OnFramePresented( + fuchsia::scenic::scheduling::FramePresentedInfo info) { + on_frame_presented_callback_(std::move(info)); +} + +void FlatlandConnection::EnqueueAcquireFence(zx::event fence) { + acquire_fences_.push_back(std::move(fence)); +} + +void FlatlandConnection::EnqueueReleaseFence(zx::event fence) { + release_fences_.push_back(std::move(fence)); +} + +} // namespace flutter_runner diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.h b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.h new file mode 100644 index 0000000000..c8f53103d3 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_connection.h @@ -0,0 +1,83 @@ +// 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_DEFAULT_FLATLAND_CONNECTION_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DEFAULT_FLATLAND_CONNECTION_H_ + +#include + +#include "flutter/fml/closure.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/time/time_delta.h" + +#include "vsync_waiter.h" + +#include +#include + +namespace flutter_runner { + +using on_frame_presented_event = + std::function; + +// The component residing on the raster thread that is responsible for +// maintaining the Flatland instance connection and presenting updates. +class FlatlandConnection final { + public: + FlatlandConnection(std::string debug_label, + fml::closure error_callback, + on_frame_presented_event on_frame_presented_callback, + uint64_t max_frames_in_flight, + fml::TimeDelta vsync_offset); + + ~FlatlandConnection(); + + void Present(); + + // Used to implement VsyncWaiter functionality. + void AwaitVsync(FireCallbackCallback callback); + void AwaitVsyncForSecondaryCallback(FireCallbackCallback callback); + + fuchsia::ui::composition::Flatland* flatland() { return flatland_.get(); } + + fuchsia::ui::composition::TransformId NextTransformId() { + return {++next_transform_id_}; + } + + fuchsia::ui::composition::ContentId NextContentId() { + return {++next_content_id_}; + } + + void EnqueueAcquireFence(zx::event fence); + void EnqueueReleaseFence(zx::event fence); + + private: + void OnError(fuchsia::ui::composition::FlatlandError error); + + void OnNextFrameBegin( + fuchsia::ui::composition::OnNextFrameBeginValues values); + void OnFramePresented(fuchsia::scenic::scheduling::FramePresentedInfo info); + + fuchsia::ui::composition::FlatlandPtr flatland_; + + fml::closure error_callback_; + + uint64_t next_transform_id_ = 0; + uint64_t next_content_id_ = 0; + + on_frame_presented_event on_frame_presented_callback_; + uint32_t present_credits_ = 1; + + FireCallbackCallback fire_callback_; + bool first_call = true; + + std::vector acquire_fences_; + std::vector release_fences_; + + FML_DISALLOW_COPY_AND_ASSIGN(FlatlandConnection); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DEFAULT_FLATLAND_CONNECTION_H_ diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_external_view_embedder.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_external_view_embedder.cc new file mode 100644 index 0000000000..e84bdf852c --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_external_view_embedder.cc @@ -0,0 +1,424 @@ +// 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 "flatland_external_view_embedder.h" + +#include "flutter/fml/trace_event.h" +#include "third_party/skia/include/core/SkPicture.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter_runner { + +FlatlandExternalViewEmbedder::FlatlandExternalViewEmbedder( + std::string debug_label, + fuchsia::ui::views::ViewCreationToken view_creation_token, + scenic::ViewRefPair view_ref_pair, + fidl::InterfaceRequest + parent_viewport_watcher_request, + FlatlandConnection& flatland, + VulkanSurfaceProducer& surface_producer, + bool intercept_all_input) + : flatland_(flatland), surface_producer_(surface_producer) { + flatland_.flatland()->CreateView(std::move(view_creation_token), + std::move(parent_viewport_watcher_request)); + + root_transform_id_ = flatland_.NextTransformId(); + flatland_.flatland()->CreateTransform(root_transform_id_); + flatland_.flatland()->SetRootTransform(root_transform_id_); +} + +FlatlandExternalViewEmbedder::~FlatlandExternalViewEmbedder() = default; + +SkCanvas* FlatlandExternalViewEmbedder::GetRootCanvas() { + auto found = frame_layers_.find(kRootLayerId); + if (found == frame_layers_.end()) { + FML_DLOG(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(); +} + +std::vector FlatlandExternalViewEmbedder::GetCurrentCanvases() { + std::vector canvases; + for (const auto& layer : frame_layers_) { + // This method (for legacy reasons) expects non-root current canvases. + if (layer.first.has_value()) { + canvases.push_back(layer.second.canvas_spy->GetSpyingCanvas()); + } + } + return canvases; +} + +void FlatlandExternalViewEmbedder::PrerollCompositeEmbeddedView( + int view_id, + std::unique_ptr params) { + zx_handle_t handle = static_cast(view_id); + FML_CHECK(frame_layers_.count(handle) == 0); + + frame_layers_.emplace(std::make_pair(EmbedderLayerId{handle}, + EmbedderLayer(frame_size_, *params))); + frame_composition_order_.push_back(handle); +} + +SkCanvas* FlatlandExternalViewEmbedder::CompositeEmbeddedView(int view_id) { + zx_handle_t handle = static_cast(view_id); + auto found = frame_layers_.find(handle); + FML_CHECK(found != frame_layers_.end()); + + return found->second.canvas_spy->GetSpyingCanvas(); +} + +flutter::PostPrerollResult FlatlandExternalViewEmbedder::PostPrerollAction( + fml::RefPtr raster_thread_merger) { + return flutter::PostPrerollResult::kSuccess; +} + +void FlatlandExternalViewEmbedder::BeginFrame( + SkISize frame_size, + GrDirectContext* context, + double device_pixel_ratio, + fml::RefPtr raster_thread_merger) { + TRACE_EVENT0("flutter", "FlatlandExternalViewEmbedder::BeginFrame"); + + // Reset for new frame. + Reset(); + frame_size_ = frame_size; + + // TODO(fxbug.dev/64201): Handle device pixel ratio. + + // Create the root layer. + frame_layers_.emplace( + std::make_pair(kRootLayerId, EmbedderLayer(frame_size, std::nullopt))); + frame_composition_order_.push_back(kRootLayerId); +} + +void FlatlandExternalViewEmbedder::EndFrame( + bool should_resubmit_frame, + fml::RefPtr raster_thread_merger) { + TRACE_EVENT0("flutter", "FlatlandExternalViewEmbedder::EndFrame"); +} + +void FlatlandExternalViewEmbedder::SubmitFrame( + GrDirectContext* context, + std::unique_ptr frame, + const std::shared_ptr& gpu_disable_sync_switch) { + TRACE_EVENT0("flutter", "FlatlandExternalViewEmbedder::SubmitFrame"); + std::vector> frame_surfaces; + std::unordered_map 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; + } + + // If we receive an unitialized surface, we need to first create flatland + // resource. + if (surface->GetImageId() == 0) { + auto image_id = flatland_.NextContentId().value; + const auto& size = surface->GetSize(); + fuchsia::ui::composition::ImageProperties image_properties; + image_properties.set_size({static_cast(size.width()), + static_cast(size.height())}); + flatland_.flatland()->CreateImage( + {image_id}, surface->GetBufferCollectionImportToken(), 0, + std::move(image_properties)); + + surface->SetImageId(image_id); + surface->SetReleaseImageCallback([flatland = &flatland_, image_id]() { + flatland->flatland()->ReleaseImage({image_id}); + }); + } + + // Enqueue fences for the next present. + flatland_.EnqueueAcquireFence(surface->GetAcquireFence()); + flatland_.EnqueueReleaseFence(surface->GetReleaseFence()); + + frame_surface_indices.emplace( + std::make_pair(layer.first, frame_surfaces.size())); + frame_surfaces.emplace_back(std::move(surface)); + } + } + + // Submit layers and platform views to Scenic in composition order. + { + TRACE_EVENT0("flutter", "SubmitLayers"); + + size_t flatland_layer_index = 0; + 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 FlatlandView structure corresponding to the platform view. + auto found = flatland_views_.find(layer_id.value()); + FML_CHECK(found != flatland_views_.end()); + auto& viewport = found->second; + + // Compute mutators, and size for the platform view. + const ViewMutators view_mutators = + ParseMutatorStack(view_params.mutatorsStack()); + const SkSize view_size = view_params.sizePoints(); + FML_CHECK(view_mutators.total_transform == + view_params.transformMatrix()); + + // TODO(fxbug.dev/64201): Handle clips. + + // Set transform for the viewport. + // TODO(fxbug.dev/64201): Handle scaling. + if (view_mutators.transform != viewport.mutators.transform) { + flatland_.flatland()->SetTranslation( + viewport.transform_id, + {static_cast(view_mutators.transform.getTranslateX()), + static_cast(view_mutators.transform.getTranslateY())}); + viewport.mutators.transform = view_mutators.transform; + } + + // TODO(fxbug.dev/64201): Set HitTestBehavior. + // TODO(fxbug.dev/64201): Set opacity. + + // Set size + // TODO(): Set occlusion hint, and focusable. + if (view_size != viewport.size) { + fuchsia::ui::composition::ViewportProperties properties; + properties.set_logical_size( + {static_cast(view_size.fWidth), + static_cast(view_size.fHeight)}); + flatland_.flatland()->SetViewportProperties(viewport.viewport_id, + std::move(properties)); + viewport.size = view_size; + } + + // Attach the FlatlandView to the main scene graph. + flatland_.flatland()->AddChild(root_transform_id_, + viewport.transform_id); + } + + // 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(flatland_layer_index <= flatland_layers_.size()); + if (flatland_layer_index == flatland_layers_.size()) { + FlatlandLayer new_layer{ + .transform_id = flatland_.NextTransformId(), + .image_id = {surface_for_layer->GetImageId()}}; + flatland_.flatland()->CreateTransform(new_layer.transform_id); + flatland_.flatland()->SetContent(new_layer.transform_id, + new_layer.image_id); + const auto& size = surface_for_layer->GetSize(); + flatland_.flatland()->SetImageDestinationSize( + new_layer.image_id, {static_cast(size.width()), + static_cast(size.height())}); + flatland_layers_.emplace_back(std::move(new_layer)); + } + + // Attach the FlatlandLayer to the main scene graph. + flatland_.flatland()->AddChild( + root_transform_id_, + flatland_layers_[flatland_layer_index].transform_id); + } + + // Reset for the next pass: + // +The next layer will not be the first layer. + flatland_layer_index++; + } + } + + // Present the session to Scenic, along with surface acquire/release fences. + { + TRACE_EVENT0("flutter", "SessionPresent"); + + flatland_.Present(); + } + + // Render the recorded SkPictures into the surfaces. + { + 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 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()); + sk_sp picture = + layer->second.recorder->finishRecordingAsPicture(); + FML_CHECK(picture != nullptr); + + canvas->setMatrix(SkMatrix::I()); + canvas->clear(SK_ColorTRANSPARENT); + canvas->drawPicture(picture); + canvas->flush(); + } + } + + // Flush deferred Skia work and inform Scenic that render targets are ready. + { + TRACE_EVENT0("flutter", "PresentSurfaces"); + + surface_producer_.OnSurfacesPresented(std::move(frame_surfaces)); + } + + // Submit the underlying render-backend-specific frame for processing. + frame->Submit(); +} + +void FlatlandExternalViewEmbedder::CreateView( + int64_t view_id, + FlatlandViewCallback on_view_created, + FlatlandViewIdCallback on_view_bound) { + FML_CHECK(flatland_views_.find(view_id) == flatland_views_.end()); + + FlatlandView new_view = {.transform_id = flatland_.NextTransformId(), + .viewport_id = flatland_.NextContentId()}; + flatland_.flatland()->CreateTransform(new_view.transform_id); + fuchsia::ui::composition::ViewportProperties properties; + // TODO(fxbug.dev/64201): Add initial viewport size. + flatland_.flatland()->CreateViewport( + new_view.viewport_id, {zx::channel((zx_handle_t)view_id)}, + std::move(properties), new_view.content_link.NewRequest()); + flatland_.flatland()->SetContent(new_view.transform_id, new_view.viewport_id); + + on_view_created(); + on_view_bound(new_view.viewport_id); + flatland_views_.emplace(std::make_pair(view_id, std::move(new_view))); +} + +void FlatlandExternalViewEmbedder::DestroyView( + int64_t view_id, + FlatlandViewIdCallback on_view_unbound) { + auto flatland_view = flatland_views_.find(view_id); + FML_CHECK(flatland_view != flatland_views_.end()); + auto viewport_id = flatland_view->second.viewport_id; + + flatland_views_.erase(flatland_view); + on_view_unbound(viewport_id); +} + +void FlatlandExternalViewEmbedder::SetViewProperties( + int64_t view_id, + const SkRect& occlusion_hint, + bool hit_testable, + bool focusable) { + auto found = flatland_views_.find(view_id); + FML_CHECK(found != flatland_views_.end()); + + // TODO(fxbug.dev/64201): Set occlusion_hint, hit_testable and focusable. +} + +void FlatlandExternalViewEmbedder::Reset() { + frame_layers_.clear(); + frame_composition_order_.clear(); + frame_size_ = SkISize::Make(0, 0); + + // Clear images on all layers so they aren't cached unnecessarily. + for (auto& layer : flatland_layers_) { + flatland_.flatland()->RemoveChild(root_transform_id_, layer.transform_id); + } +} + +FlatlandExternalViewEmbedder::ViewMutators +FlatlandExternalViewEmbedder::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::opacity: { + mutators.opacity *= std::clamp(mutator->GetAlphaFloat(), 0.f, 1.f); + } break; + case flutter::MutatorType::transform: { + total_transform.preConcat(mutator->GetMatrix()); + transform_accumulator.preConcat(mutator->GetMatrix()); + } break; + case flutter::MutatorType::clip_rect: { + mutators.clips.emplace_back(TransformedClip{ + .transform = transform_accumulator, + .rect = mutator->GetRect(), + }); + transform_accumulator = SkMatrix::I(); + } break; + case flutter::MutatorType::clip_rrect: { + mutators.clips.emplace_back(TransformedClip{ + .transform = transform_accumulator, + .rect = mutator->GetRRect().getBounds(), + }); + transform_accumulator = SkMatrix::I(); + } break; + case flutter::MutatorType::clip_path: { + 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; +} + +} // namespace flutter_runner diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_external_view_embedder.h b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_external_view_embedder.h new file mode 100644 index 0000000000..0084efc819 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_external_view_embedder.h @@ -0,0 +1,189 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_EXTERNAL_VIEW_EMBEDDER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_EXTERNAL_VIEW_EMBEDDER_H_ + +#include +#include + +#include // For uint32_t & uint64_t +#include +#include +#include +#include + +#include "flutter/flow/embedded_views.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" +#include "flutter/shell/common/canvas_spy.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 "flutter/flow/embedded_views.h" +#include "flutter/fml/macros.h" + +#include "flatland_connection.h" +#include "vulkan_surface_producer.h" + +namespace flutter_runner { + +using FlatlandViewCallback = std::function; +using FlatlandViewIdCallback = + std::function; + +// This class orchestrates interaction with the Scenic's Flatland compositor on +// Fuchsia. It ensures that flutter content and platform view content are both +// rendered correctly in a unified scene. +class FlatlandExternalViewEmbedder final + : public flutter::ExternalViewEmbedder { + public: + FlatlandExternalViewEmbedder( + std::string debug_label, + fuchsia::ui::views::ViewCreationToken view_creation_token, + scenic::ViewRefPair view_ref_pair, + fidl::InterfaceRequest + parent_viewport_watcher_request, + FlatlandConnection& flatland, + VulkanSurfaceProducer& surface_producer, + bool intercept_all_input = false); + ~FlatlandExternalViewEmbedder(); + + // |ExternalViewEmbedder| + SkCanvas* GetRootCanvas() override; + + // |ExternalViewEmbedder| + std::vector GetCurrentCanvases() override; + + // |ExternalViewEmbedder| + void PrerollCompositeEmbeddedView( + int view_id, + std::unique_ptr params) override; + + // |ExternalViewEmbedder| + SkCanvas* CompositeEmbeddedView(int view_id) override; + + // |ExternalViewEmbedder| + flutter::PostPrerollResult PostPrerollAction( + fml::RefPtr raster_thread_merger) override; + + // |ExternalViewEmbedder| + void BeginFrame( + SkISize frame_size, + GrDirectContext* context, + double device_pixel_ratio, + fml::RefPtr raster_thread_merger) override; + + // |ExternalViewEmbedder| + void EndFrame( + bool should_resubmit_frame, + fml::RefPtr raster_thread_merger) override; + + // |ExternalViewEmbedder| + void SubmitFrame(GrDirectContext* context, + std::unique_ptr frame, + const std::shared_ptr& + gpu_disable_sync_switch) 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 CreateView(int64_t view_id, + FlatlandViewCallback on_view_created, + FlatlandViewIdCallback on_view_bound); + void DestroyView(int64_t view_id, FlatlandViewIdCallback 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. + + // 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 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; + } + }; + + ViewMutators ParseMutatorStack(const flutter::MutatorsStack& mutators_stack); + + struct EmbedderLayer { + EmbedderLayer(const SkISize& frame_size, + std::optional view_params) + : embedded_view_params(std::move(view_params)), + recorder(std::make_unique()), + canvas_spy(std::make_unique( + recorder->beginRecording(frame_size.width(), + frame_size.height()))), + surface_size(frame_size) {} + + std::optional embedded_view_params; + std::unique_ptr recorder; + std::unique_ptr canvas_spy; + SkISize surface_size; + }; + using EmbedderLayerId = std::optional; + constexpr static EmbedderLayerId kRootLayerId = EmbedderLayerId{}; + + struct FlatlandView { + fuchsia::ui::composition::TransformId transform_id; + fuchsia::ui::composition::ContentId viewport_id; + fuchsia::ui::composition::ChildViewWatcherPtr content_link; + ViewMutators mutators; + SkSize size = SkSize::MakeEmpty(); + }; + + struct FlatlandLayer { + fuchsia::ui::composition::TransformId transform_id; + fuchsia::ui::composition::ContentId image_id; + }; + + FlatlandConnection& flatland_; + VulkanSurfaceProducer& surface_producer_; + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher_; + + fuchsia::ui::composition::TransformId root_transform_id_; + + std::unordered_map flatland_views_; + std::vector flatland_layers_; + + std::unordered_map frame_layers_; + std::vector frame_composition_order_; + SkISize frame_size_ = SkISize::Make(0, 0); + + FML_DISALLOW_COPY_AND_ASSIGN(FlatlandExternalViewEmbedder); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_EXTERNAL_VIEW_EMBEDDER_H_ 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 new file mode 100644 index 0000000000..57206e1fd7 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.cc @@ -0,0 +1,98 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flatland_platform_view.h" + +#include "flutter/fml/make_copyable.h" + +namespace flutter_runner { + +FlatlandPlatformView::FlatlandPlatformView( + 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, + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher, + 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(delegate, + std::move(debug_label), + std::move(view_ref), + std::move(task_runners), + std::move(runner_services), + std::move(parent_environment_service_provider), + std::move(vrf), + std::move(focuser), + std::move(keyboard_listener), + 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), + std::move(view_embedder), + std::move(await_vsync_callback), + std::move(await_vsync_for_secondary_callback_callback)), + parent_viewport_watcher_(std::move(parent_viewport_watcher)) { + parent_viewport_watcher_.set_error_handler([](zx_status_t status) { + FML_LOG(ERROR) << "Interface error on: ParentViewportWatcher status: " + << status; + }); + + parent_viewport_watcher_->GetLayout( + fit::bind_member(this, &FlatlandPlatformView::OnGetLayout)); +} + +FlatlandPlatformView::~FlatlandPlatformView() = default; + +void FlatlandPlatformView::OnGetLayout( + fuchsia::ui::composition::LayoutInfo info) { + view_logical_size_ = {static_cast(info.logical_size().width), + static_cast(info.logical_size().height)}; + + // TODO(fxbug.dev/64201): Set device pixel ratio. + + SetViewportMetrics({ + 1, // device_pixel_ratio + view_logical_size_.value()[0], // physical_width + view_logical_size_.value()[1], // 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, + }); + + parent_viewport_watcher_->GetLayout( + fit::bind_member(this, &FlatlandPlatformView::OnGetLayout)); +} + +} // namespace flutter_runner 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 new file mode 100644 index 0000000000..c2607d0d08 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/flatland_platform_view.h @@ -0,0 +1,53 @@ +// 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_FLATLAND_PLATFORM_VIEW_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_PLATFORM_VIEW_H_ + +#include "platform_view.h" + +namespace flutter_runner { + +// The FlatlandPlatformView... +class FlatlandPlatformView final : public flutter_runner::PlatformView { + public: + FlatlandPlatformView( + 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, + fuchsia::ui::composition::ParentViewportWatcherPtr + parent_viewport_watcher, + 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); + ~FlatlandPlatformView(); + + void OnGetLayout(fuchsia::ui::composition::LayoutInfo info); + + private: + fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher_; + + FML_DISALLOW_COPY_AND_ASSIGN(FlatlandPlatformView); +}; + +} // namespace flutter_runner + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLATLAND_PLATFORM_VIEW_H_ 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 new file mode 100644 index 0000000000..e89a06ef46 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.cc @@ -0,0 +1,261 @@ +// 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 { + +GfxPlatformView::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) + : PlatformView(delegate, + std::move(debug_label), + std::move(view_ref), + std::move(task_runners), + std::move(runner_services), + std::move(parent_environment_service_provider), + std::move(vrf), + std::move(focuser), + std::move(keyboard_listener), + 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), + std::move(view_embedder), + std::move(await_vsync_callback), + std::move(await_vsync_for_secondary_callback_callback)), + session_listener_binding_(this, std::move(session_listener_request)), + session_listener_error_callback_( + std::move(on_session_listener_error_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 events) { + TRACE_EVENT0("flutter", "PlatformView::OnScenicEvent"); + + std::vector 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_DLOG(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) { + FML_DLOG(ERROR) + << "Got an identical pixel ratio from Scenic; ignoring: " + << 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 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_DLOG(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) { + FML_DLOG(ERROR) + << "Got an identical view size from Scenic; ignoring: " + << new_view_size[0] << " " << new_view_size[1]; + 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; + case fuchsia::ui::scenic::Event::Tag::kInput: + switch (event.input().Which()) { + case fuchsia::ui::input::InputEvent::Tag::kFocus: + break; + case fuchsia::ui::input::InputEvent::Tag::kPointer: { + OnHandlePointerEvent(event.input().pointer()); + break; + } + case fuchsia::ui::input::InputEvent::Tag::kKeyboard: { + // All devices should receive key events via input3.KeyboardListener + // instead. + FML_LOG(WARNING) << "Keyboard event from Scenic: ignored"; + break; + } + case fuchsia::ui::input::InputEvent::Tag::Invalid: { + FML_DCHECK(false) + << "Flutter PlatformView::OnScenicEvent: Got an invalid INPUT " + "event."; + } + } + 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 logical_size = *view_logical_size_; + SetViewportMetrics({ + pixel_ratio, // device_pixel_ratio + logical_size[0] * pixel_ratio, // physical_width + 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, + }); + } +} + +} // namespace flutter_runner 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 new file mode 100644 index 0000000000..d1b6601344 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/gfx_platform_view.h @@ -0,0 +1,64 @@ +// 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 "platform_view.h" + +#include + +namespace flutter_runner { + +// The GfxPlatformView implements SessionListener and gets Session events but it +// does *not* actually own the Session itself; that is owned by the +// FuchsiaExternalViewEmbedder on the raster thread. +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(); + + private: + // |fuchsia::ui::scenic::SessionListener| + void OnScenicError(std::string error) override; + void OnScenicEvent(std::vector events) override; + + fidl::Binding session_listener_binding_; + fit::closure session_listener_error_callback_; + + fml::WeakPtrFactory + 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/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_product_runner.cmx b/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_product_runner.cmx index 788c3c4c41..b88409bbd9 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_product_runner.cmx +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_product_runner.cmx @@ -24,7 +24,9 @@ "fuchsia.sysmem.Allocator", "fuchsia.timezone.Timezone", "fuchsia.tracing.provider.Registry", + "fuchsia.ui.composition.Allocator", + "fuchsia.ui.composition.Flatland", "fuchsia.vulkan.loader.Loader" ] } -} +} \ No newline at end of file diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_runner.cmx b/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_runner.cmx index 788c3c4c41..b88409bbd9 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_runner.cmx +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_aot_runner.cmx @@ -24,7 +24,9 @@ "fuchsia.sysmem.Allocator", "fuchsia.timezone.Timezone", "fuchsia.tracing.provider.Registry", + "fuchsia.ui.composition.Allocator", + "fuchsia.ui.composition.Flatland", "fuchsia.vulkan.loader.Loader" ] } -} +} \ No newline at end of file diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_product_runner.cmx b/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_product_runner.cmx index d2976d2855..5b25def2fb 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_product_runner.cmx +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_product_runner.cmx @@ -25,7 +25,9 @@ "fuchsia.sysmem.Allocator", "fuchsia.timezone.Timezone", "fuchsia.tracing.provider.Registry", + "fuchsia.ui.composition.Allocator", + "fuchsia.ui.composition.Flatland", "fuchsia.vulkan.loader.Loader" ] } -} +} \ No newline at end of file diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_runner.cmx b/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_runner.cmx index d2976d2855..5b25def2fb 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_runner.cmx +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/meta/flutter_jit_runner.cmx @@ -25,7 +25,9 @@ "fuchsia.sysmem.Allocator", "fuchsia.timezone.Timezone", "fuchsia.tracing.provider.Registry", + "fuchsia.ui.composition.Allocator", + "fuchsia.ui.composition.Flatland", "fuchsia.vulkan.loader.Loader" ] } -} +} \ No newline at end of file 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 8827f05045..018c1b9482 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.cc @@ -7,8 +7,6 @@ #include "platform_view.h" -#include - #include #include #include @@ -60,13 +58,10 @@ PlatformView::PlatformView( std::shared_ptr runner_services, fidl::InterfaceHandle parent_environment_service_provider_handle, - fidl::InterfaceRequest - session_listener_request, fidl::InterfaceHandle vrf, fidl::InterfaceHandle focuser, fidl::InterfaceRequest keyboard_listener_request, - fit::closure session_listener_error_callback, OnEnableWireframe wireframe_enabled_callback, OnCreateView on_create_view_callback, OnUpdateView on_update_view_callback, @@ -84,9 +79,6 @@ PlatformView::PlatformView( view_ref_(std::move(view_ref)), focus_delegate_( std::make_shared(std::move(vrf), std::move(focuser))), - session_listener_binding_(this, std::move(session_listener_request)), - session_listener_error_callback_( - std::move(session_listener_error_callback)), 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)), @@ -104,7 +96,6 @@ PlatformView::PlatformView( await_vsync_for_secondary_callback_callback), weak_factory_(this) { // Register all error handlers. - SetInterfaceErrorHandler(session_listener_binding_, "SessionListener"); SetInterfaceErrorHandler(ime_, "Input Method Editor"); SetInterfaceErrorHandler(text_sync_service_, "Text Sync Service"); SetInterfaceErrorHandler(parent_environment_service_provider_, @@ -231,198 +222,6 @@ void PlatformView::OnAction(fuchsia::ui::input::InputMethodAction action) { ); } -void PlatformView::OnScenicError(std::string error) { - FML_LOG(ERROR) << "Session error: " << error; - session_listener_error_callback_(); -} - -void PlatformView::OnScenicEvent( - std::vector events) { - TRACE_EVENT0("flutter", "PlatformView::OnScenicEvent"); - - std::vector 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_DLOG(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) { - FML_DLOG(ERROR) - << "Got an identical pixel ratio from Scenic; ignoring: " - << 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 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_DLOG(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) { - FML_DLOG(ERROR) - << "Got an identical view size from Scenic; ignoring: " - << new_view_size[0] << " " << new_view_size[1]; - 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; - case fuchsia::ui::scenic::Event::Tag::kInput: - switch (event.input().Which()) { - case fuchsia::ui::input::InputEvent::Tag::kFocus: - break; - case fuchsia::ui::input::InputEvent::Tag::kPointer: { - OnHandlePointerEvent(event.input().pointer()); - break; - } - case fuchsia::ui::input::InputEvent::Tag::kKeyboard: { - // All devices should receive key events via input3.KeyboardListener - // instead. - FML_LOG(WARNING) << "Keyboard event from Scenic: ignored"; - break; - } - case fuchsia::ui::input::InputEvent::Tag::Invalid: { - FML_DCHECK(false) - << "Flutter PlatformView::OnScenicEvent: Got an invalid INPUT " - "event."; - } - } - 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 logical_size = *view_logical_size_; - SetViewportMetrics({ - pixel_ratio, // device_pixel_ratio - logical_size[0] * pixel_ratio, // physical_width - 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, - }); - } -} - bool PlatformView::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()) { 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 75d1f3ae1d..34aaf8c83d 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.h +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/platform_view.h @@ -56,14 +56,9 @@ using OnShaderWarmup = std::function&, // in HandlePlatformMessage. This communication is bidirectional. Platform // messages are notably responsible for communication related to input and // external views / windowing. -// -// The PlatformView implements SessionListener and gets Session events but it -// does *not* actually own the Session itself; that is owned by the -// FuchsiaExternalViewEmbedder on the raster thread. -class PlatformView final : public flutter::PlatformView, - private fuchsia::ui::scenic::SessionListener, - private fuchsia::ui::input3::KeyboardListener, - private fuchsia::ui::input::InputMethodEditorClient { +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, @@ -72,13 +67,10 @@ class PlatformView final : public flutter::PlatformView, 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, @@ -92,7 +84,7 @@ class PlatformView final : public flutter::PlatformView, AwaitVsyncForSecondaryCallbackCallback await_vsync_for_secondary_callback_callback); - ~PlatformView(); + virtual ~PlatformView(); // |flutter::PlatformView| void SetSemanticsEnabled(bool enabled) override; @@ -101,7 +93,7 @@ class PlatformView final : public flutter::PlatformView, std::shared_ptr CreateExternalViewEmbedder() override; - private: + protected: void RegisterPlatformMessageHandlers(); // |fuchsia.ui.input3.KeyboardListener| @@ -118,10 +110,6 @@ class PlatformView final : public flutter::PlatformView, // |fuchsia::ui::input::InputMethodEditorClient| void OnAction(fuchsia::ui::input::InputMethodAction action) override; - // |fuchsia::ui::scenic::SessionListener| - void OnScenicError(std::string error) override; - void OnScenicEvent(std::vector 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. @@ -202,8 +190,6 @@ class PlatformView final : public flutter::PlatformView, std::optional> view_logical_origin_; std::optional view_pixel_ratio_; - fidl::Binding session_listener_binding_; - fit::closure session_listener_error_callback_; OnEnableWireframe wireframe_enabled_callback_; OnCreateView on_create_view_callback_; OnUpdateView on_update_view_callback_; 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 e6a7192616..28501ad4e5 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 @@ -22,7 +22,7 @@ #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/platform_view.h" +#include "flutter/shell/platform/fuchsia/flutter/gfx_platform_view.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "surface.h" @@ -258,10 +258,10 @@ class PlatformViewBuilder { } // Once Build is called, the instance is no longer usable. - PlatformView Build() { + GfxPlatformView Build() { EXPECT_FALSE(std::exchange(built_, true)) << "Build() was already called, this buider is good for one use only."; - return PlatformView( + return GfxPlatformView( 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_), @@ -376,7 +376,7 @@ TEST_F(PlatformViewTests, InvalidPlatformMessageRequest) { fidl::BindingSet vrf_bindings; auto vrf_handle = vrf_bindings.AddBinding(&vrf); - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetViewRefFocused(std::move(vrf_handle)) @@ -455,7 +455,7 @@ TEST_F(PlatformViewTests, CreateSurfaceTest) { "PlatformViewTest", view_embedder, gr_context.get()); }; - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetCreateSurfaceCallback(CreateSurfaceCallback) @@ -487,7 +487,7 @@ TEST_F(PlatformViewTests, SetViewportMetrics) { sys::testing::ServiceDirectoryProvider services_provider(dispatcher()); flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr, nullptr); - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetSessionListenerRequest(session_listener.NewRequest()) @@ -606,7 +606,7 @@ TEST_F(PlatformViewTests, ChangesAccessibilitySettings) { EXPECT_FALSE(delegate.semantics_enabled()); EXPECT_EQ(delegate.semantics_features(), 0); - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder( delegate, // delegate std::move(task_runners), // task_runners @@ -645,7 +645,7 @@ TEST_F(PlatformViewTests, EnableWireframeTest) { wireframe_enabled = should_enable; }; - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetEnableWireframeCallback(EnableWireframeCallback) @@ -704,7 +704,7 @@ TEST_F(PlatformViewTests, CreateViewTest) { on_view_bound(0); }; - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetCreateViewCallback(CreateViewCallback) @@ -757,7 +757,7 @@ TEST_F(PlatformViewTests, UpdateViewTest) { focusable_for_test = focusable; }; - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetUpdateViewCallback(UpdateViewCallback) @@ -880,7 +880,7 @@ TEST_F(PlatformViewTests, DestroyViewTest) { on_view_unbound(0); }; - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetDestroyViewCallback(DestroyViewCallback) @@ -942,7 +942,7 @@ TEST_F(PlatformViewTests, ViewEventsTest) { on_view_bound(kViewHolderId); }; - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetSessionListenerRequest(session_listener.NewRequest()) @@ -1062,7 +1062,7 @@ TEST_F(PlatformViewTests, GetFocusStatesTest) { fidl::BindingSet vrf_bindings; auto vrf_handle = vrf_bindings.AddBinding(&vrf); - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetViewRefFocused(std::move(vrf_handle)) @@ -1124,7 +1124,7 @@ TEST_F(PlatformViewTests, RequestFocusTest) { fidl::BindingSet focuser_bindings; auto focuser_handle = focuser_bindings.AddBinding(&focuser); - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetFocuser(std::move(focuser_handle)) @@ -1170,7 +1170,7 @@ TEST_F(PlatformViewTests, RequestFocusFailTest) { fidl::BindingSet focuser_bindings; auto focuser_handle = focuser_bindings.AddBinding(&focuser); - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetFocuser(std::move(focuser_handle)) @@ -1223,7 +1223,7 @@ TEST_F(PlatformViewTests, OnKeyEvent) { fidl::InterfacePtr keyboard_listener; - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetKeyboardListener(keyboard_listener.NewRequest(dispatcher())) @@ -1317,7 +1317,7 @@ TEST_F(PlatformViewTests, OnShaderWarmup) { completion_callback(shaders_in.size()); }; - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetShaderWarmupCallback(on_shader_warmup) @@ -1394,7 +1394,7 @@ TEST_F(PlatformViewTests, DownPointerNumericNudge) { MockPlatformViewDelegate delegate; flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr, nullptr); - flutter_runner::PlatformView platform_view = + flutter_runner::GfxPlatformView platform_view = PlatformViewBuilder(delegate, std::move(task_runners), services_provider.service_directory()) .SetSessionListenerRequest(session_listener.NewRequest()) diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.cc index 3a4cbc0b93..38f9898a64 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.cc @@ -103,16 +103,17 @@ bool VulkanSurface::CreateVulkanImage(vulkan::VulkanProvider& vulkan_provider, VulkanSurface::VulkanSurface( vulkan::VulkanProvider& vulkan_provider, fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, sk_sp context, scenic::Session* session, const SkISize& size, uint32_t buffer_id) : vulkan_provider_(vulkan_provider), session_(session), wait_(this) { - FML_CHECK(session_ != nullptr); + FML_CHECK(session_ || flatland_allocator.is_bound()); FML_CHECK(context != nullptr); - if (!AllocateDeviceMemory(sysmem_allocator, std::move(context), size, - buffer_id)) { + if (!AllocateDeviceMemory(sysmem_allocator, flatland_allocator, + std::move(context), size, buffer_id)) { FML_LOG(ERROR) << "VulkanSurface: Could not allocate device memory."; return; } @@ -134,11 +135,15 @@ VulkanSurface::VulkanSurface( } VulkanSurface::~VulkanSurface() { - if (image_id_) { - session_->Enqueue(scenic::NewReleaseResourceCmd(image_id_)); - } - if (buffer_id_) { - session_->DeregisterBufferCollection(buffer_id_); + if (session_) { + if (image_id_) { + session_->Enqueue(scenic::NewReleaseResourceCmd(image_id_)); + } + if (buffer_id_) { + session_->DeregisterBufferCollection(buffer_id_); + } + } else { + release_image_callback_(); } wait_.Cancel(); wait_.set_object(ZX_HANDLE_INVALID); @@ -227,6 +232,7 @@ bool VulkanSurface::CreateFences() { bool VulkanSurface::AllocateDeviceMemory( fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, sk_sp context, const SkISize& size, uint32_t buffer_id) { @@ -250,8 +256,29 @@ bool VulkanSurface::AllocateDeviceMemory( LOG_AND_RETURN(status != ZX_OK, "VulkanSurface: Failed to sync collection token"); - session_->RegisterBufferCollection(buffer_id, std::move(scenic_token)); - buffer_id_ = buffer_id; + if (session_) { + session_->RegisterBufferCollection(buffer_id, std::move(scenic_token)); + buffer_id_ = buffer_id; + } else { + fuchsia::ui::composition::BufferCollectionExportToken export_token; + status = + zx::eventpair::create(0, &export_token.value, &import_token_.value); + + fuchsia::ui::composition::RegisterBufferCollectionArgs args; + args.set_export_token(std::move(export_token)); + args.set_buffer_collection_token(std::move(scenic_token)); + args.set_usage( + fuchsia::ui::composition::RegisterBufferCollectionUsage::DEFAULT); + flatland_allocator->RegisterBufferCollection( + std::move(args), + [](fuchsia::ui::composition::Allocator_RegisterBufferCollection_Result + result) { + if (result.is_err()) { + FML_LOG(ERROR) + << "RegisterBufferCollection call to Scenic Allocator failed"; + } + }); + } VkBufferCollectionCreateInfoFUCHSIA import_info; import_info.collectionToken = vulkan_token.Unbind().TakeChannel().release(); @@ -379,10 +406,18 @@ bool VulkanSurface::SetupSkiaSurface(sk_sp context, } void VulkanSurface::PushSessionImageSetupOps(scenic::Session* session) { - if (image_id_ == 0) - image_id_ = session->AllocResourceId(); - session->Enqueue(scenic::NewCreateImage2Cmd( - image_id_, sk_surface_->width(), sk_surface_->height(), buffer_id_, 0)); + if (session) { + if (image_id_ == 0) + image_id_ = session->AllocResourceId(); + session->Enqueue(scenic::NewCreateImage2Cmd( + image_id_, sk_surface_->width(), sk_surface_->height(), buffer_id_, 0)); + } +} + +void VulkanSurface::SetImageId(uint32_t image_id) { + FML_CHECK(image_id_ == 0); + FML_CHECK(!session_); + image_id_ = image_id; } uint32_t VulkanSurface::GetImageId() { @@ -393,6 +428,33 @@ sk_sp VulkanSurface::GetSkiaSurface() const { return valid_ ? sk_surface_ : nullptr; } +fuchsia::ui::composition::BufferCollectionImportToken +VulkanSurface::GetBufferCollectionImportToken() { + FML_CHECK(!session_); + fuchsia::ui::composition::BufferCollectionImportToken import_dup; + import_token_.value.duplicate(ZX_RIGHT_SAME_RIGHTS, &import_dup.value); + return import_dup; +} + +zx::event VulkanSurface::GetAcquireFence() { + FML_CHECK(!session_); + zx::event fence; + acquire_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); + return fence; +} + +zx::event VulkanSurface::GetReleaseFence() { + FML_CHECK(!session_); + zx::event fence; + release_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence); + return fence; +} +void VulkanSurface::SetReleaseImageCallback( + ReleaseImageCallback release_image_callback) { + FML_CHECK(!session_); + release_image_callback_ = release_image_callback; +} + size_t VulkanSurface::AdvanceAndGetAge() { size_history_[size_history_index_] = GetSize(); size_history_index_ = (size_history_index_ + 1) % kSizeHistorySize; @@ -401,15 +463,16 @@ size_t VulkanSurface::AdvanceAndGetAge() { } bool VulkanSurface::FlushSessionAcquireAndReleaseEvents() { - zx::event acquire, release; - - if (acquire_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &acquire) != ZX_OK || - release_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &release) != ZX_OK) { - return false; + if (session_) { + zx::event acquire, release; + if (acquire_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &acquire) != ZX_OK || + release_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &release) != ZX_OK) { + return false; + } + session_->EnqueueAcquireFence(std::move(acquire)); + session_->EnqueueReleaseFence(std::move(release)); } - session_->EnqueueAcquireFence(std::move(acquire)); - session_->EnqueueReleaseFence(std::move(release)); age_ = 0; return true; } diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.h b/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.h index 7e54bd2368..fcaed40d4b 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.h +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface.h @@ -10,6 +10,7 @@ #include #include +#include #include #include "flutter/flow/raster_cache_key.h" @@ -22,6 +23,8 @@ namespace flutter_runner { +using ReleaseImageCallback = std::function; + class SurfaceProducerSurface { public: virtual ~SurfaceProducerSurface() = default; @@ -37,9 +40,21 @@ class SurfaceProducerSurface { virtual void SignalWritesFinished( const std::function& on_writes_committed) = 0; + virtual void SetImageId(uint32_t image_id) = 0; + virtual uint32_t GetImageId() = 0; virtual sk_sp GetSkiaSurface() const = 0; + + virtual fuchsia::ui::composition::BufferCollectionImportToken + GetBufferCollectionImportToken() = 0; + + virtual zx::event GetAcquireFence() = 0; + + virtual zx::event GetReleaseFence() = 0; + + virtual void SetReleaseImageCallback( + ReleaseImageCallback release_image_callback) = 0; }; class SurfaceProducer { @@ -71,6 +86,7 @@ class VulkanSurface final : public SurfaceProducerSurface { public: VulkanSurface(vulkan::VulkanProvider& vulkan_provider, fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, sk_sp context, scenic::Session* session, const SkISize& size, @@ -95,12 +111,29 @@ class VulkanSurface final : public SurfaceProducerSurface { void SignalWritesFinished( const std::function& on_writes_committed) override; + // |SurfaceProducerSurface| + void SetImageId(uint32_t image_id) override; + // |SurfaceProducerSurface| uint32_t GetImageId() override; // |SurfaceProducerSurface| sk_sp GetSkiaSurface() const override; + // |SurfaceProducerSurface| + fuchsia::ui::composition::BufferCollectionImportToken + GetBufferCollectionImportToken() override; + + // |SurfaceProducerSurface| + zx::event GetAcquireFence() override; + + // |SurfaceProducerSurface| + zx::event GetReleaseFence() override; + + // |SurfaceProducerSurface| + void SetReleaseImageCallback( + ReleaseImageCallback release_image_callback) override; + const vulkan::VulkanHandle& GetVkImage() { return vulkan_image_.vk_image; } @@ -144,10 +177,12 @@ class VulkanSurface final : public SurfaceProducerSurface { zx_status_t status, const zx_packet_signal_t* signal); - bool AllocateDeviceMemory(fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator, - sk_sp context, - const SkISize& size, - uint32_t buffer_id); + bool AllocateDeviceMemory( + fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator, + fuchsia::ui::composition::AllocatorPtr& flatland_allocator, + sk_sp context, + const SkISize& size, + uint32_t buffer_id); bool CreateVulkanImage(vulkan::VulkanProvider& vulkan_provider, const SkISize& size, @@ -176,6 +211,7 @@ class VulkanSurface final : public SurfaceProducerSurface { vulkan::VulkanHandle command_buffer_fence_; sk_sp sk_surface_; uint32_t buffer_id_ = 0; + fuchsia::ui::composition::BufferCollectionImportToken import_token_; uint32_t image_id_ = 0; vulkan::VulkanHandle collection_; zx::event acquire_event_; @@ -188,6 +224,7 @@ class VulkanSurface final : public SurfaceProducerSurface { int size_history_index_ = 0; size_t age_ = 0; bool valid_ = false; + ReleaseImageCallback release_image_callback_; FML_DISALLOW_COPY_AND_ASSIGN(VulkanSurface); }; diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.cc b/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.cc index a0a7f32d28..ae83ff974a 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.cc +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.cc @@ -43,6 +43,13 @@ VulkanSurfacePool::VulkanSurfacePool(vulkan::VulkanProvider& vulkan_provider, sysmem_allocator_->SetDebugClientInfo(GetCurrentProcessName(), GetCurrentProcessId()); FML_DCHECK(status != ZX_OK); + + if (!scenic_session_) { + status = fdio_service_connect( + "/svc/fuchsia.ui.composition.Allocator", + flatland_allocator_.NewRequest().TakeChannel().release()); + FML_DCHECK(status != ZX_OK); + } } VulkanSurfacePool::~VulkanSurfacePool() {} @@ -117,8 +124,8 @@ std::unique_ptr VulkanSurfacePool::CreateSurface( TRACE_EVENT2("flutter", "VulkanSurfacePool::CreateSurface", "width", size.width(), "height", size.height()); auto surface = std::make_unique( - vulkan_provider_, sysmem_allocator_, context_, scenic_session_, size, - buffer_id_++); + vulkan_provider_, sysmem_allocator_, flatland_allocator_, context_, + scenic_session_, size, buffer_id_++); if (!surface->IsValid()) { FML_LOG(ERROR) << "VulkanSurfaceProducer: Created surface is invalid"; return nullptr; diff --git a/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.h b/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.h index 00686f5418..694b8396c6 100644 --- a/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.h +++ b/engine/src/flutter/shell/platform/fuchsia/flutter/vulkan_surface_pool.h @@ -4,6 +4,8 @@ #pragma once +#include + #include #include @@ -42,6 +44,7 @@ class VulkanSurfacePool final { sk_sp context_; scenic::Session* scenic_session_; fuchsia::sysmem::AllocatorSyncPtr sysmem_allocator_; + fuchsia::ui::composition::AllocatorPtr flatland_allocator_; std::vector> available_surfaces_; std::unordered_map> pending_surfaces_;