diff --git a/flutter/engine/src/flutter/shell/common/BUILD.gn b/flutter/engine/src/flutter/shell/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c3ffd57d5c4c29aaa5c70c3579f94a4c68a7f494 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/BUILD.gn @@ -0,0 +1,369 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/common/config.gni") +import("//flutter/impeller/tools/impeller.gni") +import("//flutter/shell/gpu/gpu.gni") +import("//flutter/testing/testing.gni") + +if (is_fuchsia) { + import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +} + +# Template to generate a dart embedder resource.cc file. +# Required invoker inputs: +# String output (name of output file) +# List inputs (list of input files to be included) +# String table_name (name of symbol for resource table) +# String root_prefix (base directory of resources) +# Optional invoker inputs: +# String input_directory (directory of resources that are recursively added) +# List deps +# List datadeps +template("dart_embedder_resources") { + action(target_name) { + script = "$dart_src/runtime/tools/create_resources.py" + deps = [] + if (defined(invoker.deps)) { + deps += invoker.deps + } + datadeps = [] + if (defined(invoker.datadeps)) { + datadeps = invoker.datadeps + } + + output = invoker.output + outputs = [ output ] + + inputs = [ script ] + invoker.inputs + + root_prefix = rebase_path(invoker.root_prefix) + + args = [ + "--output", + rebase_path(output), + "--outer_namespace", + "flutter", + "--inner_namespace", + "runtime", + "--table_name", + invoker.table_name, + "--root_prefix", + root_prefix, + ] + if (defined(invoker.input_directory)) { + args += [ + "--client_root", + rebase_path(invoker.input_directory), + ] + } + args += rebase_path(invoker.inputs) + } +} + +source_set("platform_message_handler") { + sources = [ "platform_message_handler.h" ] + public_configs = [ "//flutter:config" ] + deps = [ "//flutter/fml:fml" ] +} + +source_set("display") { + sources = [ + "display.cc", + "display.h", + "variable_refresh_rate_display.cc", + "variable_refresh_rate_display.h", + "variable_refresh_rate_reporter.h", + ] + public_configs = [ "//flutter:config" ] + deps = [ "//flutter/fml:fml" ] +} + +source_set("common") { + sources = [ + "animator.cc", + "animator.h", + "context_options.cc", + "context_options.h", + "display_manager.cc", + "display_manager.h", + "dl_op_spy.cc", + "dl_op_spy.h", + "engine.cc", + "engine.h", + "pipeline.cc", + "pipeline.h", + "platform_view.cc", + "platform_view.h", + "pointer_data_dispatcher.cc", + "pointer_data_dispatcher.h", + "rasterizer.cc", + "rasterizer.h", + "resource_cache_limit_calculator.cc", + "resource_cache_limit_calculator.h", + "run_configuration.cc", + "run_configuration.h", + "serialization_callbacks.cc", + "serialization_callbacks.h", + "shell.cc", + "shell.h", + "shell_io_manager.cc", + "shell_io_manager.h", + "skia_event_tracer_impl.cc", + "skia_event_tracer_impl.h", + "snapshot_controller.cc", + "snapshot_controller.h", + "snapshot_controller_skia.cc", + "snapshot_controller_skia.h", + "snapshot_surface_producer.h", + "switches.cc", + "switches.h", + "thread_host.cc", + "thread_host.h", + "vsync_waiter.cc", + "vsync_waiter.h", + "vsync_waiter_fallback.cc", + "vsync_waiter_fallback.h", + ] + + public_configs = [ "//flutter:config" ] + + public_deps = [ + ":display", + ":platform_message_handler", + "//flutter/shell/version", + "//flutter/third_party/rapidjson", + "//flutter/third_party/tonic", + "//flutter/txt", + ] + + deps = [ + "$dart_src/runtime:dart_api", + "//flutter/assets", + "//flutter/common", + "//flutter/common/graphics", + "//flutter/flow", + "//flutter/fml", + "//flutter/lib/ui", + "//flutter/runtime", + "//flutter/shell/common:base64", + "//flutter/shell/profiling", + "//flutter/skia", + ] + + if (impeller_supports_rendering) { + sources += [ + "snapshot_controller_impeller.cc", + "snapshot_controller_impeller.h", + ] + + deps += [ "//flutter/impeller" ] + } +} + +# These are in their own source_set to avoid a dependency cycle with //common/graphics +source_set("base64") { + sources = [ + "base64.cc", + "base64.h", + ] + deps = [ "//flutter/fml" ] +} + +template("shell_host_executable") { + executable(target_name) { + testonly = true + + deps = [] + + ldflags = [] + + forward_variables_from(invoker, "*") + + deps += [ + ":common", + "//flutter/lib/snapshot", + "//flutter/runtime:libdart", + ] + + public_configs = [ "//flutter:export_dynamic_symbols" ] + } +} + +if (enable_unittests) { + shell_gpu_configuration("shell_unittests_gpu_configuration") { + enable_software = test_enable_software + enable_vulkan = test_enable_vulkan + enable_gl = test_enable_gl + enable_metal = test_enable_metal + } + + test_fixtures("shell_unittests_fixtures") { + dart_main = "fixtures/shell_test.dart" + + fixtures = [ + "fixtures/shelltest_screenshot.png", + "fixtures/hello_loop_2.gif", + "//flutter/txt/third_party/fonts/Roboto-Regular.ttf", + ] + } + + shell_host_executable("shell_benchmarks") { + sources = [ + "dart_native_benchmarks.cc", + "shell_benchmarks.cc", + ] + + deps = [ + ":shell_unittests_fixtures", + "//flutter/benchmarking", + "//flutter/flow", + "//flutter/testing:dart", + "//flutter/testing:fixture_test", + "//flutter/testing:testing_lib", + ] + } + + config("shell_test_fixture_sources_config") { + defines = [ + # Required for MSVC STL + "_ENABLE_ATOMIC_ALIGNMENT_FIX", + ] + } + + source_set("shell_test_fixture_sources") { + testonly = true + + sources = [ + "shell_test.cc", + "shell_test.h", + "shell_test_external_view_embedder.cc", + "shell_test_external_view_embedder.h", + "shell_test_platform_view.cc", + "shell_test_platform_view.h", + "vsync_waiters_test.cc", + "vsync_waiters_test.h", + ] + + public_deps = [ + "//flutter/common/graphics", + "//flutter/flow", + "//flutter/runtime", + "//flutter/shell/common", + "//flutter/testing", + ] + + deps = [ + ":shell_unittests_gpu_configuration", + "//flutter/assets", + "//flutter/common", + "//flutter/lib/ui", + "//flutter/skia", + "//flutter/testing:dart", + "//flutter/testing:fixture_test", + "//flutter/third_party/rapidjson", + ] + + if (impeller_supports_rendering) { + deps += [ "//flutter/impeller" ] + } + + public_configs = [ + ":shell_test_fixture_sources_config", + ":shell_unittests_gpu_configuration_config", + ] + + if (test_enable_gl) { + sources += [ + "shell_test_platform_view_gl.cc", + "shell_test_platform_view_gl.h", + ] + + public_deps += [ "//flutter/testing:opengl" ] + } + + if (test_enable_vulkan) { + sources += [ + "shell_test_platform_view_vulkan.cc", + "shell_test_platform_view_vulkan.h", + ] + + public_deps += [ + "//flutter/flutter_vma:flutter_skia_vma", + "//flutter/vulkan", + ] + } + + if (test_enable_metal) { + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + + sources += [ + "shell_test_platform_view_metal.h", + "shell_test_platform_view_metal.mm", + ] + + public_deps += [ "//flutter/shell/platform/darwin/graphics" ] + } + } + + shell_host_executable("shell_unittests") { + testonly = true + + sources = [ + "animator_unittests.cc", + "base64_unittests.cc", + "context_options_unittests.cc", + "dl_op_spy_unittests.cc", + "engine_animator_unittests.cc", + "engine_unittests.cc", + "input_events_unittests.cc", + "persistent_cache_unittests.cc", + "pipeline_unittests.cc", + "rasterizer_unittests.cc", + "resource_cache_limit_calculator_unittests.cc", + "shell_unittests.cc", + "switches_unittests.cc", + "variable_refresh_rate_display_unittests.cc", + "vsync_waiter_unittests.cc", + ] + + deps = [ + ":shell_test_fixture_sources", + ":shell_unittests_fixtures", + "//flutter/assets", + "//flutter/common/graphics", + "//flutter/display_list/testing:display_list_testing", + "//flutter/shell/common:base64", + "//flutter/shell/profiling:profiling_unittests", + "//flutter/shell/version", + "//flutter/testing:fixture_test", + "//flutter/third_party/googletest:gmock", + ] + + if (is_fuchsia) { + sources += [ "shell_fuchsia_unittests.cc" ] + + deps += [ + "${fuchsia_sdk}/fidl/fuchsia.intl", + "${fuchsia_sdk}/fidl/fuchsia.settings", + "${fuchsia_sdk}/pkg/fidl_cpp", + "${fuchsia_sdk}/pkg/sys_cpp", + ] + } else if (shell_enable_gl) { + # TODO(63837): This test is hard-coded to use a TestGLSurface so it cannot + # run on fuchsia or when GL is not enabled. + sources += [ "shell_io_manager_unittests.cc" ] + deps += [ "//flutter/third_party/swiftshader" ] + } + + if (shell_enable_gl) { + deps += [ + "//flutter/third_party/angle:libEGL_static", + "//flutter/third_party/angle:libGLESv2_static", + "//flutter/third_party/swiftshader", + ] + } + } +} diff --git a/flutter/engine/src/flutter/shell/common/animator.cc b/flutter/engine/src/flutter/shell/common/animator.cc new file mode 100644 index 0000000000000000000000000000000000000000..e8329c11906e2128911d439491cc1f97ba129d6f --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/animator.cc @@ -0,0 +1,329 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/animator.h" + +#include "flutter/common/constants.h" +#include "flutter/flow/frame_timings.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/fml/trace_event.h" +#include "third_party/dart/runtime/include/dart_tools_api.h" + +namespace flutter { + +namespace { + +// Wait 51 milliseconds (which is 1 more milliseconds than 3 frames at 60hz) +// before notifying the engine that we are idle. See comments in |BeginFrame| +// for further discussion on why this is necessary. +constexpr fml::TimeDelta kNotifyIdleTaskWaitTime = + fml::TimeDelta::FromMilliseconds(51); + +} // namespace + +Animator::Animator(Delegate& delegate, + const TaskRunners& task_runners, + std::unique_ptr waiter) + : delegate_(delegate), + task_runners_(task_runners), + waiter_(std::move(waiter)), +#if SHELL_ENABLE_METAL + layer_tree_pipeline_(std::make_shared(2)), +#else // SHELL_ENABLE_METAL + // TODO(dnfield): We should remove this logic and set the pipeline depth + // back to 2 in this case. See + // https://github.com/flutter/engine/pull/9132 for discussion. + layer_tree_pipeline_(std::make_shared( + task_runners.GetPlatformTaskRunner() == + task_runners.GetRasterTaskRunner() + ? 1 + : 2)), +#endif // SHELL_ENABLE_METAL + pending_frame_semaphore_(1), + weak_factory_(this) { +} + +Animator::~Animator() = default; + +void Animator::EnqueueTraceFlowId(uint64_t trace_flow_id) { + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetUITaskRunner(), + [self = weak_factory_.GetWeakPtr(), trace_flow_id] { + if (!self) { + return; + } + self->trace_flow_ids_.push_back(trace_flow_id); + self->ScheduleMaybeClearTraceFlowIds(); + }); +} + +void Animator::BeginFrame( + std::unique_ptr frame_timings_recorder) { + TRACE_EVENT_ASYNC_END0("flutter", "Frame Request Pending", + frame_request_number_); + // Clear layer trees rendered out of a frame. Only Animator::Render called + // within a frame is used. + layer_trees_tasks_.clear(); + + frame_request_number_++; + + frame_timings_recorder_ = std::move(frame_timings_recorder); + frame_timings_recorder_->RecordBuildStart(fml::TimePoint::Now()); + + size_t flow_id_count = trace_flow_ids_.size(); + std::unique_ptr flow_ids = + std::make_unique(flow_id_count); + for (size_t i = 0; i < flow_id_count; ++i) { + flow_ids.get()[i] = trace_flow_ids_.at(i); + } + + TRACE_EVENT_WITH_FRAME_NUMBER(frame_timings_recorder_, "flutter", + "Animator::BeginFrame", flow_id_count, + flow_ids.get()); + + while (!trace_flow_ids_.empty()) { + uint64_t trace_flow_id = trace_flow_ids_.front(); + TRACE_FLOW_END("flutter", "PointerEvent", trace_flow_id); + trace_flow_ids_.pop_front(); + } + + frame_scheduled_ = false; + regenerate_layer_trees_ = false; + pending_frame_semaphore_.Signal(); + + if (!producer_continuation_) { + // We may already have a valid pipeline continuation in case a previous + // begin frame did not result in an Animator::Render. Simply reuse that + // instead of asking the pipeline for a fresh continuation. + producer_continuation_ = layer_tree_pipeline_->Produce(); + + if (!producer_continuation_) { + // If we still don't have valid continuation, the pipeline is currently + // full because the consumer is being too slow. Try again at the next + // frame interval. + TRACE_EVENT0("flutter", "PipelineFull"); + RequestFrame(); + return; + } + } + + // We have acquired a valid continuation from the pipeline and are ready + // to service potential frame. + FML_DCHECK(producer_continuation_); + const fml::TimePoint frame_target_time = + frame_timings_recorder_->GetVsyncTargetTime(); + dart_frame_deadline_ = frame_target_time.ToEpochDelta(); + uint64_t frame_number = frame_timings_recorder_->GetFrameNumber(); + delegate_.OnAnimatorBeginFrame(frame_target_time, frame_number); +} + +void Animator::EndFrame() { + if (frame_timings_recorder_ == nullptr) { + // `EndFrame` has been called in this frame. This happens if the engine has + // called `OnAllViewsRendered` and then the end of the vsync task calls + // `EndFrame` again. + return; + } + if (!layer_trees_tasks_.empty()) { + // The build is completed in OnAnimatorBeginFrame. + frame_timings_recorder_->RecordBuildEnd(fml::TimePoint::Now()); + + delegate_.OnAnimatorUpdateLatestFrameTargetTime( + frame_timings_recorder_->GetVsyncTargetTime()); + + // Commit the pending continuation. + std::vector> layer_tree_task_list; + layer_tree_task_list.reserve(layer_trees_tasks_.size()); + for (auto& [view_id, layer_tree_task] : layer_trees_tasks_) { + layer_tree_task_list.push_back(std::move(layer_tree_task)); + } + layer_trees_tasks_.clear(); + PipelineProduceResult result = producer_continuation_.Complete( + std::make_unique(std::move(layer_tree_task_list), + std::move(frame_timings_recorder_))); + + if (!result.success) { + FML_DLOG(INFO) << "Failed to commit to the pipeline"; + } else if (!result.is_first_item) { + // Do nothing. It has been successfully pushed to the pipeline but not as + // the first item. Eventually the 'Rasterizer' will consume it, so we + // don't need to notify the delegate. + } else { + delegate_.OnAnimatorDraw(layer_tree_pipeline_); + } + } + frame_timings_recorder_ = nullptr; + + if (!frame_scheduled_ && has_rendered_) { + // Wait a tad more than 3 60hz frames before reporting a big idle period. + // This is a heuristic that is meant to avoid giving false positives to the + // VM when we are about to schedule a frame in the next vsync, the idea + // being that if there have been three vsyncs with no frames it's a good + // time to start doing GC work. + task_runners_.GetUITaskRunner()->PostDelayedTask( + [self = weak_factory_.GetWeakPtr()]() { + if (!self) { + return; + } + // If there's a frame scheduled, bail. + // If there's no frame scheduled, but we're not yet past the last + // vsync deadline, bail. + if (!self->frame_scheduled_) { + auto now = + fml::TimeDelta::FromMicroseconds(Dart_TimelineGetMicros()); + if (now > self->dart_frame_deadline_) { + TRACE_EVENT0("flutter", "BeginFrame idle callback"); + self->delegate_.OnAnimatorNotifyIdle( + now + fml::TimeDelta::FromMilliseconds(100)); + } + } + }, + kNotifyIdleTaskWaitTime); + } + FML_DCHECK(layer_trees_tasks_.empty()); + FML_DCHECK(frame_timings_recorder_ == nullptr); +} + +void Animator::Render(int64_t view_id, + std::unique_ptr layer_tree, + float device_pixel_ratio) { + has_rendered_ = true; + + if (!frame_timings_recorder_) { + // Framework can directly call render with a built scene. A major reason is + // to render warm up frames. + frame_timings_recorder_ = std::make_unique(); + const fml::TimePoint placeholder_time = fml::TimePoint::Now(); + frame_timings_recorder_->RecordVsync(placeholder_time, placeholder_time); + frame_timings_recorder_->RecordBuildStart(placeholder_time); + } + + TRACE_EVENT_WITH_FRAME_NUMBER(frame_timings_recorder_, "flutter", + "Animator::Render", /*flow_id_count=*/0, + /*flow_ids=*/nullptr); + + // Only inserts if the view ID has not been rendered before, ignoring + // duplicate Render calls. + layer_trees_tasks_.try_emplace( + view_id, std::make_unique(view_id, std::move(layer_tree), + device_pixel_ratio)); +} + +const std::weak_ptr Animator::GetVsyncWaiter() const { + std::weak_ptr weak = waiter_; + return weak; +} + +bool Animator::CanReuseLastLayerTrees() { + return !regenerate_layer_trees_; +} + +void Animator::DrawLastLayerTrees( + std::unique_ptr frame_timings_recorder) { + // This method is very cheap, but this makes it explicitly clear in trace + // files. + TRACE_EVENT0("flutter", "Animator::DrawLastLayerTrees"); + + pending_frame_semaphore_.Signal(); + // In this case BeginFrame doesn't get called, we need to + // adjust frame timings to update build start and end times, + // given that the frame doesn't get built in this case, we + // will use Now() for both start and end times as an indication. + const auto now = fml::TimePoint::Now(); + frame_timings_recorder->RecordBuildStart(now); + frame_timings_recorder->RecordBuildEnd(now); + delegate_.OnAnimatorDrawLastLayerTrees(std::move(frame_timings_recorder)); +} + +void Animator::RequestFrame(bool regenerate_layer_trees) { + if (regenerate_layer_trees && !regenerate_layer_trees_) { + // This event will be closed by BeginFrame. BeginFrame will only be called + // if regenerating the layer trees. If a frame has been requested to update + // an external texture, this will be false and no BeginFrame call will + // happen. + TRACE_EVENT_ASYNC_BEGIN0("flutter", "Frame Request Pending", + frame_request_number_); + regenerate_layer_trees_ = true; + } + + if (!pending_frame_semaphore_.TryWait()) { + // Multiple calls to Animator::RequestFrame will still result in a + // single request to the VsyncWaiter. + return; + } + + // The AwaitVSync is going to call us back at the next VSync. However, we want + // to be reasonably certain that the UI thread is not in the middle of a + // particularly expensive callout. We post the AwaitVSync to run right after + // an idle. This does NOT provide a guarantee that the UI thread has not + // started an expensive operation right after posting this message however. + // To support that, we need edge triggered wakes on VSync. + + task_runners_.GetUITaskRunner()->PostTask( + [self = weak_factory_.GetWeakPtr()]() { + if (!self) { + return; + } + self->AwaitVSync(); + }); + frame_scheduled_ = true; +} + +void Animator::AwaitVSync() { + waiter_->AsyncWaitForVsync( + [self = weak_factory_.GetWeakPtr()]( + std::unique_ptr frame_timings_recorder) { + if (self) { + if (self->CanReuseLastLayerTrees()) { + self->DrawLastLayerTrees(std::move(frame_timings_recorder)); + } else { + self->BeginFrame(std::move(frame_timings_recorder)); + self->EndFrame(); + } + } + }); + if (has_rendered_) { + delegate_.OnAnimatorNotifyIdle(dart_frame_deadline_); + } +} + +void Animator::OnAllViewsRendered() { + if (!layer_trees_tasks_.empty()) { + EndFrame(); + } +} + +void Animator::ScheduleSecondaryVsyncCallback(uintptr_t id, + const fml::closure& callback) { + waiter_->ScheduleSecondaryCallback(id, callback); +} + +void Animator::ScheduleMaybeClearTraceFlowIds() { + waiter_->ScheduleSecondaryCallback( + reinterpret_cast(this), [self = weak_factory_.GetWeakPtr()] { + if (!self) { + return; + } + if (!self->frame_scheduled_ && !self->trace_flow_ids_.empty()) { + size_t flow_id_count = self->trace_flow_ids_.size(); + std::unique_ptr flow_ids = + std::make_unique(flow_id_count); + for (size_t i = 0; i < flow_id_count; ++i) { + flow_ids.get()[i] = self->trace_flow_ids_.at(i); + } + + TRACE_EVENT0_WITH_FLOW_IDS( + "flutter", "Animator::ScheduleMaybeClearTraceFlowIds - callback", + flow_id_count, flow_ids.get()); + + while (!self->trace_flow_ids_.empty()) { + auto flow_id = self->trace_flow_ids_.front(); + TRACE_FLOW_END("flutter", "PointerEvent", flow_id); + self->trace_flow_ids_.pop_front(); + } + } + }); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/animator.h b/flutter/engine/src/flutter/shell/common/animator.h new file mode 100644 index 0000000000000000000000000000000000000000..d559945358b990eaf19cb4864fdbcf4d6b2b9ca5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/animator.h @@ -0,0 +1,160 @@ +// 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_COMMON_ANIMATOR_H_ +#define FLUTTER_SHELL_COMMON_ANIMATOR_H_ + +#include + +#include "flutter/common/task_runners.h" +#include "flutter/flow/frame_timings.h" +#include "flutter/fml/memory/ref_ptr.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/fml/synchronization/semaphore.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/shell/common/pipeline.h" +#include "flutter/shell/common/rasterizer.h" +#include "flutter/shell/common/vsync_waiter.h" + +namespace flutter { + +namespace testing { +class ShellTest; +} + +/// Executor of animations. +/// +/// In conjunction with the |VsyncWaiter| it allows callers (typically Dart +/// code) to schedule work that ends up generating a |LayerTree|. +class Animator final { + public: + class Delegate { + public: + virtual void OnAnimatorBeginFrame(fml::TimePoint frame_target_time, + uint64_t frame_number) = 0; + + virtual void OnAnimatorNotifyIdle(fml::TimeDelta deadline) = 0; + + virtual void OnAnimatorUpdateLatestFrameTargetTime( + fml::TimePoint frame_target_time) = 0; + + virtual void OnAnimatorDraw(std::shared_ptr pipeline) = 0; + + virtual void OnAnimatorDrawLastLayerTrees( + std::unique_ptr frame_timings_recorder) = 0; + }; + + Animator(Delegate& delegate, + const TaskRunners& task_runners, + std::unique_ptr waiter); + + ~Animator(); + + void RequestFrame(bool regenerate_layer_trees = true); + + //-------------------------------------------------------------------------- + /// @brief Tells the Animator that all views that should render for this + /// frame have been rendered. + /// + /// In regular frames, since all `Render` calls must take place + /// during a vsync task, the Animator knows that all views have + /// been rendered at the end of the vsync task, therefore calling + /// this method is not needed. + /// + /// However, the engine might decide to start it a bit earlier, for + /// example, if the engine decides that no more views can be + /// rendered, so that the rasterization can start a bit earlier. + /// + /// This method is also useful in warm-up frames. In a warm up + /// frame, `Animator::Render` is called out of vsync tasks, and + /// Animator requires an explicit end-of-frame call to know when to + /// send the layer trees to the pipeline. + /// + /// For more about warm up frames, see + /// `PlatformDispatcher.scheduleWarmUpFrame`. + /// + void OnAllViewsRendered(); + + //-------------------------------------------------------------------------- + /// @brief Tells the Animator that this frame needs to render another view. + /// + /// This method must be called during a vsync callback, or + /// technically, between Animator::BeginFrame and Animator::EndFrame + /// (both private methods). Otherwise, this call will be ignored. + /// + void Render(int64_t view_id, + std::unique_ptr layer_tree, + float device_pixel_ratio); + + const std::weak_ptr GetVsyncWaiter() const; + + //-------------------------------------------------------------------------- + /// @brief Schedule a secondary callback to be executed right after the + /// main `VsyncWaiter::AsyncWaitForVsync` callback (which is added + /// by `Animator::RequestFrame`). + /// + /// Like the callback in `AsyncWaitForVsync`, this callback is + /// only scheduled to be called once, and it's supposed to be + /// called in the UI thread. If there is no AsyncWaitForVsync + /// callback (`Animator::RequestFrame` is not called), this + /// secondary callback will still be executed at vsync. + /// + /// This callback is used to provide the vsync signal needed by + /// `SmoothPointerDataDispatcher`, and for our own flow events. + /// + /// @see `PointerDataDispatcher::ScheduleSecondaryVsyncCallback`. + void ScheduleSecondaryVsyncCallback(uintptr_t id, + const fml::closure& callback); + + // Enqueue |trace_flow_id| into |trace_flow_ids_|. The flow event will be + // ended at either the next frame, or the next vsync interval with no active + // rendering. + void EnqueueTraceFlowId(uint64_t trace_flow_id); + + private: + // Animator's work during a vsync is split into two methods, BeginFrame and + // EndFrame. The two methods should be called synchronously back-to-back to + // avoid being interrupted by a regular vsync. The reason to split them is to + // allow ShellTest::PumpOneFrame to insert a Render in between. + + void BeginFrame(std::unique_ptr frame_timings_recorder); + void EndFrame(); + + bool CanReuseLastLayerTrees(); + + void DrawLastLayerTrees( + std::unique_ptr frame_timings_recorder); + + void AwaitVSync(); + + // Clear |trace_flow_ids_| if |frame_scheduled_| is false. + void ScheduleMaybeClearTraceFlowIds(); + + Delegate& delegate_; + TaskRunners task_runners_; + std::shared_ptr waiter_; + + std::unique_ptr frame_timings_recorder_; + std::unordered_map> + layer_trees_tasks_; + uint64_t frame_request_number_ = 1; + fml::TimeDelta dart_frame_deadline_; + std::shared_ptr layer_tree_pipeline_; + fml::Semaphore pending_frame_semaphore_; + FramePipeline::ProducerContinuation producer_continuation_; + bool regenerate_layer_trees_ = false; + bool frame_scheduled_ = false; + std::deque trace_flow_ids_; + bool has_rendered_ = false; + + fml::WeakPtrFactory weak_factory_; + + friend class testing::ShellTest; + + FML_DISALLOW_COPY_AND_ASSIGN(Animator); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_ANIMATOR_H_ diff --git a/flutter/engine/src/flutter/shell/common/animator_unittests.cc b/flutter/engine/src/flutter/shell/common/animator_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..f5f71ae341f725010c5ff0d7108b5c9ef05a0508 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/animator_unittests.cc @@ -0,0 +1,267 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include "flutter/shell/common/animator.h" + +#include +#include +#include + +#include "flutter/shell/common/shell_test.h" +#include "flutter/shell/common/shell_test_platform_view.h" +#include "flutter/testing/post_task_sync.h" +#include "flutter/testing/testing.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace flutter { +namespace testing { + +constexpr int64_t kImplicitViewId = 0; + +class FakeAnimatorDelegate : public Animator::Delegate { + public: + MOCK_METHOD(void, + OnAnimatorBeginFrame, + (fml::TimePoint frame_target_time, uint64_t frame_number), + (override)); + + void OnAnimatorNotifyIdle(fml::TimeDelta deadline) override { + notify_idle_called_ = true; + } + + MOCK_METHOD(void, + OnAnimatorUpdateLatestFrameTargetTime, + (fml::TimePoint frame_target_time), + (override)); + + MOCK_METHOD(void, + OnAnimatorDraw, + (std::shared_ptr pipeline), + (override)); + + void OnAnimatorDrawLastLayerTrees( + std::unique_ptr frame_timings_recorder) override {} + + bool notify_idle_called_ = false; +}; + +TEST_F(ShellTest, VSyncTargetTime) { + // Add native callbacks to listen for window.onBeginFrame + int64_t target_time; + fml::AutoResetWaitableEvent on_target_time_latch; + auto nativeOnBeginFrame = [&on_target_time_latch, + &target_time](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + target_time = + tonic::DartConverter::FromArguments(args, 0, exception); + on_target_time_latch.Signal(); + }; + AddNativeCallback("NativeOnBeginFrame", + CREATE_NATIVE_ENTRY(nativeOnBeginFrame)); + + // Create all te prerequisites for a shell. + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + auto settings = CreateSettingsForFixture(); + + std::unique_ptr shell; + + TaskRunners task_runners = GetTaskRunnersForFixture(); + // this is not used as we are not using simulated events. + const auto vsync_clock = std::make_shared(); + CreateVsyncWaiter create_vsync_waiter = [&]() { + return static_cast>( + std::make_unique(task_runners)); + }; + + // create a shell with a constant firing vsync waiter. + auto platform_task = std::async(std::launch::async, [&]() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + + shell = Shell::Create( + flutter::PlatformData(), task_runners, settings, + [vsync_clock, &create_vsync_waiter](Shell& shell) { + return ShellTestPlatformView::Create( + ShellTestPlatformView::DefaultBackendType(), shell, + shell.GetTaskRunners(), vsync_clock, create_vsync_waiter, nullptr, + shell.GetIsGpuDisabledSyncSwitch()); + }, + [](Shell& shell) { return std::make_unique(shell); }); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + configuration.SetEntrypoint("onBeginFrameMain"); + + RunEngine(shell.get(), std::move(configuration)); + }); + platform_task.wait(); + on_target_time_latch.Wait(); + const auto vsync_waiter_target_time = + ConstantFiringVsyncWaiter::kFrameTargetTime; + ASSERT_EQ(vsync_waiter_target_time.ToEpochDelta().ToMicroseconds(), + target_time); + + // validate that the latest target time has also been updated. + ASSERT_EQ(GetLatestFrameTargetTime(shell.get()), vsync_waiter_target_time); + + // teardown. + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, AnimatorDoesNotNotifyIdleBeforeRender) { + FakeAnimatorDelegate delegate; + TaskRunners task_runners = { + "test", + CreateNewThread(), // platform + CreateNewThread(), // raster + CreateNewThread(), // ui + CreateNewThread() // io + }; + + auto clock = std::make_shared(); + fml::AutoResetWaitableEvent latch; + std::shared_ptr animator; + + auto flush_vsync_task = [&] { + fml::AutoResetWaitableEvent ui_latch; + task_runners.GetUITaskRunner()->PostTask([&] { ui_latch.Signal(); }); + do { + clock->SimulateVSync(); + } while (ui_latch.WaitWithTimeout(fml::TimeDelta::FromMilliseconds(1))); + latch.Signal(); + }; + + // Create the animator on the UI task runner. + task_runners.GetUITaskRunner()->PostTask([&] { + auto vsync_waiter = static_cast>( + std::make_unique(task_runners, clock)); + animator = std::make_unique(delegate, task_runners, + std::move(vsync_waiter)); + latch.Signal(); + }); + latch.Wait(); + + // Validate it has not notified idle and start it. This will request a frame. + task_runners.GetUITaskRunner()->PostTask([&] { + ASSERT_FALSE(delegate.notify_idle_called_); + // Immediately request a frame saying it can reuse the last layer tree to + // avoid more calls to BeginFrame by the animator. + animator->RequestFrame(false); + task_runners.GetPlatformTaskRunner()->PostTask(flush_vsync_task); + }); + latch.Wait(); + ASSERT_FALSE(delegate.notify_idle_called_); + + fml::AutoResetWaitableEvent render_latch; + // Validate it has not notified idle and try to render. + task_runners.GetUITaskRunner()->PostDelayedTask( + [&] { + ASSERT_FALSE(delegate.notify_idle_called_); + EXPECT_CALL(delegate, OnAnimatorBeginFrame).WillOnce([&] { + auto layer_tree = + std::make_unique(nullptr, DlISize(600, 800)); + animator->Render(kImplicitViewId, std::move(layer_tree), 1.0); + render_latch.Signal(); + }); + // Request a frame that builds a layer tree and renders a frame. + // When the frame is rendered, render_latch will be signaled. + animator->RequestFrame(true); + task_runners.GetPlatformTaskRunner()->PostTask(flush_vsync_task); + }, + // See kNotifyIdleTaskWaitTime in animator.cc. + fml::TimeDelta::FromMilliseconds(60)); + latch.Wait(); + render_latch.Wait(); + + // A frame has been rendered, and the next frame request will notify idle. + // But at the moment there isn't another frame request, therefore it still + // hasn't notified idle. + task_runners.GetUITaskRunner()->PostTask([&] { + ASSERT_FALSE(delegate.notify_idle_called_); + // False to avoid getting cals to BeginFrame that will request more frames + // before we are ready. + animator->RequestFrame(false); + task_runners.GetPlatformTaskRunner()->PostTask(flush_vsync_task); + }); + latch.Wait(); + + // Now it should notify idle. Make sure it is destroyed on the UI thread. + ASSERT_TRUE(delegate.notify_idle_called_); + + task_runners.GetPlatformTaskRunner()->PostTask(flush_vsync_task); + latch.Wait(); + + task_runners.GetUITaskRunner()->PostTask([&] { + animator.reset(); + latch.Signal(); + }); + latch.Wait(); +} + +TEST_F(ShellTest, AnimatorDoesNotNotifyDelegateIfPipelineIsNotEmpty) { + FakeAnimatorDelegate delegate; + TaskRunners task_runners = { + "test", + CreateNewThread(), // platform + CreateNewThread(), // raster + CreateNewThread(), // ui + CreateNewThread() // io + }; + + auto clock = std::make_shared(); + std::shared_ptr animator; + + auto flush_vsync_task = [&] { + fml::AutoResetWaitableEvent ui_latch; + task_runners.GetUITaskRunner()->PostTask([&] { ui_latch.Signal(); }); + do { + clock->SimulateVSync(); + } while (ui_latch.WaitWithTimeout(fml::TimeDelta::FromMilliseconds(1))); + }; + + // Create the animator on the UI task runner. + PostTaskSync(task_runners.GetUITaskRunner(), [&] { + auto vsync_waiter = static_cast>( + std::make_unique(task_runners, clock)); + animator = std::make_unique(delegate, task_runners, + std::move(vsync_waiter)); + }); + + fml::AutoResetWaitableEvent begin_frame_latch; + // It must always be called when the method 'Animator::Render' is called, + // regardless of whether the pipeline is empty or not. + EXPECT_CALL(delegate, OnAnimatorUpdateLatestFrameTargetTime).Times(2); + // It will only be called once even though we call the method + // 'Animator::Render' twice. because it will only be called when the pipeline + // is empty. + EXPECT_CALL(delegate, OnAnimatorDraw).Times(1); + + for (int i = 0; i < 2; i++) { + task_runners.GetUITaskRunner()->PostTask([&] { + EXPECT_CALL(delegate, OnAnimatorBeginFrame).WillOnce([&] { + auto layer_tree = + std::make_unique(nullptr, DlISize(600, 800)); + animator->Render(kImplicitViewId, std::move(layer_tree), 1.0); + begin_frame_latch.Signal(); + }); + animator->RequestFrame(); + task_runners.GetPlatformTaskRunner()->PostTask(flush_vsync_task); + }); + begin_frame_latch.Wait(); + } + + PostTaskSync(task_runners.GetUITaskRunner(), [&] { animator.reset(); }); +} + +} // namespace testing +} // namespace flutter + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/common/base64.cc b/flutter/engine/src/flutter/shell/common/base64.cc new file mode 100644 index 0000000000000000000000000000000000000000..d98b5ecfda620d9945a84f158d11f77516569e90 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/base64.cc @@ -0,0 +1,160 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/base64.h" + +#include "flutter/fml/logging.h" + +#include + +#define DecodePad -2 +#define EncodePad 64 + +static const char kDefaultEncode[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/="; + +static const signed char kDecodeData[] = { + 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, + -1, -1, DecodePad, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51}; + +namespace flutter { + +Base64::Error Base64::Decode(const void* srcv, + size_t srcLength, + void* dstv, + size_t* dstLength) { + const unsigned char* src = static_cast(srcv); + unsigned char* dst = static_cast(dstv); + + int i = 0; + bool padTwo = false; + bool padThree = false; + char unsigned const* const end = src + srcLength; + while (src < end) { + unsigned char bytes[4] = {0, 0, 0, 0}; + int byte = 0; + do { + unsigned char srcByte = *src++; + if (srcByte == 0) { + *dstLength = i; + return Error::kNone; + } + if (srcByte <= ' ') { + continue; // treat as white space + } + if (srcByte < '+' || srcByte > 'z') { + return Error::kBadChar; + } + signed char decoded = kDecodeData[srcByte - '+']; + bytes[byte] = decoded; + if (decoded != DecodePad) { + if (decoded < 0) { + return Error::kBadChar; + } + byte++; + if (*src) { + continue; + } + if (byte == 0) { + *dstLength = i; + return Error::kNone; + } + if (byte == 4) { + break; + } + } + // As an optimization, if we find an equals sign + // we assume all future bytes to read are the + // appropriate number of padding equals signs. + if (byte < 2) { + return Error::kBadPadding; + } + padThree = true; + if (byte == 2) { + padTwo = true; + } + break; + } while (byte < 4); + int two = 0; + int three = 0; + if (dst) { + int one = static_cast(bytes[0] << 2); + two = bytes[1]; + one |= two >> 4; + two = static_cast((two << 4) & 0xFF); + three = bytes[2]; + two |= three >> 2; + three = static_cast((three << 6) & 0xFF); + three |= bytes[3]; + FML_DCHECK(one < 256 && two < 256 && three < 256); + dst[i] = static_cast(one); + } + i++; + if (padTwo) { + break; + } + if (dst) { + dst[i] = static_cast(two); + } + i++; + if (padThree) { + break; + } + if (dst) { + dst[i] = static_cast(three); + } + i++; + } + *dstLength = i; + return Error::kNone; +} + +size_t Base64::Encode(const void* srcv, size_t length, void* dstv) { + FML_DCHECK(dstv); + const unsigned char* src = static_cast(srcv); + unsigned char* dst = static_cast(dstv); + + const char* encode = kDefaultEncode; + size_t remainder = length % 3; + char unsigned const* const end = &src[length - remainder]; + while (src < end) { + unsigned a = *src++; + unsigned b = *src++; + unsigned c = *src++; + int d = c & 0x3F; + c = (c >> 6 | b << 2) & 0x3F; + b = (b >> 4 | a << 4) & 0x3F; + a = a >> 2; + // NOLINTBEGIN(clang-analyzer-core.NullDereference) + *dst++ = encode[a]; + *dst++ = encode[b]; + *dst++ = encode[c]; + *dst++ = encode[d]; + // NOLINTEND(clang-analyzer-core.NullDereference) + } + if (remainder > 0) { + int k1 = 0; + int k2 = EncodePad; + int a = static_cast(*src++); + if (remainder == 2) { + int b = *src++; + k1 = b >> 4; + k2 = (b << 2) & 0x3F; + } + // NOLINTBEGIN(clang-analyzer-core.NullDereference) + *dst++ = encode[a >> 2]; + *dst++ = encode[(k1 | a << 4) & 0x3F]; + *dst++ = encode[k2]; + *dst++ = encode[EncodePad]; + // NOLINTEND(clang-analyzer-core.NullDereference) + } + return EncodedSize(length); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/base64.h b/flutter/engine/src/flutter/shell/common/base64.h new file mode 100644 index 0000000000000000000000000000000000000000..18f8a56dad539d62912d54de88ea4aa0e1d84aac --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/base64.h @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_BASE64_H_ +#define FLUTTER_SHELL_COMMON_BASE64_H_ + +#include + +namespace flutter { + +struct Base64 { + public: + enum class Error { + kNone, + kBadPadding, + kBadChar, + }; + + /** + Base64 encodes src into dst. + + @param dst a pointer to a buffer large enough to receive the result. + + @return the required length of dst for encoding. + */ + static size_t Encode(const void* src, size_t length, void* dst); + + /** + Returns the length of the buffer that needs to be allocated to encode + srcDataLength bytes. + */ + static size_t EncodedSize(size_t srcDataLength) { + // Take the floor of division by 3 to find the number of groups that need to + // be encoded. Each group takes 4 bytes to be represented in base64. + return ((srcDataLength + 2) / 3) * 4; + } + + /** + Base64 decodes src into dst. + + This can be called once with 'dst' nullptr to get the required size, + then again with an allocated 'dst' pointer to do the actual decoding. + + @param dst nullptr or a pointer to a buffer large enough to receive the + result + + @param dstLength assigned the length dst is required to be. Must not be + nullptr. + */ + [[nodiscard]] static Error Decode(const void* src, + size_t srcLength, + void* dst, + size_t* dstLength); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_BASE64_H_ diff --git a/flutter/engine/src/flutter/shell/common/base64_unittests.cc b/flutter/engine/src/flutter/shell/common/base64_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..521a234bc1d2a1cc78e7886a41206540e1cb8d38 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/base64_unittests.cc @@ -0,0 +1,122 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/base64.h" + +#include "fml/logging.h" +#include "gtest/gtest.h" + +#include + +namespace flutter { +namespace testing { + +TEST(Base64, EncodeStrings) { + auto test = [](const std::string& input, const std::string& output) { + char buffer[256]; + size_t len = Base64::Encode(input.c_str(), input.length(), &buffer); + FML_CHECK(len <= 256); + ASSERT_EQ(len, Base64::EncodedSize(input.length())); + std::string actual(buffer, len); + ASSERT_STREQ(actual.c_str(), output.c_str()); + }; + // Some arbitrary strings + test("apple", "YXBwbGU="); + test("BANANA", "QkFOQU5B"); + test("Cherry Pie", "Q2hlcnJ5IFBpZQ=="); + test("fLoCcInAuCiNiHiLiPiLiFiCaTiOn", + "ZkxvQ2NJbkF1Q2lOaUhpTGlQaUxpRmlDYVRpT24="); + test("", ""); +} + +TEST(Base64, EncodeBytes) { + auto test = [](const uint8_t input[], size_t num, const std::string& output) { + char buffer[512]; + size_t len = Base64::Encode(input, num, &buffer); + FML_CHECK(len <= 512); + ASSERT_EQ(len, Base64::EncodedSize(num)); + std::string actual(buffer, len); + ASSERT_STREQ(actual.c_str(), output.c_str()); + }; + // Some arbitrary raw bytes + uint8_t e[] = {0x02, 0x71, 0x82, 0x81, 0x82, 0x84, 0x59}; + test(e, sizeof(e), "AnGCgYKEWQ=="); + + uint8_t pi[] = {0x03, 0x24, 0x3F, 0x6A, 0x88, 0x85}; + test(pi, sizeof(pi), "AyQ/aoiF"); + + uint8_t bytes[256]; + for (int i = 0; i < 256; i++) { + bytes[i] = i; + } + test(bytes, sizeof(bytes), + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gIS" + "IjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFV" + "WV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJ" + "iouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8v" + "b6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8P" + "Hy8/T19vf4+fr7/P3+/w=="); +} + +TEST(Base64, DecodeStringsSuccess) { + auto test = [](const std::string& input, const std::string& output) { + char buffer[256]; + size_t len = 0; + auto err = Base64::Decode(input.c_str(), input.length(), &buffer, &len); + ASSERT_EQ(err, Base64::Error::kNone); + FML_CHECK(len <= 256); + std::string actual(buffer, len); + ASSERT_STREQ(actual.c_str(), output.c_str()); + }; + // Some arbitrary strings + test("ZGF0ZQ==", "date"); + test("RWdncGxhbnQ=", "Eggplant"); + test("RmlzaCAmIENoaXBz", "Fish & Chips"); + test("U3VQZVJjQWxJZlJhR2lMaVN0SWNFeFBpQWxJZE9jSW9Vcw==", + "SuPeRcAlIfRaGiLiStIcExPiAlIdOcIoUs"); + + // Spaces are ignored + test("Y X Bwb GU=", "apple"); +} + +TEST(Base64, DecodeStringsHasErrors) { + auto test = [](const std::string& input, Base64::Error expectedError) { + char buffer[256]; + size_t len = 0; + auto err = Base64::Decode(input.c_str(), input.length(), &buffer, &len); + ASSERT_EQ(err, expectedError) << input; + }; + + test("Nuts&Bolts", Base64::Error::kBadChar); + test("Error!", Base64::Error::kBadChar); + test(":", Base64::Error::kBadChar); + + test("RmlzaCAmIENoaXBz=", Base64::Error::kBadPadding); + // Some cases of bad padding may be ignored due to an internal optimization + // test("ZGF0ZQ=", Base64::Error::kBadPadding); + // test("RWdncGxhbnQ", Base64::Error::kBadPadding); +} + +TEST(Base64, DecodeBytes) { + auto test = [](const std::string& input, const uint8_t output[], size_t num) { + char buffer[256]; + size_t len = 0; + auto err = Base64::Decode(input.c_str(), input.length(), &buffer, &len); + ASSERT_EQ(err, Base64::Error::kNone); + FML_CHECK(len <= 256); + ASSERT_EQ(num, len) << input; + for (int i = 0; i < static_cast(len); i++) { + ASSERT_EQ(uint8_t(buffer[i]), output[i]) << input << i; + } + }; + // Some arbitrary raw bytes, same as the byte output above + uint8_t e[] = {0x02, 0x71, 0x82, 0x81, 0x82, 0x84, 0x59}; + test("AnGCgYKEWQ==", e, sizeof(e)); + + uint8_t pi[] = {0x03, 0x24, 0x3F, 0x6A, 0x88, 0x85}; + test("AyQ/aoiF", pi, sizeof(pi)); +} + +} // namespace testing +} // namespace flutter \ No newline at end of file diff --git a/flutter/engine/src/flutter/shell/common/context_options.cc b/flutter/engine/src/flutter/shell/common/context_options.cc new file mode 100644 index 0000000000000000000000000000000000000000..bef8615f8df39b4f35c9d449e23b45fc5f4e99b4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/context_options.cc @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#if !SLIMPELLER + +#include "flutter/shell/common/context_options.h" + +#include "flutter/common/graphics/persistent_cache.h" + +namespace flutter { + +GrContextOptions MakeDefaultContextOptions(ContextType type, + std::optional api) { + GrContextOptions options; + + if (PersistentCache::cache_sksl()) { + options.fShaderCacheStrategy = GrContextOptions::ShaderCacheStrategy::kSkSL; + } + PersistentCache::MarkStrategySet(); + options.fPersistentCache = PersistentCache::GetCacheForProcess(); + + if (api.has_value() && api.value() == GrBackendApi::kOpenGL) { + // Using stencil buffers has caused memory and performance regressions. + // See b/226484927 for internal customer regressions doc. + // Before enabling, we need to show a motivating case for where it will + // improve performance on OpenGL backend. + options.fAvoidStencilBuffers = true; + + // To get video playback on the widest range of devices, we limit Skia to + // ES2 shading language when the ES3 external image extension is missing. + options.fPreferExternalImagesOverES3 = true; + } + + // TODO(goderbauer): remove option when skbug.com/7523 is fixed. + options.fDisableGpuYUVConversion = true; + + options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo; + + options.fReducedShaderVariations = false; + + return options; +}; + +} // namespace flutter + +#endif // !SLIMPELLER diff --git a/flutter/engine/src/flutter/shell/common/context_options.h b/flutter/engine/src/flutter/shell/common/context_options.h new file mode 100644 index 0000000000000000000000000000000000000000..0d37735f957f53bdb9b84da4057a2201cbe97eb7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/context_options.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_CONTEXT_OPTIONS_H_ +#define FLUTTER_SHELL_COMMON_CONTEXT_OPTIONS_H_ + +#if !SLIMPELLER + +#include + +#include "flutter/fml/macros.h" +#include "third_party/skia/include/gpu/ganesh/GrContextOptions.h" + +namespace flutter { + +enum class ContextType { + /// The context is used to render to a texture or renderbuffer. + kRender, + /// The context will only be used to transfer resources to and from device + /// memory. No rendering will be performed using this context. + kResource, +}; + +//------------------------------------------------------------------------------ +/// @brief Initializes GrContextOptions with values suitable for Flutter. +/// The options can be further tweaked before a GrContext is created +/// from these options. +/// +/// @param[in] type The type of context that will be created using these +/// options. +/// @param[in] type The client rendering API that will be wrapped using a +/// context with these options. This argument is only required +/// if the context is going to be used with a particular +/// client rendering API. +/// +/// @return The default graphics context options. +/// +GrContextOptions MakeDefaultContextOptions( + ContextType type, + std::optional api = std::nullopt); + +} // namespace flutter + +#endif // !SLIMPELLER + +#endif // FLUTTER_SHELL_COMMON_CONTEXT_OPTIONS_H_ diff --git a/flutter/engine/src/flutter/shell/common/context_options_unittests.cc b/flutter/engine/src/flutter/shell/common/context_options_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..e49f8e2894944c3d5912aef9068d985c98cdf328 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/context_options_unittests.cc @@ -0,0 +1,19 @@ +// 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 "context_options.h" + +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +TEST(ContextOptionsTest, OpenGLDisablesStencilBuffers) { + auto options = MakeDefaultContextOptions(flutter::ContextType::kRender, + GrBackendApi::kOpenGL); + EXPECT_TRUE(options.fAvoidStencilBuffers); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/dart_native_benchmarks.cc b/flutter/engine/src/flutter/shell/common/dart_native_benchmarks.cc new file mode 100644 index 0000000000000000000000000000000000000000..ff3999eefe0acf3dfba9437e7371e0c466942c66 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/dart_native_benchmarks.cc @@ -0,0 +1,108 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/shell.h" + +#include "flutter/benchmarking/benchmarking.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/testing/dart_fixture.h" +#include "flutter/testing/dart_isolate_runner.h" +#include "flutter/testing/testing.h" +#include "fml/synchronization/count_down_latch.h" +#include "runtime/dart_vm_lifecycle.h" + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace flutter::testing { + +class DartNativeBenchmarks : public DartFixture, public benchmark::Fixture { + public: + DartNativeBenchmarks() : DartFixture() {} + + void SetUp(const ::benchmark::State& state) {} + + void TearDown(const ::benchmark::State& state) {} + + private: + FML_DISALLOW_COPY_AND_ASSIGN(DartNativeBenchmarks); +}; + +BENCHMARK_F(DartNativeBenchmarks, TimeToFirstNativeMessageFromIsolateInNewVM) +(benchmark::State& st) { + while (st.KeepRunning()) { + fml::AutoResetWaitableEvent latch; + st.PauseTiming(); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + AddNativeCallback("NotifyNative", + CREATE_NATIVE_ENTRY(([&latch](Dart_NativeArguments args) { + latch.Signal(); + }))); + + const auto settings = CreateSettingsForFixture(); + DartVMRef vm_ref = DartVMRef::Create(settings); + + ThreadHost thread_host("io.flutter.test.DartNativeBenchmarks.", + ThreadHost::Type::kPlatform | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners( + "test", + thread_host.platform_thread->GetTaskRunner(), // platform + thread_host.platform_thread->GetTaskRunner(), // raster + thread_host.ui_thread->GetTaskRunner(), // ui + thread_host.io_thread->GetTaskRunner() // io + ); + + { + st.ResumeTiming(); + auto isolate = + RunDartCodeInIsolate(vm_ref, settings, task_runners, "notifyNative", + {}, GetDefaultKernelFilePath()); + ASSERT_TRUE(isolate); + ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); + latch.Wait(); + } + } +} + +BENCHMARK_F(DartNativeBenchmarks, MultipleDartToNativeMessages) +(benchmark::State& st) { + while (st.KeepRunning()) { + fml::CountDownLatch latch(1000); + st.PauseTiming(); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + AddNativeCallback("NotifyNative", + CREATE_NATIVE_ENTRY(([&latch](Dart_NativeArguments args) { + latch.CountDown(); + }))); + + const auto settings = CreateSettingsForFixture(); + DartVMRef vm_ref = DartVMRef::Create(settings); + + ThreadHost thread_host("io.flutter.test.DartNativeBenchmarks.", + ThreadHost::Type::kPlatform | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners( + "test", + thread_host.platform_thread->GetTaskRunner(), // platform + thread_host.platform_thread->GetTaskRunner(), // raster + thread_host.ui_thread->GetTaskRunner(), // ui + thread_host.io_thread->GetTaskRunner() // io + ); + + { + st.ResumeTiming(); + auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, + "thousandCallsToNative", {}, + GetDefaultKernelFilePath()); + ASSERT_TRUE(isolate); + ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); + latch.Wait(); + } + } +} + +} // namespace flutter::testing + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/common/display.cc b/flutter/engine/src/flutter/shell/common/display.cc new file mode 100644 index 0000000000000000000000000000000000000000..05feded91be5a55d510fa5d8d5b05a91f63e30df --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/display.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/display.h" + +namespace flutter { +double Display::GetRefreshRate() const { + return refresh_rate_; +} +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/display.h b/flutter/engine/src/flutter/shell/common/display.h new file mode 100644 index 0000000000000000000000000000000000000000..361e45bfc1207157c02f36137fca33fc24eaf742 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/display.h @@ -0,0 +1,91 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_DISPLAY_H_ +#define FLUTTER_SHELL_COMMON_DISPLAY_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/common/variable_refresh_rate_reporter.h" + +namespace flutter { + +/// Unique ID per display that is stable until the Flutter application restarts. +/// See also: `flutter::Display` +typedef size_t DisplayId; + +/// To be used when the display refresh rate is unknown. +static constexpr double kUnknownDisplayRefreshRate = 0; + +/// The POD of a |Display|. This data is for a point in time and suitable +/// for copying. +struct DisplayData { + DisplayId id; + double width; + double height; + double pixel_ratio; + double refresh_rate; +}; + +/// Display refers to a graphics hardware system consisting of a framebuffer, +/// typically a monitor or a screen. This class holds the various display +/// settings. +class Display { + public: + //------------------------------------------------------------------------------ + /// @brief Construct a new Display object in case where the display id of the + /// display is known. + Display(DisplayId display_id, + double refresh_rate, + double width, + double height, + double device_pixel_ratio) + : display_id_(display_id), + refresh_rate_(refresh_rate), + width_(width), + height_(height), + device_pixel_ratio_(device_pixel_ratio) {} + + virtual ~Display() = default; + + // Get the display's maximum refresh rate in the unit of frame per second. + // Return `kUnknownDisplayRefreshRate` if the refresh rate is unknown. + virtual double GetRefreshRate() const; + + /// Returns the `DisplayId` of the display. + DisplayId GetDisplayId() const { return display_id_; } + + /// The width of the display in physical pixels. + virtual double GetWidth() const { return width_; } + + /// The height of the display in physical pixels. + virtual double GetHeight() const { return height_; } + + /// The device pixel ratio of the display. + virtual double GetDevicePixelRatio() const { return device_pixel_ratio_; } + + DisplayData GetDisplayData() { + return DisplayData{ + .id = GetDisplayId(), + .width = GetWidth(), + .height = GetHeight(), + .pixel_ratio = GetDevicePixelRatio(), + .refresh_rate = GetRefreshRate(), + }; + } + + private: + DisplayId display_id_; + double refresh_rate_; + double width_; + double height_; + double device_pixel_ratio_; + + FML_DISALLOW_COPY_AND_ASSIGN(Display); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_DISPLAY_H_ diff --git a/flutter/engine/src/flutter/shell/common/display_manager.cc b/flutter/engine/src/flutter/shell/common/display_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..e9382028dc6268cdad38506040184af822b517b7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/display_manager.cc @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/display_manager.h" + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" + +namespace flutter { + +DisplayManager::DisplayManager() = default; + +DisplayManager::~DisplayManager() = default; + +double DisplayManager::GetMainDisplayRefreshRate() const { + std::scoped_lock lock(displays_mutex_); + if (displays_.empty()) { + return kUnknownDisplayRefreshRate; + } else { + return displays_[0]->GetRefreshRate(); + } +} + +void DisplayManager::HandleDisplayUpdates( + std::vector> displays) { + FML_DCHECK(!displays.empty()); + std::scoped_lock lock(displays_mutex_); + displays_ = std::move(displays); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/display_manager.h b/flutter/engine/src/flutter/shell/common/display_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..ae3e9d0a5607eac7f8992ef3c0f85249893c1050 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/display_manager.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_DISPLAY_MANAGER_H_ +#define FLUTTER_SHELL_COMMON_DISPLAY_MANAGER_H_ + +#include +#include + +#include "flutter/shell/common/display.h" + +namespace flutter { + +/// Manages lifecycle of the connected displays. This class is thread-safe. +class DisplayManager { + public: + DisplayManager(); + + ~DisplayManager(); + + /// Returns the display refresh rate of the main display. In cases where there + /// is only one display connected, it will return that. We do not yet support + /// cases where there are multiple displays. + /// + /// When there are no registered displays, it returns + /// `kUnknownDisplayRefreshRate`. + double GetMainDisplayRefreshRate() const; + + /// Handles the display updates. + void HandleDisplayUpdates(std::vector> displays); + + private: + /// Guards `displays_` vector. + mutable std::mutex displays_mutex_; + std::vector> displays_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_DISPLAY_MANAGER_H_ diff --git a/flutter/engine/src/flutter/shell/common/dl_op_spy.cc b/flutter/engine/src/flutter/shell/common/dl_op_spy.cc new file mode 100644 index 0000000000000000000000000000000000000000..2b0426a1a079af6f7f1fe50724ff00ad75d23250 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/dl_op_spy.cc @@ -0,0 +1,156 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/dl_op_spy.h" + +namespace flutter { + +bool DlOpSpy::did_draw() { + return did_draw_; +} + +void DlOpSpy::setColor(DlColor color) { + color_ = color; + if (color.isTransparent()) { + will_draw_ = false; + } else { + will_draw_ = true; + } +} +void DlOpSpy::setColorSource(const DlColorSource* source) { + if (!source) { + // Restore settings based on previously set color + setColor(color_); + return; + } + will_draw_ = true; +} +void DlOpSpy::save() {} +void DlOpSpy::saveLayer(const DlRect& bounds, + const SaveLayerOptions options, + const DlImageFilter* backdrop, + std::optional backdrop_id) {} +void DlOpSpy::restore() {} +void DlOpSpy::drawColor(DlColor color, DlBlendMode mode) { + did_draw_ |= !color.isTransparent(); +} +void DlOpSpy::drawPaint() { + did_draw_ |= will_draw_; +} +// TODO(cyanglaz): check whether the shape (line, rect, oval, etc) needs to be +// evaluated. https://github.com/flutter/flutter/issues/123803 +void DlOpSpy::drawLine(const DlPoint& p0, const DlPoint& p1) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawDashedLine(const DlPoint& p0, + const DlPoint& p1, + DlScalar on_length, + DlScalar off_length) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawRect(const DlRect& rect) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawOval(const DlRect& bounds) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawCircle(const DlPoint& center, DlScalar radius) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawRoundRect(const DlRoundRect& rrect) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawDiffRoundRect(const DlRoundRect& outer, + const DlRoundRect& inner) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawRoundSuperellipse(const DlRoundSuperellipse& rse) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawPath(const DlPath& path) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawArc(const DlRect& oval_bounds, + DlScalar start_degrees, + DlScalar sweep_degrees, + bool use_center) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawPoints(DlPointMode mode, + uint32_t count, + const DlPoint points[]) { + did_draw_ |= will_draw_; +} +void DlOpSpy::drawVertices(const std::shared_ptr& vertices, + DlBlendMode mode) { + did_draw_ |= will_draw_; +} +// In theory, below drawImage methods can produce a transparent screen when a +// transparent image is provided. The operation of determine whether an image is +// transparent needs examine all the pixels in the image object, which is slow. +// Drawing a completely transparent image is not a valid use case, thus, such +// case is ignored. +void DlOpSpy::drawImage(const sk_sp image, + const DlPoint& point, + DlImageSampling sampling, + bool render_with_attributes) { + did_draw_ = true; +} +void DlOpSpy::drawImageRect(const sk_sp image, + const DlRect& src, + const DlRect& dst, + DlImageSampling sampling, + bool render_with_attributes, + DlSrcRectConstraint constraint) { + did_draw_ = true; +} +void DlOpSpy::drawImageNine(const sk_sp image, + const DlIRect& center, + const DlRect& dst, + DlFilterMode filter, + bool render_with_attributes) { + did_draw_ = true; +} +void DlOpSpy::drawAtlas(const sk_sp atlas, + const DlRSTransform xform[], + const DlRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const DlRect* cull_rect, + bool render_with_attributes) { + did_draw_ = true; +} +void DlOpSpy::drawDisplayList(const sk_sp display_list, + DlScalar opacity) { + if (did_draw_ || opacity == 0) { + return; + } + DlOpSpy receiver; + display_list->Dispatch(receiver); + did_draw_ |= receiver.did_draw(); +} +void DlOpSpy::drawTextBlob(const sk_sp blob, + DlScalar x, + DlScalar y) { + did_draw_ |= will_draw_; +} + +void DlOpSpy::drawTextFrame( + const std::shared_ptr& text_frame, + DlScalar x, + DlScalar y) { + did_draw_ |= will_draw_; +} + +void DlOpSpy::drawShadow(const DlPath& path, + const DlColor color, + const DlScalar elevation, + bool transparent_occluder, + DlScalar dpr) { + did_draw_ |= !color.isTransparent(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/dl_op_spy.h b/flutter/engine/src/flutter/shell/common/dl_op_spy.h new file mode 100644 index 0000000000000000000000000000000000000000..b6ebae2ef427f7976a7594ce1ffcc427561b49d9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/dl_op_spy.h @@ -0,0 +1,123 @@ +// 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_COMMON_DL_OP_SPY_H_ +#define FLUTTER_SHELL_COMMON_DL_OP_SPY_H_ + +#include "flutter/display_list/dl_op_receiver.h" +#include "flutter/display_list/utils/dl_receiver_utils.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// Receives to drawing commands of a DisplayListBuilder. +/// +/// This is used to determine whether any non-transparent pixels will be drawn +/// on the canvas. +/// All the drawImage operations are considered drawing non-transparent pixels. +/// +/// To use this class, dispatch the operations from DisplayList to a concrete +/// DlOpSpy object, and check the result of `did_draw` method. +/// +/// ``` +/// DlOpSpy dl_op_spy; +/// display_list.Dispatch(dl_op_spy); +/// bool did_draw = dl_op_spy.did_draw() +/// ``` +/// +class DlOpSpy final : public virtual DlOpReceiver, + private IgnoreAttributeDispatchHelper, + private IgnoreClipDispatchHelper, + private IgnoreTransformDispatchHelper { + public: + //---------------------------------------------------------------------------- + /// @brief Returns true if any non transparent content has been drawn. + bool did_draw(); + + private: + void setColor(DlColor color) override; + void setColorSource(const DlColorSource* source) override; + void save() override; + void saveLayer(const DlRect& bounds, + const SaveLayerOptions options, + const DlImageFilter* backdrop, + std::optional backdrop_id) override; + void restore() override; + void drawColor(DlColor color, DlBlendMode mode) override; + void drawPaint() override; + void drawLine(const DlPoint& p0, const DlPoint& p1) override; + void drawDashedLine(const DlPoint& p0, + const DlPoint& p1, + DlScalar on_length, + DlScalar off_length) override; + void drawRect(const DlRect& rect) override; + void drawOval(const DlRect& bounds) override; + void drawCircle(const DlPoint& center, DlScalar radius) override; + void drawRoundRect(const DlRoundRect& rrect) override; + void drawDiffRoundRect(const DlRoundRect& outer, + const DlRoundRect& inner) override; + void drawRoundSuperellipse(const DlRoundSuperellipse& rse) override; + void drawPath(const DlPath& path) override; + void drawArc(const DlRect& oval_bounds, + DlScalar start_degrees, + DlScalar sweep_degrees, + bool use_center) override; + void drawPoints(DlPointMode mode, + uint32_t count, + const DlPoint points[]) override; + void drawVertices(const std::shared_ptr& vertices, + DlBlendMode mode) override; + void drawImage(const sk_sp image, + const DlPoint& point, + DlImageSampling sampling, + bool render_with_attributes) override; + void drawImageRect( + const sk_sp image, + const DlRect& src, + const DlRect& dst, + DlImageSampling sampling, + bool render_with_attributes, + DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) override; + void drawImageNine(const sk_sp image, + const DlIRect& center, + const DlRect& dst, + DlFilterMode filter, + bool render_with_attributes) override; + void drawAtlas(const sk_sp atlas, + const DlRSTransform xform[], + const DlRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const DlRect* cull_rect, + bool render_with_attributes) override; + void drawDisplayList(const sk_sp display_list, + DlScalar opacity = SK_Scalar1) override; + void drawTextBlob(const sk_sp blob, + DlScalar x, + DlScalar y) override; + void drawTextFrame(const std::shared_ptr& text_frame, + DlScalar x, + DlScalar y) override; + void drawShadow(const DlPath& path, + const DlColor color, + const DlScalar elevation, + bool transparent_occluder, + DlScalar dpr) override; + + // Most recently set color, used when color_source goes to null + DlColor color_; + + // Indicates if the attributes are set to values that will modify the + // destination. For now, the test only checks if there is a non-transparent + // color set. + bool will_draw_ = true; + + bool did_draw_ = false; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_DL_OP_SPY_H_ diff --git a/flutter/engine/src/flutter/shell/common/dl_op_spy_unittests.cc b/flutter/engine/src/flutter/shell/common/dl_op_spy_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..a02dca2d1bcdf77a7c5361913a1e4c6ac955c15b --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/dl_op_spy_unittests.cc @@ -0,0 +1,588 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/display_list/display_list.h" +#include "flutter/display_list/dl_builder.h" +#include "flutter/display_list/testing/dl_test_snippets.h" +#include "flutter/shell/common/dl_op_spy.h" +#include "flutter/testing/testing.h" + +namespace flutter { +namespace testing { + +// The following macros demonstrate that the DlOpSpy class is equivalent +// to DisplayList::affects_transparent_surface() now that DisplayListBuilder +// implements operation culling. +// See https://github.com/flutter/flutter/issues/125403 +#define ASSERT_DID_DRAW(spy, dl) \ + do { \ + ASSERT_TRUE(spy.did_draw()); \ + ASSERT_TRUE(dl->modifies_transparent_black()); \ + } while (0) + +#define ASSERT_NO_DRAW(spy, dl) \ + do { \ + ASSERT_FALSE(spy.did_draw()); \ + ASSERT_FALSE(dl->modifies_transparent_black()); \ + } while (0) + +TEST(DlOpSpy, DidDrawIsFalseByDefault) { + DlOpSpy dl_op_spy; + ASSERT_FALSE(dl_op_spy.did_draw()); +} + +TEST(DlOpSpy, EmptyDisplayList) { + DisplayListBuilder builder; + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); +} + +TEST(DlOpSpy, SetColor) { + { // No Color set. + DisplayListBuilder builder; + DlPaint paint; + builder.DrawRect(DlRect::MakeWH(5, 5), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // Set transparent color. + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawRect(DlRect::MakeWH(5, 5), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } + { // Set black color. + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawRect(DlRect::MakeWH(5, 5), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, SetColorSource) { + { // Set null source + DisplayListBuilder builder; + DlPaint paint; + paint.setColorSource(nullptr); + builder.DrawRect(DlRect::MakeWH(5, 5), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // setColorSource(null) restores previous color visibility + DlOpSpy dl_op_spy; + DlOpReceiver* receiver = &dl_op_spy; + receiver->setColor(DlColor::kTransparent()); + receiver->drawRect(DlRect::MakeWH(5, 5)); + ASSERT_FALSE(dl_op_spy.did_draw()); + DlColor colors[2] = { + DlColor::kGreen(), + DlColor::kBlue(), + }; + float stops[2] = { + 0.0f, + 1.0f, + }; + auto color_source = DlColorSource::MakeLinear({0, 0}, {10, 10}, 2, colors, + stops, DlTileMode::kClamp); + receiver->setColorSource(color_source.get()); + receiver->setColorSource(nullptr); + receiver->drawRect(DlRect::MakeWH(5, 5)); + ASSERT_FALSE(dl_op_spy.did_draw()); + } +} + +TEST(DlOpSpy, DrawColor) { + { // Black color source. + DisplayListBuilder builder; + auto color = DlColor::kBlack(); + builder.DrawColor(color, DlBlendMode::kSrc); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // Transparent color with kSrc. + DisplayListBuilder builder; + auto color = DlColor::kTransparent(); + builder.DrawColor(color, DlBlendMode::kSrc); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } + { // Transparent color with kSrcOver. + DisplayListBuilder builder; + auto color = DlColor::kTransparent(); + builder.DrawColor(color, DlBlendMode::kSrcOver); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawPaint) { + { // Transparent color in paint. + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawPaint(paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } + { // black color in paint. + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawPaint(paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawLine) { + { // black + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawLine(DlPoint(0, 1), DlPoint(1, 2), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawLine(DlPoint(0, 1), DlPoint(1, 2), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawDashedLine) { + { // black + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawDashedLine(DlPoint(0, 1), DlPoint(1, 2), 1.0f, 1.0f, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawDashedLine(DlPoint(0, 1), DlPoint(1, 2), 1.0f, 1.0f, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawRect) { + { // black + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawRect(DlRect::MakeWH(5, 5), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawRect(DlRect::MakeWH(5, 5), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawOval) { + { // black + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawOval(DlRect::MakeWH(5, 5), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawOval(DlRect::MakeWH(5, 5), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawCircle) { + { // black + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawCircle(DlPoint(5, 5), 1.0, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawCircle(DlPoint(5, 5), 1.0, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawRRect) { + { // black + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawRoundRect(DlRoundRect::MakeRect(DlRect::MakeWH(5, 5)), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawRoundRect(DlRoundRect::MakeRect(DlRect::MakeWH(5, 5)), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawPath) { + { // black line + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + paint.setDrawStyle(DlDrawStyle::kStroke); + DlPathBuilder path_builder; + path_builder.MoveTo({0, 1}); + path_builder.LineTo({1, 1}); + builder.DrawPath(DlPath(path_builder), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // triangle + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + DlPathBuilder path_builder; + path_builder.MoveTo({0, 0}); + path_builder.LineTo({1, 0}); + path_builder.LineTo({0, 1}); + builder.DrawPath(DlPath(path_builder), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent line + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + paint.setDrawStyle(DlDrawStyle::kStroke); + DlPathBuilder path_builder; + path_builder.MoveTo({0, 1}); + path_builder.LineTo({1, 1}); + builder.DrawPath(DlPath(path_builder), paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawArc) { + { // black + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawArc(DlRect::MakeWH(5, 5), 0, 1, true, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawArc(DlRect::MakeWH(5, 5), 0, 1, true, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawPoints) { + { // black + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + const DlPoint points[] = {DlPoint(5, 4)}; + builder.DrawPoints(DlPointMode::kPoints, 1, points, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + const DlPoint points[] = {DlPoint(5, 4)}; + builder.DrawPoints(DlPointMode::kPoints, 1, points, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawVertices) { + { // black + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + const DlPoint vertices[] = { + DlPoint(5, 5), + DlPoint(5, 15), + DlPoint(15, 5), + }; + const DlPoint texture_coordinates[] = { + DlPoint(5, 5), + DlPoint(15, 5), + DlPoint(5, 15), + }; + const DlColor colors[] = { + DlColor::kBlack(), + DlColor::kRed(), + DlColor::kGreen(), + }; + auto dl_vertices = DlVertices::Make(DlVertexMode::kTriangles, 3, vertices, + texture_coordinates, colors, 0); + builder.DrawVertices(dl_vertices, DlBlendMode::kSrc, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + const DlPoint vertices[] = { + DlPoint(5, 5), + DlPoint(5, 15), + DlPoint(15, 5), + }; + const DlPoint texture_coordinates[] = { + DlPoint(5, 5), + DlPoint(15, 5), + DlPoint(5, 15), + }; + const DlColor colors[] = { + DlColor::kBlack(), + DlColor::kRed(), + DlColor::kGreen(), + }; + auto dl_vertices = DlVertices::Make(DlVertexMode::kTriangles, 3, vertices, + texture_coordinates, colors, 0); + builder.DrawVertices(dl_vertices, DlBlendMode::kSrc, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, Images) { + { // DrawImage + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawImage(kTestImage1, DlPoint(5, 5), DlImageSampling::kLinear); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // DrawImageRect + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawImageRect(kTestImage1, DlRect::MakeWH(5, 5), + DlRect::MakeWH(5, 5), DlImageSampling::kLinear); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // DrawImageNine + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawImageNine(kTestImage1, DlIRect::MakeWH(5, 5), + DlRect::MakeWH(5, 5), DlFilterMode::kLinear); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // DrawAtlas + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + const DlRSTransform xform[] = { + DlRSTransform::Make({0, 0}, 1.0f, DlDegrees(0)), + }; + const DlRect tex[] = {DlRect::MakeXYWH(10, 10, 10, 10)}; + DlRect cull_rect = DlRect::MakeWH(5, 5); + builder.DrawAtlas(kTestImage1, xform, tex, nullptr, 1, DlBlendMode::kSrc, + DlImageSampling::kLinear, &cull_rect); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawDisplayList) { + { // Recursive Transparent DisplayList + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawPaint(paint); + sk_sp dl = builder.Build(); + + DisplayListBuilder builder_parent; + DlPaint paint_parent(DlColor::kTransparent()); + builder_parent.DrawPaint(paint_parent); + builder_parent.DrawDisplayList(dl, 1); + sk_sp dl2 = builder_parent.Build(); + + DlOpSpy dl_op_spy; + dl2->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl2); + } + { // Sub non-transparent DisplayList, + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawPaint(paint); + sk_sp dl = builder.Build(); + + DisplayListBuilder builder_parent; + DlPaint paint_parent(DlColor::kTransparent()); + builder_parent.DrawPaint(paint_parent); + builder_parent.DrawDisplayList(dl, 1); + sk_sp dl2 = builder_parent.Build(); + + DlOpSpy dl_op_spy; + dl2->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl2); + } + + { // Sub non-transparent DisplayList, 0 opacity + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + builder.DrawPaint(paint); + sk_sp dl = builder.Build(); + + DisplayListBuilder builder_parent; + DlPaint paint_parent(DlColor::kTransparent()); + builder_parent.DrawPaint(paint_parent); + builder_parent.DrawDisplayList(dl, 0); + sk_sp dl2 = builder_parent.Build(); + + DlOpSpy dl_op_spy; + dl2->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl2); + } + + { // Parent non-transparent DisplayList + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + builder.DrawPaint(paint); + sk_sp dl = builder.Build(); + + DisplayListBuilder builder_parent; + DlPaint paint_parent(DlColor::kBlack()); + builder_parent.DrawPaint(paint_parent); + builder_parent.DrawDisplayList(dl, 0); + sk_sp dl2 = builder_parent.Build(); + + DlOpSpy dl_op_spy; + dl2->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl2); + } +} + +TEST(DlOpSpy, DrawTextBlob) { + { // Non-transparent color. + DisplayListBuilder builder; + DlPaint paint(DlColor::kBlack()); + std::string string = "xx"; + builder.DrawTextBlob(GetTestTextBlob(42), 1, 1, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent color. + DisplayListBuilder builder; + DlPaint paint(DlColor::kTransparent()); + std::string string = "xx"; + builder.DrawTextBlob(GetTestTextBlob(43), 1, 1, paint); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +TEST(DlOpSpy, DrawShadow) { + { // valid shadow + DisplayListBuilder builder; + DlPaint paint; + DlColor color = DlColor::kBlack(); + builder.DrawShadow(kTestPath1, color, 1, false, 1); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_DID_DRAW(dl_op_spy, dl); + } + { // transparent color + DisplayListBuilder builder; + DlPaint paint; + DlColor color = DlColor::kTransparent(); + builder.DrawShadow(kTestPath1, color, 1, false, 1); + sk_sp dl = builder.Build(); + DlOpSpy dl_op_spy; + dl->Dispatch(dl_op_spy); + ASSERT_NO_DRAW(dl_op_spy, dl); + } +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/engine.cc b/flutter/engine/src/flutter/shell/common/engine.cc new file mode 100644 index 0000000000000000000000000000000000000000..56e894335aa37ef7982bcc9972f77f22486157f9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/engine.cc @@ -0,0 +1,646 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/engine.h" + +#include +#include +#include +#include +#include + +#include "flutter/assets/native_assets.h" +#include "flutter/common/settings.h" +#include "flutter/fml/trace_event.h" +#include "flutter/lib/ui/text/font_collection.h" +#include "flutter/shell/common/animator.h" +#include "rapidjson/document.h" + +namespace flutter { + +static constexpr char kAssetChannel[] = "flutter/assets"; +static constexpr char kLifecycleChannel[] = "flutter/lifecycle"; +static constexpr char kNavigationChannel[] = "flutter/navigation"; +static constexpr char kLocalizationChannel[] = "flutter/localization"; +static constexpr char kSettingsChannel[] = "flutter/settings"; +static constexpr char kIsolateChannel[] = "flutter/isolate"; + +namespace { +fml::MallocMapping MakeMapping(const std::string& str) { + return fml::MallocMapping::Copy(str.c_str(), str.length()); +} +} // namespace + +Engine::Engine( + Delegate& delegate, + const PointerDataDispatcherMaker& dispatcher_maker, + const std::shared_ptr& image_decoder_task_runner, + const TaskRunners& task_runners, + const Settings& settings, + std::unique_ptr animator, + const fml::WeakPtr& io_manager, + const std::shared_ptr& font_collection, + std::unique_ptr runtime_controller, + const std::shared_ptr& gpu_disabled_switch) + : delegate_(delegate), + settings_(settings), + animator_(std::move(animator)), + runtime_controller_(std::move(runtime_controller)), + font_collection_(font_collection), + image_decoder_(ImageDecoder::Make(settings_, + task_runners, + image_decoder_task_runner, + io_manager, + gpu_disabled_switch)), + task_runners_(task_runners), + weak_factory_(this) { + pointer_data_dispatcher_ = dispatcher_maker(*this); +} + +Engine::Engine(Delegate& delegate, + const PointerDataDispatcherMaker& dispatcher_maker, + DartVM& vm, + fml::RefPtr isolate_snapshot, + const TaskRunners& task_runners, + const PlatformData& platform_data, + const Settings& settings, + std::unique_ptr animator, + fml::WeakPtr io_manager, + const fml::RefPtr& unref_queue, + fml::TaskRunnerAffineWeakPtr snapshot_delegate, + const std::shared_ptr& gpu_disabled_switch, + impeller::RuntimeStageBackend runtime_stage_type) + : Engine(delegate, + dispatcher_maker, + vm.GetConcurrentWorkerTaskRunner(), + task_runners, + settings, + std::move(animator), + io_manager, + std::make_shared(), + nullptr, + gpu_disabled_switch) { + runtime_controller_ = std::make_unique( + *this, // runtime delegate + &vm, // VM + std::move(isolate_snapshot), // isolate snapshot + settings_.idle_notification_callback, // idle notification callback + platform_data, // platform data + settings_.isolate_create_callback, // isolate create callback + settings_.isolate_shutdown_callback, // isolate shutdown callback + settings_.persistent_isolate_data, // persistent isolate data + UIDartState::Context{ + task_runners_, // task runners + std::move(snapshot_delegate), // snapshot delegate + std::move(io_manager), // io manager + unref_queue, // Skia unref queue + image_decoder_->GetWeakPtr(), // image decoder + image_generator_registry_.GetWeakPtr(), // image generator registry + settings_.advisory_script_uri, // advisory script uri + settings_.advisory_script_entrypoint, // advisory script entrypoint + settings_ + .skia_deterministic_rendering_on_cpu, // deterministic rendering + vm.GetConcurrentWorkerTaskRunner(), // concurrent task runner + settings_.enable_impeller, // enable impeller + runtime_stage_type, // runtime stage type + }); +} + +std::unique_ptr Engine::Spawn( + Delegate& delegate, + const PointerDataDispatcherMaker& dispatcher_maker, + const Settings& settings, + std::unique_ptr animator, + const std::string& initial_route, + const fml::WeakPtr& io_manager, + fml::TaskRunnerAffineWeakPtr snapshot_delegate, + const std::shared_ptr& gpu_disabled_switch) const { + auto result = std::make_unique( + /*delegate=*/delegate, + /*dispatcher_maker=*/dispatcher_maker, + /*image_decoder_task_runner=*/ + runtime_controller_->GetDartVM()->GetConcurrentWorkerTaskRunner(), + /*task_runners=*/task_runners_, + /*settings=*/settings, + /*animator=*/std::move(animator), + /*io_manager=*/io_manager, + /*font_collection=*/font_collection_, + /*runtime_controller=*/nullptr, + /*gpu_disabled_switch=*/gpu_disabled_switch); + result->runtime_controller_ = runtime_controller_->Spawn( + /*p_client=*/*result, + /*advisory_script_uri=*/settings.advisory_script_uri, + /*advisory_script_entrypoint=*/settings.advisory_script_entrypoint, + /*idle_notification_callback=*/settings.idle_notification_callback, + /*isolate_create_callback=*/settings.isolate_create_callback, + /*isolate_shutdown_callback=*/settings.isolate_shutdown_callback, + /*persistent_isolate_data=*/settings.persistent_isolate_data, + /*io_manager=*/io_manager, + /*image_decoder=*/result->GetImageDecoderWeakPtr(), + /*image_generator_registry=*/result->GetImageGeneratorRegistry(), + /*snapshot_delegate=*/std::move(snapshot_delegate)); + result->initial_route_ = initial_route; + result->asset_manager_ = asset_manager_; + return result; +} + +Engine::~Engine() = default; + +fml::WeakPtr Engine::GetWeakPtr() const { + return weak_factory_.GetWeakPtr(); +} + +void Engine::SetupDefaultFontManager() { + TRACE_EVENT0("flutter", "Engine::SetupDefaultFontManager"); + font_collection_->SetupDefaultFontManager(settings_.font_initialization_data); +} + +std::shared_ptr Engine::GetAssetManager() { + return asset_manager_; +} + +fml::WeakPtr Engine::GetImageDecoderWeakPtr() { + return image_decoder_->GetWeakPtr(); +} + +fml::WeakPtr Engine::GetImageGeneratorRegistry() { + return image_generator_registry_.GetWeakPtr(); +} + +bool Engine::UpdateAssetManager( + const std::shared_ptr& new_asset_manager) { + if (asset_manager_ && new_asset_manager && + *asset_manager_ == *new_asset_manager) { + return false; + } + + asset_manager_ = new_asset_manager; + + if (!asset_manager_) { + return false; + } + + // Using libTXT as the text engine. + if (settings_.use_asset_fonts) { + font_collection_->RegisterFonts(asset_manager_); + } + + if (settings_.use_test_fonts) { + font_collection_->RegisterTestFonts(); + } + + if (native_assets_manager_ == nullptr) { + native_assets_manager_ = std::make_shared(); + } + native_assets_manager_->RegisterNativeAssets(asset_manager_); + + return true; +} + +bool Engine::Restart(RunConfiguration configuration) { + TRACE_EVENT0("flutter", "Engine::Restart"); + if (!configuration.IsValid()) { + FML_LOG(ERROR) << "Engine run configuration was invalid."; + return false; + } + delegate_.OnPreEngineRestart(); + runtime_controller_ = runtime_controller_->Clone(); + UpdateAssetManager(nullptr); + return Run(std::move(configuration)) == Engine::RunStatus::Success; +} + +Engine::RunStatus Engine::Run(RunConfiguration configuration) { + if (!configuration.IsValid()) { + FML_LOG(ERROR) << "Engine run configuration was invalid."; + return RunStatus::Failure; + } + + last_entry_point_ = configuration.GetEntrypoint(); + last_entry_point_library_ = configuration.GetEntrypointLibrary(); +#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) + // This is only used to support restart. + last_entry_point_args_ = configuration.GetEntrypointArgs(); +#endif + + UpdateAssetManager(configuration.GetAssetManager()); + + if (runtime_controller_->IsRootIsolateRunning()) { + return RunStatus::FailureAlreadyRunning; + } + + // If the embedding prefetched the default font manager, then set up the + // font manager later in the engine launch process. This makes it less + // likely that the setup will need to wait for the prefetch to complete. + auto root_isolate_create_callback = [&]() { + if (settings_.prefetched_default_font_manager) { + SetupDefaultFontManager(); + } + }; + + if (!runtime_controller_->LaunchRootIsolate( + settings_, // + root_isolate_create_callback, // + configuration.GetEntrypoint(), // + configuration.GetEntrypointLibrary(), // + configuration.GetEntrypointArgs(), // + configuration.TakeIsolateConfiguration(), // + native_assets_manager_, // + configuration.GetEngineId())) // + { + return RunStatus::Failure; + } + + auto service_id = runtime_controller_->GetRootIsolateServiceID(); + if (service_id.has_value()) { + std::unique_ptr service_id_message = + std::make_unique( + kIsolateChannel, MakeMapping(service_id.value()), nullptr); + HandlePlatformMessage(std::move(service_id_message)); + } + + return Engine::RunStatus::Success; +} + +void Engine::BeginFrame(fml::TimePoint frame_time, uint64_t frame_number) { + runtime_controller_->BeginFrame(frame_time, frame_number); +} + +void Engine::ReportTimings(std::vector timings) { + runtime_controller_->ReportTimings(std::move(timings)); +} + +void Engine::NotifyIdle(fml::TimeDelta deadline) { + runtime_controller_->NotifyIdle(deadline); +} + +void Engine::NotifyDestroyed() { + TRACE_EVENT0("flutter", "Engine::NotifyDestroyed"); + runtime_controller_->NotifyDestroyed(); +} + +std::optional Engine::GetUIIsolateReturnCode() { + return runtime_controller_->GetRootIsolateReturnCode(); +} + +Dart_Port Engine::GetUIIsolateMainPort() { + return runtime_controller_->GetMainPort(); +} + +std::string Engine::GetUIIsolateName() { + return runtime_controller_->GetIsolateName(); +} + +bool Engine::UIIsolateHasLivePorts() { + return runtime_controller_->HasLivePorts(); +} + +bool Engine::UIIsolateHasPendingMicrotasks() { + return runtime_controller_->HasPendingMicrotasks(); +} + +tonic::DartErrorHandleType Engine::GetUIIsolateLastError() { + return runtime_controller_->GetLastError(); +} + +void Engine::AddView(int64_t view_id, + const ViewportMetrics& view_metrics, + std::function callback) { + runtime_controller_->AddView(view_id, view_metrics, std::move(callback)); +} + +bool Engine::RemoveView(int64_t view_id) { + return runtime_controller_->RemoveView(view_id); +} + +bool Engine::SendViewFocusEvent(const ViewFocusEvent& event) { + return runtime_controller_->SendViewFocusEvent(event); +} + +void Engine::SetViewportMetrics(int64_t view_id, + const ViewportMetrics& metrics) { + runtime_controller_->SetViewportMetrics(view_id, metrics); + ScheduleFrame(); +} + +void Engine::DispatchPlatformMessage(std::unique_ptr message) { + std::string channel = message->channel(); + if (channel == kLifecycleChannel) { + if (HandleLifecyclePlatformMessage(message.get())) { + return; + } + } else if (channel == kLocalizationChannel) { + if (HandleLocalizationPlatformMessage(message.get())) { + return; + } + } else if (channel == kSettingsChannel) { + HandleSettingsPlatformMessage(message.get()); + return; + } else if (!runtime_controller_->IsRootIsolateRunning() && + channel == kNavigationChannel) { + // If there's no runtime_, we may still need to set the initial route. + HandleNavigationPlatformMessage(std::move(message)); + return; + } + + if (runtime_controller_->IsRootIsolateRunning() && + runtime_controller_->DispatchPlatformMessage(std::move(message))) { + return; + } + + FML_DLOG(WARNING) << "Dropping platform message on channel: " << channel; +} + +bool Engine::HandleLifecyclePlatformMessage(PlatformMessage* message) { + const auto& data = message->data(); + std::string state(reinterpret_cast(data.GetMapping()), + data.GetSize()); + + // Always schedule a frame when the app does become active as per API + // recommendation + // https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive?language=objc + if (state == "AppLifecycleState.resumed" || + state == "AppLifecycleState.inactive") { + ScheduleFrame(); + } + runtime_controller_->SetInitialLifecycleState(state); + // Always forward these messages to the framework by returning false. + return false; +} + +bool Engine::HandleNavigationPlatformMessage( + std::unique_ptr message) { + const auto& data = message->data(); + + rapidjson::Document document; + document.Parse(reinterpret_cast(data.GetMapping()), + data.GetSize()); + if (document.HasParseError() || !document.IsObject()) { + return false; + } + auto root = document.GetObject(); + auto method = root.FindMember("method"); + if (method->value != "setInitialRoute") { + return false; + } + auto route = root.FindMember("args"); + initial_route_ = route->value.GetString(); + return true; +} + +bool Engine::HandleLocalizationPlatformMessage(PlatformMessage* message) { + const auto& data = message->data(); + + rapidjson::Document document; + document.Parse(reinterpret_cast(data.GetMapping()), + data.GetSize()); + if (document.HasParseError() || !document.IsObject()) { + return false; + } + auto root = document.GetObject(); + auto method = root.FindMember("method"); + if (method == root.MemberEnd()) { + return false; + } + const size_t strings_per_locale = 4; + if (method->value == "setLocale") { + // Decode and pass the list of locale data onwards to dart. + auto args = root.FindMember("args"); + if (args == root.MemberEnd() || !args->value.IsArray()) { + return false; + } + + if (args->value.Size() % strings_per_locale != 0) { + return false; + } + std::vector locale_data; + for (size_t locale_index = 0; locale_index < args->value.Size(); + locale_index += strings_per_locale) { + if (!args->value[locale_index].IsString() || + !args->value[locale_index + 1].IsString()) { + return false; + } + locale_data.push_back(args->value[locale_index].GetString()); + locale_data.push_back(args->value[locale_index + 1].GetString()); + locale_data.push_back(args->value[locale_index + 2].GetString()); + locale_data.push_back(args->value[locale_index + 3].GetString()); + } + + return runtime_controller_->SetLocales(locale_data); + } + return false; +} + +void Engine::HandleSettingsPlatformMessage(PlatformMessage* message) { + const auto& data = message->data(); + std::string jsonData(reinterpret_cast(data.GetMapping()), + data.GetSize()); + if (runtime_controller_->SetUserSettingsData(jsonData)) { + ScheduleFrame(); + } +} + +void Engine::DispatchPointerDataPacket( + std::unique_ptr packet, + uint64_t trace_flow_id) { + TRACE_EVENT0_WITH_FLOW_IDS("flutter", "Engine::DispatchPointerDataPacket", + /*flow_id_count=*/1, + /*flow_ids=*/&trace_flow_id); + TRACE_FLOW_STEP("flutter", "PointerEvent", trace_flow_id); + pointer_data_dispatcher_->DispatchPacket(std::move(packet), trace_flow_id); +} + +void Engine::DispatchSemanticsAction(int64_t view_id, + int node_id, + SemanticsAction action, + fml::MallocMapping args) { + runtime_controller_->DispatchSemanticsAction(view_id, node_id, action, + std::move(args)); +} + +void Engine::SetSemanticsEnabled(bool enabled) { + runtime_controller_->SetSemanticsEnabled(enabled); +} + +void Engine::SetAccessibilityFeatures(int32_t flags) { + runtime_controller_->SetAccessibilityFeatures(flags); +} + +std::string Engine::DefaultRouteName() { + if (!initial_route_.empty()) { + return initial_route_; + } + return "/"; +} + +void Engine::ScheduleFrame(bool regenerate_layer_trees) { + animator_->RequestFrame(regenerate_layer_trees); +} + +void Engine::OnAllViewsRendered() { + animator_->OnAllViewsRendered(); +} + +void Engine::Render(int64_t view_id, + std::unique_ptr layer_tree, + float device_pixel_ratio) { + if (!layer_tree) { + return; + } + + // Ensure frame dimensions are sane. + if (layer_tree->frame_size().IsEmpty() || device_pixel_ratio <= 0.0f) { + return; + } + + animator_->Render(view_id, std::move(layer_tree), device_pixel_ratio); +} + +void Engine::UpdateSemantics(int64_t view_id, + SemanticsNodeUpdates update, + CustomAccessibilityActionUpdates actions) { + delegate_.OnEngineUpdateSemantics(view_id, std::move(update), + std::move(actions)); +} + +void Engine::HandlePlatformMessage(std::unique_ptr message) { + if (message->channel() == kAssetChannel) { + HandleAssetPlatformMessage(std::move(message)); + } else { + delegate_.OnEngineHandlePlatformMessage(std::move(message)); + } +} + +void Engine::OnRootIsolateCreated() { + delegate_.OnRootIsolateCreated(); +} + +void Engine::UpdateIsolateDescription(const std::string isolate_name, + int64_t isolate_port) { + delegate_.UpdateIsolateDescription(isolate_name, isolate_port); +} + +std::unique_ptr> Engine::ComputePlatformResolvedLocale( + const std::vector& supported_locale_data) { + return delegate_.ComputePlatformResolvedLocale(supported_locale_data); +} + +double Engine::GetScaledFontSize(double unscaled_font_size, + int configuration_id) const { + return delegate_.GetScaledFontSize(unscaled_font_size, configuration_id); +} + +void Engine::RequestViewFocusChange(const ViewFocusChangeRequest& request) { + delegate_.RequestViewFocusChange(request); +} + +void Engine::SetNeedsReportTimings(bool needs_reporting) { + delegate_.SetNeedsReportTimings(needs_reporting); +} + +FontCollection& Engine::GetFontCollection() { + return *font_collection_; +} + +void Engine::DoDispatchPacket(std::unique_ptr packet, + uint64_t trace_flow_id) { + animator_->EnqueueTraceFlowId(trace_flow_id); + if (runtime_controller_) { + runtime_controller_->DispatchPointerDataPacket(*packet); + } +} + +void Engine::ScheduleSecondaryVsyncCallback(uintptr_t id, + const fml::closure& callback) { + animator_->ScheduleSecondaryVsyncCallback(id, callback); +} + +void Engine::HandleAssetPlatformMessage( + std::unique_ptr message) { + fml::RefPtr response = message->response(); + if (!response) { + return; + } + const auto& data = message->data(); + std::string asset_name(reinterpret_cast(data.GetMapping()), + data.GetSize()); + + if (asset_manager_) { + std::unique_ptr asset_mapping = + asset_manager_->GetAsMapping(asset_name); + if (asset_mapping) { + response->Complete(std::move(asset_mapping)); + return; + } + } + + response->CompleteEmpty(); +} + +const std::string& Engine::GetLastEntrypoint() const { + return last_entry_point_; +} + +const std::string& Engine::GetLastEntrypointLibrary() const { + return last_entry_point_library_; +} + +const std::vector& Engine::GetLastEntrypointArgs() const { + return last_entry_point_args_; +} + +// |RuntimeDelegate| +void Engine::RequestDartDeferredLibrary(intptr_t loading_unit_id) { + return delegate_.RequestDartDeferredLibrary(loading_unit_id); +} + +std::weak_ptr Engine::GetPlatformMessageHandler() + const { + return delegate_.GetPlatformMessageHandler(); +} + +void Engine::SendChannelUpdate(std::string name, bool listening) { + delegate_.OnEngineChannelUpdate(std::move(name), listening); +} + +void Engine::LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) { + if (runtime_controller_->IsRootIsolateRunning()) { + runtime_controller_->LoadDartDeferredLibrary( + loading_unit_id, std::move(snapshot_data), + std::move(snapshot_instructions)); + } else { + LoadDartDeferredLibraryError(loading_unit_id, "No running root isolate.", + true); + } +} + +void Engine::LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string& error_message, + bool transient) { + if (runtime_controller_->IsRootIsolateRunning()) { + runtime_controller_->LoadDartDeferredLibraryError(loading_unit_id, + error_message, transient); + } +} + +const std::weak_ptr Engine::GetVsyncWaiter() const { + return animator_->GetVsyncWaiter(); +} + +void Engine::SetDisplays(const std::vector& displays) { + runtime_controller_->SetDisplays(displays); + ScheduleFrame(); +} + +void Engine::ShutdownPlatformIsolates() { + runtime_controller_->ShutdownPlatformIsolates(); +} + +void Engine::FlushMicrotaskQueue() { + runtime_controller_->FlushMicrotaskQueue(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/engine.h b/flutter/engine/src/flutter/shell/common/engine.h new file mode 100644 index 0000000000000000000000000000000000000000..8d911741931ad876bc39e0889ddb6dafb8998361 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/engine.h @@ -0,0 +1,1093 @@ +// 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_COMMON_ENGINE_H_ +#define FLUTTER_SHELL_COMMON_ENGINE_H_ + +#include +#include + +#include "flutter/assets/asset_manager.h" +#include "flutter/common/task_runners.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/lib/ui/painting/image_decoder.h" +#include "flutter/lib/ui/painting/image_generator_registry.h" +#include "flutter/lib/ui/semantics/custom_accessibility_action.h" +#include "flutter/lib/ui/semantics/semantics_node.h" +#include "flutter/lib/ui/snapshot_delegate.h" +#include "flutter/lib/ui/text/font_collection.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/lib/ui/window/viewport_metrics.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/runtime/runtime_controller.h" +#include "flutter/runtime/runtime_delegate.h" +#include "flutter/shell/common/animator.h" +#include "flutter/shell/common/pointer_data_dispatcher.h" +#include "flutter/shell/common/run_configuration.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// The engine is a component owned by the shell that resides on the UI task +/// runner and is responsible for managing the needs of the root isolate and its +/// runtime. The engine can only be created, accessed and collected on the UI +/// task runner. Each shell owns exactly one instance of the engine. +/// +/// The root isolate of Flutter application gets "window" bindings. Using these +/// bindings, the application can schedule frames, post layer-trees for +/// rendering, ask to decompress images and upload them to the GPU, etc.. +/// Non-root isolates of the VM do not get any of these capabilities and are run +/// in a VM managed thread pool (so if they did have "window", the threading +/// guarantees needed for engine operation would be violated). +/// +/// The engine is responsible for the entire life-cycle of the root isolate. +/// When the engine is collected, its owner assumes that the root isolate has +/// been shutdown and appropriate resources collected. While each engine +/// instance can only manage a single instance of a root isolate, it may restart +/// that isolate on request. This is how the cold-restart development scenario +/// is supported. +/// +/// When the engine instance is initially created, the root isolate is created +/// but it is not in the |DartIsolate::Phase::Running| phase yet. It only moves +/// into that phase when a successful call to `Engine::Run` is made. +/// +/// @see `Shell` +/// +/// @note This name of this class is perhaps a bit unfortunate and has +/// sometimes been the cause of confusion. For a class named "Engine" +/// in the Flutter "Engine" repository, its responsibilities are +/// decidedly unremarkable. But, it does happen to be the primary +/// entry-point used by components higher up in the Flutter tech stack +/// (usually in Dart code) to peer into the lower level functionality. +/// Besides, the authors haven't been able to come up with a more apt +/// name and it does happen to be one of the older classes in the +/// repository. +/// +class Engine final : public RuntimeDelegate, PointerDataDispatcher::Delegate { + public: + //---------------------------------------------------------------------------- + /// @brief Indicates the result of the call to `Engine::Run`. + /// + enum class RunStatus { + // NOLINTBEGIN(readability-identifier-naming) + //-------------------------------------------------------------------------- + /// The call to |Engine::Run| was successful and the root isolate is in the + /// `DartIsolate::Phase::Running` phase with its entry-point invocation + /// already pending in the task queue. + /// + Success, + + //-------------------------------------------------------------------------- + /// The engine can only manage a single instance of a root isolate. If a + /// previous call to run the root isolate was successful, subsequent calls + /// to run the isolate (even if the new run configuration is different) will + /// be rejected. + /// + /// It is up to the caller to decide to re-purpose the running isolate, + /// terminate it, or use another shell to host the new isolate. This is + /// mostly used by embedders which have a fire-and-forget strategy to root + /// isolate launch. For example, the application may try to "launch" an + /// isolate when the embedders launches or resumes from a paused state. That + /// the isolate is running is not necessarily a failure condition for them. + /// But from the engine's perspective, the run configuration was rejected. + /// + FailureAlreadyRunning, + + //-------------------------------------------------------------------------- + /// Used to indicate to the embedder that a root isolate was not already + /// running but the run configuration was not valid and root isolate could + /// not be moved into the `DartIsolate::Phase::Running` phase. + /// + /// The caller must attempt the run call again with a valid configuration. + /// The set of all failure modes is massive and can originate from a variety + /// of sub-components. The engine will attempt to log the same when + /// possible. With the aid of logs, the common causes of failure are: + /// + /// * AOT assets were given to JIT/DBC mode VM's and vice-versa. + /// * The assets could not be found in the asset manager. Callers must make + /// sure their run configuration asset managers have been correctly set + /// up. + /// * The assets themselves were corrupt or invalid. Callers must make sure + /// their asset delivery mechanisms are sound. + /// * The application entry-point or the root library of the entry-point + /// specified in the run configuration was invalid. Callers must make sure + /// that the entry-point is present in the application. If the name of the + /// entrypoint is not "main" in the root library, callers must also ensure + /// that the snapshotting process has not tree-shaken away this + /// entrypoint. This requires the decoration of the entrypoint with the + /// `@pragma('vm:entry-point')` directive. This problem will manifest in + /// AOT mode operation of the Dart VM. + /// + Failure, + // NOLINTEND(readability-identifier-naming) + }; + + //---------------------------------------------------------------------------- + /// @brief While the engine operates entirely on the UI task runner, it + /// needs the capabilities of the other components to fulfill the + /// requirements of the root isolate. The shell is the only class + /// that implements this interface as no other component has + /// access to all components in a thread safe manner. The engine + /// delegates these tasks to the shell via this interface. + /// + class Delegate { + public: + //-------------------------------------------------------------------------- + /// @brief When the accessibility tree has been updated by the Flutter + /// application, this new information needs to be conveyed to + /// the underlying platform. The engine delegates this task to + /// the shell via this call. The engine cannot access the + /// underlying platform directly because of threading + /// considerations. Most platform specific APIs to convey + /// accessibility information are only safe to access on the + /// platform task runner while the engine is running on the UI + /// task runner. + /// + /// @see `SemanticsNode`, `SemanticsNodeUpdates`, + /// `CustomAccessibilityActionUpdates`, + /// `PlatformView::UpdateSemantics` + /// + /// @param[in] view_id The ID of the view that this update is for + /// @param[in] updates A map with the stable semantics node identifier as + /// key and the node properties as the value. + /// @param[in] actions A map with the stable semantics node identifier as + /// key and the custom node action as the value. + /// + virtual void OnEngineUpdateSemantics( + int64_t view_id, + SemanticsNodeUpdates updates, + CustomAccessibilityActionUpdates actions) = 0; + + //-------------------------------------------------------------------------- + /// @brief When the Flutter application has a message to send to the + /// underlying platform, the message needs to be forwarded to + /// the platform on the appropriate thread (via the platform + /// task runner). The engine delegates this task to the shell + /// via this method. + /// + /// @see `PlatformView::HandlePlatformMessage` + /// + /// @param[in] message The message from the Flutter application to send to + /// the underlying platform. + /// + virtual void OnEngineHandlePlatformMessage( + std::unique_ptr message) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the root isolate of the + /// application is about to be discarded and a new isolate with + /// the same runtime started in its place. This should only + /// happen in the Flutter "debug" runtime mode in the + /// cold-restart scenario. The embedder may need to reset native + /// resource in response to the restart. + /// + /// @see `PlatformView::OnPreEngineRestart` + /// + virtual void OnPreEngineRestart() = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the shell that the root isolate is created. + /// Currently, this information is to add to the service + /// protocol list of available root isolates running in the VM + /// and their names so that the appropriate isolate can be + /// selected in the tools for debugging and instrumentation. + /// + virtual void OnRootIsolateCreated() = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the shell of the name of the root isolate and its + /// port when that isolate is launched, restarted (in the + /// cold-restart scenario) or the application itself updates the + /// name of the root isolate (via + /// `PlatformDispatcher.setIsolateDebugName` in + /// `platform_dispatcher.dart`). The name of the isolate is + /// meaningless to the engine but is used in instrumentation and + /// tooling. Currently, this information is to update the + /// service protocol list of available root isolates running in + /// the VM and their names so that the appropriate isolate can + /// be selected in the tools for debugging and instrumentation. + /// + /// @param[in] isolate_name The isolate name + /// @param[in] isolate_port The isolate port + /// + virtual void UpdateIsolateDescription(const std::string isolate_name, + int64_t isolate_port) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the shell that the application has an opinion about + /// whether its frame timings need to be reported backed to it. + /// Due to the asynchronous nature of rendering in Flutter, it + /// is not possible for the application to determine the total + /// time it took to render a specific frame. While the + /// layer-tree is constructed on the UI thread, it needs to be + /// rendering on the raster thread. Dart code cannot execute on + /// this thread. So any instrumentation about the frame times + /// gathered on this thread needs to be aggregated and sent back + /// to the UI thread for processing in Dart. + /// + /// When the application indicates that frame times need to be + /// reported, it collects this information till a specified + /// number of data points are gathered. Then this information is + /// sent back to Dart code via `Engine::ReportTimings`. + /// + /// This option is engine counterpart of the + /// `Window._setNeedsReportTimings` in `window.dart`. + /// + /// @param[in] needs_reporting If reporting information should be + /// collected and send back to Dart. + /// + virtual void SetNeedsReportTimings(bool needs_reporting) = 0; + + //-------------------------------------------------------------------------- + /// @brief Directly invokes platform-specific APIs to compute the + /// locale the platform would have natively resolved to. + /// + /// @param[in] supported_locale_data The vector of strings that represents + /// the locales supported by the app. + /// Each locale consists of three + /// strings: languageCode, countryCode, + /// and scriptCode in that order. + /// + /// @return A vector of 3 strings languageCode, countryCode, and + /// scriptCode that represents the locale selected by the + /// platform. Empty strings mean the value was unassigned. Empty + /// vector represents a null locale. + /// + virtual std::unique_ptr> + ComputePlatformResolvedLocale( + const std::vector& supported_locale_data) = 0; + + //-------------------------------------------------------------------------- + /// @brief Invoked when the Dart VM requests that a deferred library + /// be loaded. Notifies the engine that the deferred library + /// identified by the specified loading unit id should be + /// downloaded and loaded into the Dart VM via + /// `LoadDartDeferredLibrary` + /// + /// Upon encountering errors or otherwise failing to load a + /// loading unit with the specified id, the failure should be + /// directly reported to dart by calling + /// `LoadDartDeferredLibraryFailure` to ensure the waiting dart + /// future completes with an error. + /// + /// @param[in] loading_unit_id The unique id of the deferred library's + /// loading unit. This id is to be passed + /// back into LoadDartDeferredLibrary + /// in order to identify which deferred + /// library to load. + /// + virtual void RequestDartDeferredLibrary(intptr_t loading_unit_id) = 0; + + //-------------------------------------------------------------------------- + /// @brief Returns the current fml::TimePoint. + /// This method is primarily provided to allow tests to control + /// Any methods that rely on advancing the clock. + virtual fml::TimePoint GetCurrentTimePoint() = 0; + + //---------------------------------------------------------------------------- + /// @brief Returns the delegate object that handles PlatformMessage's from + /// Flutter to the host platform (and its responses). + virtual const std::shared_ptr& + GetPlatformMessageHandler() const = 0; + + //-------------------------------------------------------------------------- + /// @brief Invoked when a listener is registered on a platform channel. + /// + /// @param[in] name The name of the platform channel to which a + /// listener has been registered or cleared. + /// + /// @param[in] listening Whether the listener has been set (true) or + /// cleared (false). + /// + virtual void OnEngineChannelUpdate(std::string name, bool listening) = 0; + + //-------------------------------------------------------------------------- + /// @brief Synchronously invokes platform-specific APIs to apply the + /// system text scaling on the given unscaled font size. + /// + /// Platforms that support this feature (currently it's only + /// implemented for Android SDK level 34+) will send a valid + /// configuration_id to potential callers, before this method + /// can be called. + /// + /// @param[in] unscaled_font_size The unscaled font size specified by the + /// app developer. The value is in logical + /// pixels, and is guaranteed to be finite + /// and non-negative. + /// @param[in] configuration_id The unique id of the configuration to + /// use for computing the scaled font size. + /// + /// @return The scaled font size in logical pixels, or -1 when the given + /// configuration_id did not match a valid configuration. + /// + virtual double GetScaledFontSize(double unscaled_font_size, + int configuration_id) const = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the client that the Flutter view focus state has + /// changed and the platform view should be updated. + /// + /// @param[in] request The request to change the focus state of the view. + virtual void RequestViewFocusChange( + const ViewFocusChangeRequest& request) = 0; + }; + + //---------------------------------------------------------------------------- + /// @brief Creates an instance of the engine with a supplied + /// `RuntimeController`. Use the other constructor except for + /// tests. + /// + Engine(Delegate& delegate, + const PointerDataDispatcherMaker& dispatcher_maker, + const std::shared_ptr& + image_decoder_task_runner, + const TaskRunners& task_runners, + const Settings& settings, + std::unique_ptr animator, + const fml::WeakPtr& io_manager, + const std::shared_ptr& font_collection, + std::unique_ptr runtime_controller, + const std::shared_ptr& gpu_disabled_switch); + + //---------------------------------------------------------------------------- + /// @brief Creates an instance of the engine. This is done by the Shell + /// on the UI task runner. + /// + /// @param delegate The object used by the engine to perform + /// tasks that require access to components + /// that cannot be safely accessed by the + /// engine. This is the shell. + /// @param dispatcher_maker The callback provided by `PlatformView` for + /// engine to create the pointer data + /// dispatcher. Similar to other engine + /// resources, this dispatcher_maker and its + /// returned dispatcher is only safe to be + /// called from the UI thread. + /// @param vm An instance of the running Dart VM. + /// @param[in] isolate_snapshot The snapshot used to create the root + /// isolate. Even though the isolate is not + /// `DartIsolate::Phase::Running` phase, it is + /// created when the engine is created. This + /// requires access to the isolate snapshot + /// upfront. + // TODO(chinmaygarde): This is probably redundant now that the IO manager is + // it's own object. + /// @param[in] task_runners The task runners used by the shell that + /// hosts this engine. + /// @param[in] settings The settings used to initialize the shell + /// and the engine. + /// @param[in] animator The animator used to schedule frames. + // TODO(chinmaygarde): Move this to `Engine::Delegate` + /// @param[in] snapshot_delegate The delegate used to fulfill requests to + /// snapshot a specified scene. The engine + /// cannot snapshot a scene on the UI thread + /// directly because the scene (described via + /// a `DisplayList`) may reference resources on + /// the GPU and there is no GPU context current + /// on the UI thread. The delegate is a + /// component that has access to all the + /// requisite GPU resources. + /// @param[in] io_manager The IO manager used by this root isolate to + /// schedule tasks that manage resources on the + /// GPU. + /// + Engine(Delegate& delegate, + const PointerDataDispatcherMaker& dispatcher_maker, + DartVM& vm, + fml::RefPtr isolate_snapshot, + const TaskRunners& task_runners, + const PlatformData& platform_data, + const Settings& settings, + std::unique_ptr animator, + fml::WeakPtr io_manager, + const fml::RefPtr& unref_queue, + fml::TaskRunnerAffineWeakPtr snapshot_delegate, + const std::shared_ptr& gpu_disabled_switch, + impeller::RuntimeStageBackend runtime_stage_type = + impeller::RuntimeStageBackend::kSkSL); + + //---------------------------------------------------------------------------- + /// @brief Create a Engine that shares as many resources as + /// possible with the calling Engine such that together + /// they occupy less memory and be created faster. + /// @details This should only be called on running Engines. + /// @return A new Engine with a running isolate. + /// @see Engine::Engine + /// @see DartIsolate::SpawnIsolate + /// + std::unique_ptr Spawn( + Delegate& delegate, + const PointerDataDispatcherMaker& dispatcher_maker, + const Settings& settings, + std::unique_ptr animator, + const std::string& initial_route, + const fml::WeakPtr& io_manager, + fml::TaskRunnerAffineWeakPtr snapshot_delegate, + const std::shared_ptr& gpu_disabled_switch) const; + + //---------------------------------------------------------------------------- + /// @brief Destroys the engine engine. Called by the shell on the UI task + /// runner. The running root isolate is terminated and will no + /// longer access the task runner after this call returns. This + /// allows the embedder to tear down the thread immediately if + /// needed. + /// + ~Engine() override; + + //---------------------------------------------------------------------------- + /// @return The pointer to this instance of the engine. The engine may + /// only be accessed safely on the UI task runner. + /// + fml::WeakPtr GetWeakPtr() const; + + //---------------------------------------------------------------------------- + /// @brief Moves the root isolate to the `DartIsolate::Phase::Running` + /// phase on a successful call to this method. + /// + /// The isolate itself is created when the engine is created, but + /// it is not yet in the running phase. This is done to amortize + /// initial time taken to launch the root isolate. The isolate + /// snapshots used to run the isolate can be fetched on another + /// thread while the engine itself is launched on the UI task + /// runner. + /// + /// Repeated calls to this method after a successful run will be + /// rejected even if the run configuration is valid (with the + /// appropriate error returned). + /// + /// @param[in] configuration The configuration used to run the root isolate. + /// The configuration must be valid. + /// + /// @return The result of the call to run the root isolate. + /// + [[nodiscard]] RunStatus Run(RunConfiguration configuration); + + //---------------------------------------------------------------------------- + /// @brief Tears down an existing root isolate, reuses the components of + /// that isolate and attempts to launch a new isolate using the + /// given the run configuration. This is only used in the + /// "debug" Flutter runtime mode in the cold-restart scenario. + /// + /// @attention This operation must be performed with care as even a + /// non-successful restart will still tear down any existing root + /// isolate. In such cases, the engine and its shell must be + /// discarded. + /// + /// @param[in] configuration The configuration used to launch the new + /// isolate. + /// + /// @return Whether the restart was successful. If not, the engine and its + /// shell must be discarded. + /// + [[nodiscard]] bool Restart(RunConfiguration configuration); + + //---------------------------------------------------------------------------- + /// @brief Setup default font manager according to specific platform. + /// + void SetupDefaultFontManager(); + + //---------------------------------------------------------------------------- + /// @brief Updates the asset manager referenced by the root isolate of a + /// Flutter application. This happens implicitly in the call to + /// `Engine::Run` and `Engine::Restart` as the asset manager is + /// referenced from the run configuration provided to those calls. + /// In addition to the `Engine::Run` and `Engine::Restart` + /// calls, the tooling may need to update the assets available to + /// the application as the user adds them to their project. For + /// example, these assets may be referenced by code that is newly + /// patched in after a hot-reload. Neither the shell or the + /// isolate in relaunched in such cases. The tooling usually + /// patches in the new assets in a temporary location and updates + /// the asset manager to point to that location. + /// + /// @param[in] asset_manager The new asset manager to use for the running + /// root isolate. + /// + /// @return If the asset manager was successfully replaced. This may fail + /// if the new asset manager is invalid. + /// + bool UpdateAssetManager(const std::shared_ptr& asset_manager); + + //---------------------------------------------------------------------------- + /// @brief Notifies the engine that it is time to begin working on a new + /// frame previously scheduled via a call to + /// `Engine::ScheduleFrame`. This call originates in the animator. + /// + /// The frame time given as the argument indicates the point at + /// which the current frame interval began. It is very slightly + /// (because of scheduling overhead) in the past. If a new layer + /// tree is not produced and given to the raster task runner + /// within one frame interval from this point, the Flutter + /// application will jank. + /// + /// If a root isolate is running, this method calls the + /// `::_beginFrame` method in `hooks.dart`. If a root isolate is + /// not running, this call does nothing. + /// + /// This method encapsulates the entire UI thread frame workload. + /// The following (mis)behavior in the functioning of the method + /// will cause the jank in the Flutter application: + /// * The time taken by this method to create a layer-tree exceeds + /// one frame interval (for example, 16.66 ms on a 60Hz + /// display). + /// * The time take by this method to generate a new layer-tree + /// causes the current layer-tree pipeline depth to change. To + /// illustrate this point, note that maximum pipeline depth used + /// by layer tree in the engine is 2. If both the UI and GPU + /// task runner tasks finish within one frame interval, the + /// pipeline depth is one. If the UI thread happens to be + /// working on a frame when the raster thread is still not done + /// with the previous frame, the pipeline depth is 2. When the + /// pipeline depth changes from 1 to 2, animations and UI + /// interactions that cause the generation of the new layer tree + /// appropriate for (frame_time + one frame interval) will + /// actually end up at (frame_time + two frame intervals). This + /// is not what code running on the UI thread expected would + /// happen. This causes perceptible jank. + /// + /// @param[in] frame_time The point at which the current frame interval + /// began. May be used by animation interpolators, + /// physics simulations, etc.. + /// + /// @param[in] frame_number The frame number recorded by the animator. Used + /// by the framework to associate frame specific + /// debug information with frame timings and timeline + /// events. + void BeginFrame(fml::TimePoint frame_time, uint64_t frame_number); + + //---------------------------------------------------------------------------- + /// @brief Notifies the engine that the UI task runner is not expected to + /// undertake a new frame workload till a specified timepoint. The + /// timepoint is measured in microseconds against the system's + /// monotonic clock. It is recommended that the clock be accessed + /// via `Dart_TimelineGetMicros` from `dart_api.h` for + /// consistency. In reality, the clocks used by Dart, FML and + /// std::steady_clock are all the same and the timepoints can be + /// converted from on clock type to another. + /// + /// The Dart VM uses this notification to schedule book-keeping + /// tasks that may include a garbage collection. In this way, it + /// is less likely for the VM to perform such (potentially long + /// running) tasks in the middle of a frame workload. + /// + /// This notification is advisory. That is, not providing this + /// notification does not mean garbage collection is postponed + /// till this call is made. If this notification is not provided, + /// garbage collection will happen based on the usual heuristics + /// used by the Dart VM. + /// + /// Currently, this idle notification is delivered to the engine + /// at two points. Once, the deadline is calculated based on how + /// much time in the current frame interval is left on the UI task + /// runner. Since the next frame workload cannot begin till at + /// least the next callback from the vsync waiter, this period may + /// be used to used as a "small" idle notification. On the other + /// hand, if no more frames are scheduled, a large (but arbitrary) + /// idle notification deadline is chosen for a "big" idle + /// notification. Again, this notification does not guarantee + /// collection, just gives the Dart VM more hints about opportune + /// moments to perform collections. + /// + /// + /// @param[in] deadline The deadline is used by the VM to determine if the + /// corresponding sweep can be performed within the + /// deadline. + /// + void NotifyIdle(fml::TimeDelta deadline); + + //---------------------------------------------------------------------------- + /// @brief Notifies the engine that the attached flutter view has been + /// destroyed. + /// This enables the engine to notify the Dart VM so it can do + /// some cleanp activities. + void NotifyDestroyed(); + + //---------------------------------------------------------------------------- + /// @brief Dart code cannot fully measure the time it takes for a + /// specific frame to be rendered. This is because Dart code only + /// runs on the UI task runner. That is only a small part of the + /// overall frame workload. The raster task runner frame workload + /// is executed on a thread where Dart code cannot run (and hence + /// instrument). Besides, due to the pipelined nature of rendering + /// in Flutter, there may be multiple frame workloads being + /// processed at any given time. However, for non-Timeline based + /// profiling, it is useful for trace collection and processing to + /// happen in Dart. To do this, the raster task runner frame + /// workloads need to be instrumented separately. After a set + /// number of these profiles have been gathered, they need to be + /// reported back to Dart code. The shell reports this extra + /// instrumentation information back to Dart code running on the + /// engine by invoking this method at predefined intervals. + /// + /// @see `FrameTiming` + /// + // TODO(chinmaygarde): The use `int64_t` is added for ease of conversion to + // Dart but hurts readability. The phases and the units of the timepoints are + // not obvious without some sleuthing. The conversion can happen at the + // native interface boundary instead. + /// + /// @param[in] timings Collection of `FrameTiming::kCount` * `n` timestamps + /// for `n` frames whose timings have not been reported + /// yet. A collection of integers is reported here for + /// easier conversions to Dart objects. The timestamps + /// are measured against the system monotonic clock + /// measured in microseconds. + /// + void ReportTimings(std::vector timings); + + //---------------------------------------------------------------------------- + /// @brief Gets the main port of the root isolate. Since the isolate is + /// created immediately in the constructor of the engine, it is + /// possible to get its main port immediately (even before a call + /// to `Run` can be made). This is useful in registering the port + /// in a race free manner with a port nameserver. + /// + /// @return The main port of the root isolate. + /// + Dart_Port GetUIIsolateMainPort(); + + //---------------------------------------------------------------------------- + /// @brief Gets the debug name of the root isolate. By default, the + /// debug name of the isolate is derived from its advisory script + /// URI, advisory main entrypoint and its main port name. For + /// example, "main.dart$main-1234" where the script URI is + /// "main.dart", the entrypoint is "main" and the port name + /// "1234". Once launched, the isolate may re-christen itself + /// using a name it selects via `setIsolateDebugName` in + /// `platform_dispatcher.dart`. This name is purely advisory and + /// only used by instrumentation and reporting purposes. + /// + /// @return The debug name of the root isolate. + /// + std::string GetUIIsolateName(); + + //---------------------------------------------------------------------------- + /// @brief It is an unexpected challenge to determine when a Dart + /// application is "done". The application cannot simply terminate + /// the native process (and perhaps return an exit code) because + /// it does not have that power. After all, Flutter applications + /// reside within a host process that may have other + /// responsibilities besides just running Flutter applications. + /// Also, the `main` entry-points are run on an event loop and + /// returning from "main" (unlike in C/C++ applications) does not + /// mean termination of the process. Besides, the return value of + /// the main entrypoint is discarded. + /// + /// One technique used by embedders to determine "liveness" is to + /// count the outstanding live ports dedicated to the application. + /// These ports may be live as a result of pending timers, + /// scheduled tasks, pending IO on sockets, channels open with + /// other isolates, etc.. At regular intervals (sometimes as often + /// as after the UI task runner processes any task), embedders may + /// check for the "liveness" of the application and perform + /// teardown of the embedder when no more ports are live. + /// + /// @return Check if the root isolate has any live ports. + /// + bool UIIsolateHasLivePorts(); + + /// @brief Another signal of liveness is the presence of microtasks that + /// have been queued by the application but have not yet been + /// executed. Embedders may want to check for pending microtasks + /// and ensure that the microtask queue has been drained before + /// the embedder terminates. + /// + /// @return Check if the root isolate has any pending microtasks. + bool UIIsolateHasPendingMicrotasks(); + + //---------------------------------------------------------------------------- + /// @brief Errors that are unhandled on the Dart message loop are kept + /// for further inspection till the next unhandled error comes + /// along. This accessor returns the last unhandled error + /// encountered by the root isolate. + /// + /// @return The ui isolate last error. + /// + tonic::DartErrorHandleType GetUIIsolateLastError(); + + //---------------------------------------------------------------------------- + /// @brief As described in the discussion for `UIIsolateHasLivePorts`, + /// the "done-ness" of a Dart application is tricky to ascertain + /// and the return value from the main entrypoint is discarded + /// (because the Dart isolate is still running after the main + /// entrypoint returns). But, the concept of an exit code akin to + /// those returned by native applications is still useful. Short + /// lived Dart applications (usually tests), emulate this by + /// setting a per isolate "return value" and then indicating their + /// "done-ness" (usually via closing all live ports). This + /// accessor returns that "return value" is present. + /// + /// @see `UIIsolateHasLivePorts` + /// + /// @return The return code (if specified) by the isolate. + /// + std::optional GetUIIsolateReturnCode(); + + //---------------------------------------------------------------------------- + /// @brief Notify the Flutter application that a new view is available. + /// + /// A view must be added before other methods can refer to it, + /// including the implicit view. Adding a view that already exists + /// triggers an assertion. + /// + /// @param[in] view_id The ID of the new view. + /// @param[in] viewport_metrics The initial viewport metrics for the view. + /// @param[in] callback Callback that will be invoked once + /// the engine attempts to add the view. + /// + void AddView(int64_t view_id, + const ViewportMetrics& view_metrics, + std::function callback); + + //---------------------------------------------------------------------------- + /// @brief Notify the Flutter application that a view is no + /// longer available. + /// + /// Removing a view that does not exist triggers an assertion. + /// + /// The implicit view (kFlutterImplicitViewId) should never be + /// removed. Doing so triggers an assertion. + /// + /// @param[in] view_id The ID of the view. + /// + /// @return Whether the view was removed. + /// + bool RemoveView(int64_t view_id); + + //---------------------------------------------------------------------------- + /// @brief Notify the Flutter application that the focus state of a + /// native view has changed. + /// + /// @param[in] event The focus event describing the change. + bool SendViewFocusEvent(const ViewFocusEvent& event); + + //---------------------------------------------------------------------------- + /// @brief Updates the viewport metrics for a view. The viewport metrics + /// detail the size of the rendering viewport in texels as well as + /// edge insets if present. + /// + /// @see `ViewportMetrics` + /// + /// @param[in] view_id The ID for the view that `metrics` describes. + /// @param[in] metrics The metrics. + /// + void SetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics); + + //---------------------------------------------------------------------------- + /// @brief Updates the display metrics for the currently running Flutter + /// application. + /// + /// @param[in] displays A complete list of displays + /// + void SetDisplays(const std::vector& displays); + + //---------------------------------------------------------------------------- + /// @brief Notifies the engine that the embedder has sent it a message. + /// This call originates in the platform view and has been + /// forwarded to the engine on the UI task runner here. + /// + /// @param[in] message The message sent from the embedder to the Dart + /// application. + /// + void DispatchPlatformMessage(std::unique_ptr message); + + //---------------------------------------------------------------------------- + /// @brief Notifies the engine that the embedder has sent it a pointer + /// data packet. A pointer data packet may contain multiple + /// input events. This call originates in the platform view and + /// the shell has forwarded the same to the engine on the UI task + /// runner here. + /// + /// @param[in] packet The pointer data packet containing multiple + /// input events. + /// @param[in] trace_flow_id The trace flow identifier associated with the + /// pointer data packet. The engine uses this trace + /// identifier to connect trace flows in the + /// timeline from the input event to the + /// frames generated due to those input events. + /// These flows are tagged as "PointerEvent" in the + /// timeline and allow grouping frames and input + /// events into logical chunks. + /// + void DispatchPointerDataPacket(std::unique_ptr packet, + uint64_t trace_flow_id); + + //---------------------------------------------------------------------------- + /// @brief Notifies the engine that the embedder encountered an + /// accessibility related action on the specified node. This call + /// originates on the platform view and has been forwarded to the + /// engine here on the UI task runner by the shell. + /// + /// @param[in] view_id The identifier of the view. + /// @param[in] node_id The identifier of the accessibility node. + /// @param[in] action The accessibility related action performed on the + /// node of the specified ID. + /// @param[in] args Optional data that applies to the specified action. + /// + void DispatchSemanticsAction(int64_t view_id, + int node_id, + SemanticsAction action, + fml::MallocMapping args); + + //---------------------------------------------------------------------------- + /// @brief Notifies the engine that the embedder has expressed an opinion + /// about whether the accessibility tree should be generated or + /// not. This call originates in the platform view and is + /// forwarded to the engine here on the UI task runner by the + /// shell. + /// + /// @param[in] enabled Whether the accessibility tree is enabled or + /// disabled. + /// + void SetSemanticsEnabled(bool enabled); + + //---------------------------------------------------------------------------- + /// @brief Notifies the engine that the embedder has expressed an opinion + /// about where the flags to set on the accessibility tree. This + /// flag originates in the platform view and is forwarded to the + /// engine here on the UI task runner by the shell. + /// + /// The engine does not care about the accessibility feature flags + /// as all it does is forward this information from the embedder + /// to the framework. However, curious readers may refer to + /// `AccessibilityFeatures` in `window.dart` for currently + /// supported accessibility feature flags. + /// + /// @param[in] flags The features to enable in the accessibility tree. + /// + void SetAccessibilityFeatures(int32_t flags); + + // |RuntimeDelegate| + void ScheduleFrame(bool regenerate_layer_trees) override; + + /// Schedule a frame with the default parameter of regenerating the layer + /// tree. + void ScheduleFrame() { ScheduleFrame(true); } + + // |RuntimeDelegate| + void OnAllViewsRendered() override; + + // |RuntimeDelegate| + FontCollection& GetFontCollection() override; + + // |RuntimeDelegate| + std::shared_ptr GetAssetManager() override; + + // Return the weak_ptr of ImageDecoder. + fml::WeakPtr GetImageDecoderWeakPtr(); + + //---------------------------------------------------------------------------- + /// @brief Get the `ImageGeneratorRegistry` associated with the current + /// engine. + /// + /// @return The engine's `ImageGeneratorRegistry`. + /// + fml::WeakPtr GetImageGeneratorRegistry(); + + // |PointerDataDispatcher::Delegate| + void DoDispatchPacket(std::unique_ptr packet, + uint64_t trace_flow_id) override; + + // |PointerDataDispatcher::Delegate| + void ScheduleSecondaryVsyncCallback(uintptr_t id, + const fml::closure& callback) override; + + //---------------------------------------------------------------------------- + /// @brief Get the last Entrypoint that was used in the RunConfiguration + /// when |Engine::Run| was called. + /// + const std::string& GetLastEntrypoint() const; + + //---------------------------------------------------------------------------- + /// @brief Get the last Entrypoint Library that was used in the + /// RunConfiguration when |Engine::Run| was called. + /// + const std::string& GetLastEntrypointLibrary() const; + + //---------------------------------------------------------------------------- + /// @brief Get the last Entrypoint Arguments that was used in the + /// RunConfiguration when |Engine::Run| was called.This is only + /// valid in debug mode. + /// + const std::vector& GetLastEntrypointArgs() const; + + //---------------------------------------------------------------------------- + /// @brief Getter for the initial route. This can be set with a platform + /// message. + /// + const std::string& InitialRoute() const { return initial_route_; } + + //-------------------------------------------------------------------------- + /// @brief Loads the Dart shared library into the Dart VM. When the + /// Dart library is loaded successfully, the Dart future + /// returned by the originating loadLibrary() call completes. + /// + /// The Dart compiler may generate separate shared libraries + /// files called 'loading units' when libraries are imported + /// as deferred. Each of these shared libraries are identified + /// by a unique loading unit id. Callers should open and resolve + /// a SymbolMapping from the shared library. The Mappings should + /// be moved into this method, as ownership will be assumed by the + /// dart root isolate after successful loading and released after + /// shutdown of the root isolate. The loading unit may not be + /// used after isolate shutdown. If loading fails, the mappings + /// will be released. + /// + /// This method is paired with a RequestDartDeferredLibrary + /// invocation that provides the embedder with the loading unit id + /// of the deferred library to load. + /// + /// + /// @param[in] loading_unit_id The unique id of the deferred library's + /// loading unit, as passed in by + /// RequestDartDeferredLibrary. + /// + /// @param[in] snapshot_data Dart snapshot data of the loading unit's + /// shared library. + /// + /// @param[in] snapshot_data Dart snapshot instructions of the loading + /// unit's shared library. + /// + void LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions); + + //-------------------------------------------------------------------------- + /// @brief Indicates to the dart VM that the request to load a deferred + /// library with the specified loading unit id has failed. + /// + /// The dart future returned by the initiating loadLibrary() call + /// will complete with an error. + /// + /// @param[in] loading_unit_id The unique id of the deferred library's + /// loading unit, as passed in by + /// RequestDartDeferredLibrary. + /// + /// @param[in] error_message The error message that will appear in the + /// dart Future. + /// + /// @param[in] transient A transient error is a failure due to + /// temporary conditions such as no network. + /// Transient errors allow the dart VM to + /// re-request the same deferred library and + /// loading_unit_id again. Non-transient + /// errors are permanent and attempts to + /// re-request the library will instantly + /// complete with an error. + void LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string& error_message, + bool transient); + + //-------------------------------------------------------------------------- + /// @brief Accessor for the RuntimeController. + /// + const RuntimeController* GetRuntimeController() const { + return runtime_controller_.get(); + } + + const std::weak_ptr GetVsyncWaiter() const; + + //-------------------------------------------------------------------------- + /// @brief Shuts down all registered platform isolates. Must be called + /// from the platform thread. + /// + void ShutdownPlatformIsolates(); + + //-------------------------------------------------------------------------- + /// @brief Flushes the microtask queue of the root isolate. + /// + void FlushMicrotaskQueue(); + + private: + // |RuntimeDelegate| + std::string DefaultRouteName() override; + + // |RuntimeDelegate| + void Render(int64_t view_id, + std::unique_ptr layer_tree, + float device_pixel_ratio) override; + + // |RuntimeDelegate| + void UpdateSemantics(int64_t view_id, + SemanticsNodeUpdates update, + CustomAccessibilityActionUpdates actions) override; + + // |RuntimeDelegate| + void HandlePlatformMessage(std::unique_ptr message) override; + + // |RuntimeDelegate| + void OnRootIsolateCreated() override; + + // |RuntimeDelegate| + void UpdateIsolateDescription(const std::string isolate_name, + int64_t isolate_port) override; + + // |RuntimeDelegate| + std::unique_ptr> ComputePlatformResolvedLocale( + const std::vector& supported_locale_data) override; + + // |RuntimeDelegate| + void RequestDartDeferredLibrary(intptr_t loading_unit_id) override; + + // |RuntimeDelegate| + std::weak_ptr GetPlatformMessageHandler() + const override; + + // |RuntimeDelegate| + void SendChannelUpdate(std::string name, bool listening) override; + + // |RuntimeDelegate| + double GetScaledFontSize(double unscaled_font_size, + int configuration_id) const override; + + // |RuntimeDelegate| + void RequestViewFocusChange(const ViewFocusChangeRequest& request) override; + + void SetNeedsReportTimings(bool value) override; + + bool HandleLifecyclePlatformMessage(PlatformMessage* message); + + bool HandleNavigationPlatformMessage( + std::unique_ptr message); + + bool HandleLocalizationPlatformMessage(PlatformMessage* message); + + void HandleSettingsPlatformMessage(PlatformMessage* message); + + void HandleAssetPlatformMessage(std::unique_ptr message); + + bool GetAssetAsBuffer(const std::string& name, std::vector* data); + + friend class testing::ShellTest; + + Engine::Delegate& delegate_; + const Settings settings_; + std::unique_ptr animator_; + std::unique_ptr runtime_controller_; + + // The pointer_data_dispatcher_ depends on animator_ and runtime_controller_. + // So it should be defined after them to ensure that pointer_data_dispatcher_ + // is destructed first. + std::unique_ptr pointer_data_dispatcher_; + + std::string last_entry_point_; + std::string last_entry_point_library_; + std::vector last_entry_point_args_; + std::string initial_route_; + std::shared_ptr asset_manager_; + std::shared_ptr font_collection_; + std::shared_ptr native_assets_manager_; + const std::unique_ptr image_decoder_; + ImageGeneratorRegistry image_generator_registry_; + TaskRunners task_runners_; + fml::WeakPtrFactory weak_factory_; // Must be the last member. + FML_DISALLOW_COPY_AND_ASSIGN(Engine); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_ENGINE_H_ diff --git a/flutter/engine/src/flutter/shell/common/engine_animator_unittests.cc b/flutter/engine/src/flutter/shell/common/engine_animator_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..fc97a8c0e2405b6641872710a67833b5eacddbe1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/engine_animator_unittests.cc @@ -0,0 +1,666 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/engine.h" + +// #include + +#include "flutter/common/constants.h" +#include "flutter/lib/ui/compositing/scene_builder.h" +#include "flutter/shell/common/shell_test.h" +#include "flutter/testing/fixture_test.h" +#include "gmock/gmock.h" + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace flutter { + +namespace { + +using ::testing::Invoke; +using ::testing::ReturnRef; + +fml::AutoResetWaitableEvent native_latch; + +void PostSync(const fml::RefPtr& task_runner, + const fml::closure& task) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask(task_runner, [&latch, &task] { + task(); + latch.Signal(); + }); + latch.Wait(); +} + +// Sort the argument list of `LayerTreeTask` into a new list that is sorted by +// their view IDs. `FrameItem::layer_tree_tasks` might not come sorted. +std::vector Sorted( + const std::vector>& layer_tree_tasks) { + std::vector result; + result.reserve(layer_tree_tasks.size()); + for (auto& task_ptr : layer_tree_tasks) { + result.push_back(task_ptr.get()); + } + std::sort(result.begin(), result.end(), + [](const LayerTreeTask* a, const LayerTreeTask* b) { + return a->view_id < b->view_id; + }); + return result; +} + +class MockDelegate : public Engine::Delegate { + public: + MOCK_METHOD(void, + OnEngineUpdateSemantics, + (int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates), + (override)); + MOCK_METHOD(void, + OnEngineHandlePlatformMessage, + (std::unique_ptr), + (override)); + MOCK_METHOD(void, OnPreEngineRestart, (), (override)); + MOCK_METHOD(void, OnRootIsolateCreated, (), (override)); + MOCK_METHOD(void, + UpdateIsolateDescription, + (const std::string, int64_t), + (override)); + MOCK_METHOD(void, SetNeedsReportTimings, (bool), (override)); + MOCK_METHOD(std::unique_ptr>, + ComputePlatformResolvedLocale, + (const std::vector&), + (override)); + MOCK_METHOD(void, RequestDartDeferredLibrary, (intptr_t), (override)); + MOCK_METHOD(fml::TimePoint, GetCurrentTimePoint, (), (override)); + MOCK_METHOD(const std::shared_ptr&, + GetPlatformMessageHandler, + (), + (const, override)); + MOCK_METHOD(void, OnEngineChannelUpdate, (std::string, bool), (override)); + MOCK_METHOD(double, + GetScaledFontSize, + (double font_size, int configuration_id), + (const, override)); + MOCK_METHOD(void, + RequestViewFocusChange, + (const ViewFocusChangeRequest&), + (override)); +}; + +class MockAnimatorDelegate : public Animator::Delegate { + public: + /* Animator::Delegate */ + MOCK_METHOD(void, + OnAnimatorBeginFrame, + (fml::TimePoint frame_target_time, uint64_t frame_number), + (override)); + MOCK_METHOD(void, + OnAnimatorNotifyIdle, + (fml::TimeDelta deadline), + (override)); + MOCK_METHOD(void, + OnAnimatorUpdateLatestFrameTargetTime, + (fml::TimePoint frame_target_time), + (override)); + MOCK_METHOD(void, + OnAnimatorDraw, + (std::shared_ptr pipeline), + (override)); + MOCK_METHOD(void, + OnAnimatorDrawLastLayerTrees, + (std::unique_ptr frame_timings_recorder), + (override)); +}; + +class MockPlatformMessageHandler : public PlatformMessageHandler { + public: + MOCK_METHOD(void, + HandlePlatformMessage, + (std::unique_ptr message), + (override)); + MOCK_METHOD(bool, + DoesHandlePlatformMessageOnPlatformThread, + (), + (const, override)); + MOCK_METHOD(void, + InvokePlatformMessageResponseCallback, + (int response_id, std::unique_ptr mapping), + (override)); + MOCK_METHOD(void, + InvokePlatformMessageEmptyResponseCallback, + (int response_id), + (override)); +}; + +class EngineAnimatorTest : public testing::FixtureTest { + public: + EngineAnimatorTest() + : thread_host_("EngineAnimatorTest", + ThreadHost::Type::kPlatform | ThreadHost::Type::kIo | + ThreadHost::Type::kUi | ThreadHost::Type::kRaster), + task_runners_({ + "EngineAnimatorTest", + thread_host_.platform_thread->GetTaskRunner(), // platform + thread_host_.raster_thread->GetTaskRunner(), // raster + thread_host_.ui_thread->GetTaskRunner(), // ui + thread_host_.io_thread->GetTaskRunner() // io + }) {} + + void PostUITaskSync(const std::function& function) { + fml::AutoResetWaitableEvent latch; + task_runners_.GetUITaskRunner()->PostTask([&] { + function(); + latch.Signal(); + }); + latch.Wait(); + } + + protected: + void SetUp() override { + settings_ = CreateSettingsForFixture(); + dispatcher_maker_ = [](PointerDataDispatcher::Delegate&) { + return nullptr; + }; + } + + MockDelegate delegate_; + PointerDataDispatcherMaker dispatcher_maker_; + ThreadHost thread_host_; + TaskRunners task_runners_; + Settings settings_; + std::unique_ptr animator_; + fml::WeakPtr io_manager_; + std::unique_ptr runtime_controller_; + std::shared_ptr image_decoder_task_runner_; + fml::TaskRunnerAffineWeakPtr snapshot_delegate_; +}; + +// A class that can launch an Engine with the specified Engine::Delegate. +// +// To use this class, contruct this class with Create, call Run, and use the +// engine with EngineTaskSync(). +class EngineContext { + public: + using EngineCallback = std::function; + + [[nodiscard]] static std::unique_ptr Create( + Engine::Delegate& delegate, // + Settings settings, // + const TaskRunners& task_runners, // + std::unique_ptr animator) { + auto [vm, isolate_snapshot] = Shell::InferVmInitDataFromSettings(settings); + FML_CHECK(vm) << "Must be able to initialize the VM."; + // Construct the class with `new` because `make_unique` has no access to the + // private constructor. + EngineContext* raw_pointer = + new EngineContext(delegate, settings, task_runners, std::move(animator), + vm, isolate_snapshot); + return std::unique_ptr(raw_pointer); + } + + void Run(RunConfiguration configuration) { + PostSync(task_runners_.GetUITaskRunner(), [this, &configuration] { + Engine::RunStatus run_status = engine_->Run(std::move(configuration)); + FML_CHECK(run_status == Engine::RunStatus::Success) + << "Engine failed to run."; + (void)run_status; // Suppress unused-variable warning + }); + } + + // Run a task that operates the Engine on the UI thread, and wait for the + // task to end. + // + // If called on the UI thread, the task is executed synchronously. + void EngineTaskSync(EngineCallback task) { + ASSERT_TRUE(engine_); + ASSERT_TRUE(task); + auto runner = task_runners_.GetUITaskRunner(); + if (runner->RunsTasksOnCurrentThread()) { + task(*engine_); + } else { + PostSync(task_runners_.GetUITaskRunner(), [&]() { task(*engine_); }); + } + } + + ~EngineContext() { + PostSync(task_runners_.GetUITaskRunner(), [this] { engine_.reset(); }); + } + + private: + EngineContext(Engine::Delegate& delegate, // + Settings settings, // + const TaskRunners& task_runners, // + std::unique_ptr animator, // + const DartVMRef& vm, // + fml::RefPtr isolate_snapshot) + : task_runners_(task_runners), vm_(vm) { + PostSync(task_runners.GetUITaskRunner(), [this, &settings, &animator, + &delegate, &isolate_snapshot] { + auto dispatcher_maker = + [](DefaultPointerDataDispatcher::Delegate& delegate) { + return std::make_unique(delegate); + }; + engine_ = std::make_unique( + /*delegate=*/delegate, + /*dispatcher_maker=*/dispatcher_maker, + /*vm=*/*&vm_, + /*isolate_snapshot=*/std::move(isolate_snapshot), + /*task_runners=*/task_runners_, + /*platform_data=*/PlatformData(), + /*settings=*/settings, + /*animator=*/std::move(animator), + /*io_manager=*/io_manager_, + /*unref_queue=*/nullptr, + /*snapshot_delegate=*/snapshot_delegate_, + /*gpu_disabled_switch=*/std::make_shared()); + }); + } + + TaskRunners task_runners_; + DartVMRef vm_; + std::unique_ptr engine_; + + fml::WeakPtr io_manager_; + fml::TaskRunnerAffineWeakPtr snapshot_delegate_; +}; +} // namespace + +TEST_F(EngineAnimatorTest, AnimatorAcceptsMultipleRenders) { + MockAnimatorDelegate animator_delegate; + std::unique_ptr engine_context; + + std::shared_ptr platform_message_handler = + std::make_shared(); + EXPECT_CALL(delegate_, GetPlatformMessageHandler) + .WillOnce(ReturnRef(platform_message_handler)); + fml::AutoResetWaitableEvent draw_latch; + EXPECT_CALL(animator_delegate, OnAnimatorDraw) + .WillOnce( + Invoke([&draw_latch](const std::shared_ptr& pipeline) { + auto status = + pipeline->Consume([&](std::unique_ptr item) { + auto tasks = Sorted(item->layer_tree_tasks); + EXPECT_EQ(tasks.size(), 2u); + EXPECT_EQ(tasks[0]->view_id, 1); + EXPECT_EQ(tasks[1]->view_id, 2); + }); + EXPECT_EQ(status, PipelineConsumeResult::Done); + draw_latch.Signal(); + })); + EXPECT_CALL(animator_delegate, OnAnimatorBeginFrame) + .WillOnce(Invoke([&engine_context](fml::TimePoint frame_target_time, + uint64_t frame_number) { + engine_context->EngineTaskSync([&](Engine& engine) { + engine.BeginFrame(frame_target_time, frame_number); + }); + })); + + native_latch.Reset(); + AddNativeCallback("NotifyNative", [](auto args) { native_latch.Signal(); }); + + std::unique_ptr animator; + PostSync(task_runners_.GetUITaskRunner(), + [&animator, &animator_delegate, &task_runners = task_runners_] { + animator = std::make_unique( + animator_delegate, task_runners, + static_cast>( + std::make_unique( + task_runners))); + }); + + engine_context = EngineContext::Create(delegate_, settings_, task_runners_, + std::move(animator)); + auto configuration = RunConfiguration::InferFromSettings(settings_); + configuration.SetEntrypoint("onDrawFrameRenderAllViews"); + engine_context->Run(std::move(configuration)); + + engine_context->EngineTaskSync([](Engine& engine) { + engine.AddView(1, ViewportMetrics{1, 10, 10, 22, 0}, + [](bool added) { ASSERT_TRUE(added); }); + engine.AddView(2, ViewportMetrics{1, 10, 10, 22, 0}, + [](bool added) { ASSERT_TRUE(added); }); + }); + + native_latch.Wait(); + + engine_context->EngineTaskSync( + [](Engine& engine) { engine.ScheduleFrame(); }); + draw_latch.Wait(); +} + +TEST_F(EngineAnimatorTest, IgnoresOutOfFrameRenders) { + MockAnimatorDelegate animator_delegate; + std::unique_ptr engine_context; + + std::shared_ptr platform_message_handler = + std::make_shared(); + EXPECT_CALL(delegate_, GetPlatformMessageHandler) + .WillOnce(ReturnRef(platform_message_handler)); + fml::AutoResetWaitableEvent draw_latch; + EXPECT_CALL(animator_delegate, OnAnimatorDraw) + .WillOnce( + Invoke([&draw_latch](const std::shared_ptr& pipeline) { + auto status = + pipeline->Consume([&](std::unique_ptr item) { + // View 1 is rendered before the frame, and is ignored. + // View 2 is rendered within the frame, and is accepted. + EXPECT_EQ(item->layer_tree_tasks.size(), 1u); + EXPECT_EQ(item->layer_tree_tasks[0]->view_id, 2); + }); + EXPECT_EQ(status, PipelineConsumeResult::Done); + draw_latch.Signal(); + })); + EXPECT_CALL(animator_delegate, OnAnimatorBeginFrame) + .WillOnce(Invoke([&engine_context](fml::TimePoint frame_target_time, + uint64_t frame_number) { + engine_context->EngineTaskSync([&](Engine& engine) { + engine.BeginFrame(frame_target_time, frame_number); + }); + })); + + std::unique_ptr animator; + PostSync(task_runners_.GetUITaskRunner(), + [&animator, &animator_delegate, &task_runners = task_runners_] { + animator = std::make_unique( + animator_delegate, task_runners, + static_cast>( + std::make_unique( + task_runners))); + }); + + engine_context = EngineContext::Create(delegate_, settings_, task_runners_, + std::move(animator)); + + engine_context->EngineTaskSync([](Engine& engine) { + engine.AddView(1, ViewportMetrics{1, 10, 10, 22, 0}, + [](bool added) { ASSERT_TRUE(added); }); + engine.AddView(2, ViewportMetrics{1, 10, 10, 22, 0}, + [](bool added) { ASSERT_TRUE(added); }); + }); + + auto configuration = RunConfiguration::InferFromSettings(settings_); + configuration.SetEntrypoint("renderViewsInFrameAndOutOfFrame"); + engine_context->Run(std::move(configuration)); + + draw_latch.Wait(); +} + +TEST_F(EngineAnimatorTest, IgnoresDuplicateRenders) { + MockAnimatorDelegate animator_delegate; + std::unique_ptr engine_context; + + std::vector> benchmark_layers; + auto capture_root_layer = [&benchmark_layers](Dart_NativeArguments args) { + auto handle = Dart_GetNativeArgument(args, 0); + intptr_t peer = 0; + Dart_Handle result = Dart_GetNativeInstanceField( + handle, tonic::DartWrappable::kPeerIndex, &peer); + ASSERT_FALSE(Dart_IsError(result)); + SceneBuilder* scene_builder = reinterpret_cast(peer); + ASSERT_TRUE(scene_builder); + std::shared_ptr root_layer = + scene_builder->layer_stack()[0]; + ASSERT_TRUE(root_layer); + benchmark_layers = root_layer->layers(); + }; + + std::shared_ptr platform_message_handler = + std::make_shared(); + EXPECT_CALL(delegate_, GetPlatformMessageHandler) + .WillOnce(ReturnRef(platform_message_handler)); + fml::AutoResetWaitableEvent draw_latch; + EXPECT_CALL(animator_delegate, OnAnimatorDraw) + .WillOnce(Invoke([&draw_latch, &benchmark_layers]( + const std::shared_ptr& pipeline) { + auto status = pipeline->Consume([&](std::unique_ptr item) { + EXPECT_EQ(item->layer_tree_tasks.size(), 1u); + EXPECT_EQ(item->layer_tree_tasks[0]->view_id, kFlutterImplicitViewId); + ContainerLayer* root_layer = reinterpret_cast( + item->layer_tree_tasks[0]->layer_tree->root_layer()); + std::vector> result_layers = + root_layer->layers(); + EXPECT_EQ(result_layers.size(), benchmark_layers.size()); + EXPECT_EQ(result_layers[0], benchmark_layers[0]); + }); + EXPECT_EQ(status, PipelineConsumeResult::Done); + draw_latch.Signal(); + })); + EXPECT_CALL(animator_delegate, OnAnimatorBeginFrame) + .WillOnce(Invoke([&engine_context](fml::TimePoint frame_target_time, + uint64_t frame_number) { + engine_context->EngineTaskSync([&](Engine& engine) { + engine.BeginFrame(frame_target_time, frame_number); + }); + })); + + AddNativeCallback("CaptureRootLayer", + CREATE_NATIVE_ENTRY(capture_root_layer)); + + std::unique_ptr animator; + PostSync(task_runners_.GetUITaskRunner(), + [&animator, &animator_delegate, &task_runners = task_runners_] { + animator = std::make_unique( + animator_delegate, task_runners, + static_cast>( + std::make_unique( + task_runners))); + }); + + engine_context = EngineContext::Create(delegate_, settings_, task_runners_, + std::move(animator)); + + engine_context->EngineTaskSync([](Engine& engine) { + engine.AddView(kFlutterImplicitViewId, ViewportMetrics{1, 10, 10, 22, 0}, + [](bool added) { ASSERT_TRUE(added); }); + }); + + auto configuration = RunConfiguration::InferFromSettings(settings_); + configuration.SetEntrypoint("renderTwiceForOneView"); + engine_context->Run(std::move(configuration)); + + draw_latch.Wait(); +} + +TEST_F(EngineAnimatorTest, AnimatorSubmitsImplicitViewBeforeDrawFrameEnds) { + MockAnimatorDelegate animator_delegate; + std::unique_ptr engine_context; + + std::shared_ptr platform_message_handler = + std::make_shared(); + EXPECT_CALL(delegate_, GetPlatformMessageHandler) + .WillOnce(ReturnRef(platform_message_handler)); + + bool rasterization_started = false; + EXPECT_CALL(animator_delegate, OnAnimatorDraw) + .WillOnce(Invoke([&rasterization_started]( + const std::shared_ptr& pipeline) { + rasterization_started = true; + auto status = pipeline->Consume([&](std::unique_ptr item) { + EXPECT_EQ(item->layer_tree_tasks.size(), 1u); + EXPECT_EQ(item->layer_tree_tasks[0]->view_id, kFlutterImplicitViewId); + }); + EXPECT_EQ(status, PipelineConsumeResult::Done); + })); + EXPECT_CALL(animator_delegate, OnAnimatorBeginFrame) + .WillRepeatedly(Invoke([&engine_context](fml::TimePoint frame_target_time, + uint64_t frame_number) { + engine_context->EngineTaskSync([&](Engine& engine) { + engine.BeginFrame(frame_target_time, frame_number); + }); + })); + + std::unique_ptr animator; + PostSync(task_runners_.GetUITaskRunner(), + [&animator, &animator_delegate, &task_runners = task_runners_] { + animator = std::make_unique( + animator_delegate, task_runners, + static_cast>( + std::make_unique( + task_runners))); + }); + + native_latch.Reset(); + // The native_latch is signaled at the end of handleDrawFrame. + AddNativeCallback("NotifyNative", + CREATE_NATIVE_ENTRY([&rasterization_started](auto args) { + EXPECT_EQ(rasterization_started, true); + native_latch.Signal(); + })); + + engine_context = EngineContext::Create(delegate_, settings_, task_runners_, + std::move(animator)); + + engine_context->EngineTaskSync([](Engine& engine) { + engine.AddView(kFlutterImplicitViewId, ViewportMetrics{1.0, 10, 10, 1, 0}, + [](bool added) { ASSERT_TRUE(added); }); + }); + + auto configuration = RunConfiguration::InferFromSettings(settings_); + configuration.SetEntrypoint("renderSingleViewAndCallAfterOnDrawFrame"); + engine_context->Run(std::move(configuration)); + + native_latch.Wait(); +} + +// The animator should submit to the pipeline the implicit view rendered in a +// warm up frame if there's already a continuation (i.e. Animator::BeginFrame +// has been called) +TEST_F(EngineAnimatorTest, AnimatorSubmitWarmUpImplicitView) { + MockAnimatorDelegate animator_delegate; + std::unique_ptr engine_context; + + std::shared_ptr platform_message_handler = + std::make_shared(); + EXPECT_CALL(delegate_, GetPlatformMessageHandler) + .WillOnce(ReturnRef(platform_message_handler)); + + fml::AutoResetWaitableEvent continuation_ready_latch; + fml::AutoResetWaitableEvent draw_latch; + EXPECT_CALL(animator_delegate, OnAnimatorDraw) + .WillOnce(Invoke([&draw_latch]( + const std::shared_ptr& pipeline) { + auto status = pipeline->Consume([&](std::unique_ptr item) { + EXPECT_EQ(item->layer_tree_tasks.size(), 1u); + EXPECT_EQ(item->layer_tree_tasks[0]->view_id, kFlutterImplicitViewId); + }); + EXPECT_EQ(status, PipelineConsumeResult::Done); + draw_latch.Signal(); + })); + EXPECT_CALL(animator_delegate, OnAnimatorBeginFrame) + .WillRepeatedly( + Invoke([&engine_context, &continuation_ready_latch]( + fml::TimePoint frame_target_time, uint64_t frame_number) { + continuation_ready_latch.Signal(); + engine_context->EngineTaskSync([&](Engine& engine) { + engine.BeginFrame(frame_target_time, frame_number); + }); + })); + + std::unique_ptr animator; + PostSync(task_runners_.GetUITaskRunner(), + [&animator, &animator_delegate, &task_runners = task_runners_] { + animator = std::make_unique( + animator_delegate, task_runners, + static_cast>( + std::make_unique( + task_runners))); + }); + + engine_context = EngineContext::Create(delegate_, settings_, task_runners_, + std::move(animator)); + + engine_context->EngineTaskSync([](Engine& engine) { + // Schedule a frame to trigger Animator::BeginFrame to create a + // continuation. The continuation needs to be available before `Engine::Run` + // since the Dart program immediately schedules a warm up frame. + engine.ScheduleFrame(true); + // Add the implicit view so that the engine recognizes it and that its + // metrics is not empty. + engine.AddView(kFlutterImplicitViewId, ViewportMetrics{1.0, 10, 10, 1, 0}, + [](bool added) { ASSERT_TRUE(added); }); + }); + continuation_ready_latch.Wait(); + + auto configuration = RunConfiguration::InferFromSettings(settings_); + configuration.SetEntrypoint("renderWarmUpImplicitView"); + engine_context->Run(std::move(configuration)); + + draw_latch.Wait(); +} + +// The warm up frame should work if only some of the registered views are +// included. +// +// This test also verifies that the warm up frame can render multiple views. +TEST_F(EngineAnimatorTest, AnimatorSubmitPartialViewsForWarmUp) { + MockAnimatorDelegate animator_delegate; + std::unique_ptr engine_context; + + std::shared_ptr platform_message_handler = + std::make_shared(); + EXPECT_CALL(delegate_, GetPlatformMessageHandler) + .WillOnce(ReturnRef(platform_message_handler)); + + fml::AutoResetWaitableEvent continuation_ready_latch; + fml::AutoResetWaitableEvent draw_latch; + EXPECT_CALL(animator_delegate, OnAnimatorDraw) + .WillOnce( + Invoke([&draw_latch](const std::shared_ptr& pipeline) { + auto status = + pipeline->Consume([&](std::unique_ptr item) { + auto tasks = Sorted(item->layer_tree_tasks); + EXPECT_EQ(tasks.size(), 2u); + EXPECT_EQ(tasks[0]->view_id, 1); + EXPECT_EQ(tasks[1]->view_id, 2); + }); + EXPECT_EQ(status, PipelineConsumeResult::Done); + draw_latch.Signal(); + })); + EXPECT_CALL(animator_delegate, OnAnimatorBeginFrame) + .WillRepeatedly( + Invoke([&engine_context, &continuation_ready_latch]( + fml::TimePoint frame_target_time, uint64_t frame_number) { + continuation_ready_latch.Signal(); + engine_context->EngineTaskSync([&](Engine& engine) { + engine.BeginFrame(frame_target_time, frame_number); + }); + })); + + std::unique_ptr animator; + PostSync(task_runners_.GetUITaskRunner(), + [&animator, &animator_delegate, &task_runners = task_runners_] { + animator = std::make_unique( + animator_delegate, task_runners, + static_cast>( + std::make_unique( + task_runners))); + }); + + engine_context = EngineContext::Create(delegate_, settings_, task_runners_, + std::move(animator)); + + engine_context->EngineTaskSync([](Engine& engine) { + // Schedule a frame to make the animator create a continuation. + engine.ScheduleFrame(true); + // Add multiple views. + engine.AddView(0, ViewportMetrics{1, 10, 10, 22, 0}, + [](bool added) { ASSERT_TRUE(added); }); + engine.AddView(1, ViewportMetrics{1, 10, 10, 22, 0}, + [](bool added) { ASSERT_TRUE(added); }); + engine.AddView(2, ViewportMetrics{1, 10, 10, 22, 0}, + [](bool added) { ASSERT_TRUE(added); }); + }); + + continuation_ready_latch.Wait(); + + auto configuration = RunConfiguration::InferFromSettings(settings_); + configuration.SetEntrypoint("renderWarmUpView1and2"); + engine_context->Run(std::move(configuration)); + + draw_latch.Wait(); +} + +} // namespace flutter + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/common/engine_unittests.cc b/flutter/engine/src/flutter/shell/common/engine_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..131db5bff6c7a26e7db353e5b00228ef4e078661 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/engine_unittests.cc @@ -0,0 +1,560 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/engine.h" + +#include + +#include "flutter/runtime/dart_vm_lifecycle.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/testing/fixture_test.h" +#include "flutter/testing/testing.h" +#include "fml/mapping.h" +#include "gmock/gmock.h" +#include "lib/ui/text/font_collection.h" +#include "rapidjson/document.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/writer.h" +#include "runtime/isolate_configuration.h" +#include "shell/common/run_configuration.h" + +namespace flutter { + +namespace { + +class FontManifestAssetResolver : public AssetResolver { + public: + FontManifestAssetResolver() {} + + bool IsValid() const override { return true; } + + bool IsValidAfterAssetManagerChange() const override { return true; } + + AssetResolver::AssetResolverType GetType() const override { + return AssetResolver::AssetResolverType::kApkAssetProvider; + } + + mutable size_t mapping_call_count = 0u; + std::unique_ptr GetAsMapping( + const std::string& asset_name) const override { + mapping_call_count++; + if (asset_name == "FontManifest.json") { + return std::make_unique("[{},{},{}]"); + } + return nullptr; + } + + std::vector> GetAsMappings( + const std::string& asset_pattern, + const std::optional& subdir) const override { + return {}; + }; + + bool operator==(const AssetResolver& other) const override { + auto mapping = GetAsMapping("FontManifest.json"); + return memcmp(other.GetAsMapping("FontManifest.json")->GetMapping(), + mapping->GetMapping(), mapping->GetSize()) == 0; + } +}; + +class MockDelegate : public Engine::Delegate { + public: + MOCK_METHOD(void, + OnEngineUpdateSemantics, + (int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates), + (override)); + MOCK_METHOD(void, + OnEngineHandlePlatformMessage, + (std::unique_ptr), + (override)); + MOCK_METHOD(void, OnPreEngineRestart, (), (override)); + MOCK_METHOD(void, OnRootIsolateCreated, (), (override)); + MOCK_METHOD(void, + UpdateIsolateDescription, + (const std::string, int64_t), + (override)); + MOCK_METHOD(void, SetNeedsReportTimings, (bool), (override)); + MOCK_METHOD(std::unique_ptr>, + ComputePlatformResolvedLocale, + (const std::vector&), + (override)); + MOCK_METHOD(void, RequestDartDeferredLibrary, (intptr_t), (override)); + MOCK_METHOD(fml::TimePoint, GetCurrentTimePoint, (), (override)); + MOCK_METHOD(const std::shared_ptr&, + GetPlatformMessageHandler, + (), + (const, override)); + MOCK_METHOD(void, OnEngineChannelUpdate, (std::string, bool), (override)); + MOCK_METHOD(double, + GetScaledFontSize, + (double font_size, int configuration_id), + (const, override)); + MOCK_METHOD(void, + RequestViewFocusChange, + (const ViewFocusChangeRequest&), + (override)); +}; + +class MockResponse : public PlatformMessageResponse { + public: + MOCK_METHOD(void, Complete, (std::unique_ptr data), (override)); + MOCK_METHOD(void, CompleteEmpty, (), (override)); +}; + +class MockRuntimeDelegate : public RuntimeDelegate { + public: + MOCK_METHOD(std::string, DefaultRouteName, (), (override)); + MOCK_METHOD(void, ScheduleFrame, (bool), (override)); + MOCK_METHOD(void, OnAllViewsRendered, (), (override)); + MOCK_METHOD(void, + Render, + (int64_t, std::unique_ptr, float), + (override)); + MOCK_METHOD(void, + UpdateSemantics, + (int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates), + (override)); + MOCK_METHOD(void, + HandlePlatformMessage, + (std::unique_ptr), + (override)); + MOCK_METHOD(FontCollection&, GetFontCollection, (), (override)); + MOCK_METHOD(std::shared_ptr, GetAssetManager, (), (override)); + MOCK_METHOD(void, OnRootIsolateCreated, (), (override)); + MOCK_METHOD(void, + UpdateIsolateDescription, + (const std::string, int64_t), + (override)); + MOCK_METHOD(void, SetNeedsReportTimings, (bool), (override)); + MOCK_METHOD(std::unique_ptr>, + ComputePlatformResolvedLocale, + (const std::vector&), + (override)); + MOCK_METHOD(void, RequestDartDeferredLibrary, (intptr_t), (override)); + MOCK_METHOD(std::weak_ptr, + GetPlatformMessageHandler, + (), + (const, override)); + MOCK_METHOD(void, SendChannelUpdate, (std::string, bool), (override)); + MOCK_METHOD(double, + GetScaledFontSize, + (double font_size, int configuration_id), + (const, override)); + MOCK_METHOD(void, + RequestViewFocusChange, + (const ViewFocusChangeRequest&), + (override)); +}; + +class MockRuntimeController : public RuntimeController { + public: + MockRuntimeController(RuntimeDelegate& client, + const TaskRunners& p_task_runners) + : RuntimeController(client, p_task_runners) {} + MOCK_METHOD(bool, IsRootIsolateRunning, (), (override, const)); + MOCK_METHOD(bool, + DispatchPlatformMessage, + (std::unique_ptr), + (override)); + MOCK_METHOD(void, + LoadDartDeferredLibraryError, + (intptr_t, const std::string, bool), + (override)); + MOCK_METHOD(DartVM*, GetDartVM, (), (const, override)); + MOCK_METHOD(bool, NotifyIdle, (fml::TimeDelta), (override)); +}; + +class MockFontCollection : public FontCollection { + public: + MOCK_METHOD(void, + RegisterFonts, + (const std::shared_ptr& asset_manager), + (override)); +}; + +std::unique_ptr MakePlatformMessage( + const std::string& channel, + const std::map& values, + const fml::RefPtr& response) { + rapidjson::Document document; + auto& allocator = document.GetAllocator(); + document.SetObject(); + + for (const auto& pair : values) { + rapidjson::Value key(pair.first.c_str(), strlen(pair.first.c_str()), + allocator); + rapidjson::Value value(pair.second.c_str(), strlen(pair.second.c_str()), + allocator); + document.AddMember(key, value, allocator); + } + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + const uint8_t* data = reinterpret_cast(buffer.GetString()); + + std::unique_ptr message = std::make_unique( + channel, fml::MallocMapping::Copy(data, buffer.GetSize()), response); + return message; +} + +class EngineTest : public testing::FixtureTest { + public: + EngineTest() + : thread_host_("EngineTest", + ThreadHost::Type::kPlatform | ThreadHost::Type::kIo | + ThreadHost::Type::kUi | ThreadHost::Type::kRaster), + task_runners_({ + "EngineTest", + thread_host_.platform_thread->GetTaskRunner(), // platform + thread_host_.raster_thread->GetTaskRunner(), // raster + thread_host_.ui_thread->GetTaskRunner(), // ui + thread_host_.io_thread->GetTaskRunner() // io + }) {} + + void PostUITaskSync(const std::function& function) { + fml::AutoResetWaitableEvent latch; + task_runners_.GetUITaskRunner()->PostTask([&] { + function(); + latch.Signal(); + }); + latch.Wait(); + } + + protected: + void SetUp() override { + settings_ = CreateSettingsForFixture(); + dispatcher_maker_ = [](PointerDataDispatcher::Delegate&) { + return nullptr; + }; + } + + MockDelegate delegate_; + PointerDataDispatcherMaker dispatcher_maker_; + ThreadHost thread_host_; + TaskRunners task_runners_; + Settings settings_; + std::unique_ptr animator_; + fml::WeakPtr io_manager_; + std::unique_ptr runtime_controller_; + std::shared_ptr image_decoder_task_runner_; + fml::TaskRunnerAffineWeakPtr snapshot_delegate_; +}; +} // namespace + +TEST_F(EngineTest, Create) { + PostUITaskSync([this] { + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/std::make_shared(), + /*runtime_controller=*/std::move(runtime_controller_), + /*gpu_disabled_switch=*/std::make_shared()); + EXPECT_TRUE(engine); + }); +} + +TEST_F(EngineTest, DispatchPlatformMessageUnknown) { + PostUITaskSync([this] { + MockRuntimeDelegate client; + auto mock_runtime_controller = + std::make_unique(client, task_runners_); + EXPECT_CALL(*mock_runtime_controller, IsRootIsolateRunning()) + .WillRepeatedly(::testing::Return(false)); + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/std::make_shared(), + /*runtime_controller=*/std::move(mock_runtime_controller), + /*gpu_disabled_switch=*/std::make_shared()); + + fml::RefPtr response = + fml::MakeRefCounted(); + std::unique_ptr message = + std::make_unique("foo", response); + engine->DispatchPlatformMessage(std::move(message)); + }); +} + +TEST_F(EngineTest, DispatchPlatformMessageInitialRoute) { + PostUITaskSync([this] { + MockRuntimeDelegate client; + auto mock_runtime_controller = + std::make_unique(client, task_runners_); + EXPECT_CALL(*mock_runtime_controller, IsRootIsolateRunning()) + .WillRepeatedly(::testing::Return(false)); + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/std::make_shared(), + /*runtime_controller=*/std::move(mock_runtime_controller), + /*gpu_disabled_switch=*/std::make_shared()); + + fml::RefPtr response = + fml::MakeRefCounted(); + std::map values{ + {"method", "setInitialRoute"}, + {"args", "test_initial_route"}, + }; + std::unique_ptr message = + MakePlatformMessage("flutter/navigation", values, response); + engine->DispatchPlatformMessage(std::move(message)); + EXPECT_EQ(engine->InitialRoute(), "test_initial_route"); + }); +} + +TEST_F(EngineTest, DispatchPlatformMessageInitialRouteIgnored) { + PostUITaskSync([this] { + MockRuntimeDelegate client; + auto mock_runtime_controller = + std::make_unique(client, task_runners_); + EXPECT_CALL(*mock_runtime_controller, IsRootIsolateRunning()) + .WillRepeatedly(::testing::Return(true)); + EXPECT_CALL(*mock_runtime_controller, DispatchPlatformMessage(::testing::_)) + .WillRepeatedly(::testing::Return(true)); + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/std::make_shared(), + /*runtime_controller=*/std::move(mock_runtime_controller), + /*gpu_disabled_switch=*/std::make_shared()); + + fml::RefPtr response = + fml::MakeRefCounted(); + std::map values{ + {"method", "setInitialRoute"}, + {"args", "test_initial_route"}, + }; + std::unique_ptr message = + MakePlatformMessage("flutter/navigation", values, response); + engine->DispatchPlatformMessage(std::move(message)); + EXPECT_EQ(engine->InitialRoute(), ""); + }); +} + +TEST_F(EngineTest, SpawnSharesFontLibrary) { + PostUITaskSync([this] { + MockRuntimeDelegate client; + auto mock_runtime_controller = + std::make_unique(client, task_runners_); + auto vm_ref = DartVMRef::Create(settings_); + EXPECT_CALL(*mock_runtime_controller, GetDartVM()) + .WillRepeatedly(::testing::Return(vm_ref.get())); + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/std::make_shared(), + /*runtime_controller=*/std::move(mock_runtime_controller), + /*gpu_disabled_switch=*/std::make_shared()); + + auto spawn = + engine->Spawn(delegate_, dispatcher_maker_, settings_, nullptr, + std::string(), io_manager_, snapshot_delegate_, nullptr); + EXPECT_TRUE(spawn != nullptr); + EXPECT_EQ(&engine->GetFontCollection(), &spawn->GetFontCollection()); + }); +} + +TEST_F(EngineTest, SpawnWithCustomInitialRoute) { + PostUITaskSync([this] { + MockRuntimeDelegate client; + auto mock_runtime_controller = + std::make_unique(client, task_runners_); + auto vm_ref = DartVMRef::Create(settings_); + EXPECT_CALL(*mock_runtime_controller, GetDartVM()) + .WillRepeatedly(::testing::Return(vm_ref.get())); + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/std::make_shared(), + /*runtime_controller=*/std::move(mock_runtime_controller), + /*gpu_disabled_switch=*/std::make_shared()); + + auto spawn = + engine->Spawn(delegate_, dispatcher_maker_, settings_, nullptr, "/foo", + io_manager_, snapshot_delegate_, nullptr); + EXPECT_TRUE(spawn != nullptr); + ASSERT_EQ("/foo", spawn->InitialRoute()); + }); +} + +TEST_F(EngineTest, SpawnWithCustomSettings) { + PostUITaskSync([this] { + MockRuntimeDelegate client; + auto mock_runtime_controller = + std::make_unique(client, task_runners_); + auto vm_ref = DartVMRef::Create(settings_); + EXPECT_CALL(*mock_runtime_controller, GetDartVM()) + .WillRepeatedly(::testing::Return(vm_ref.get())); + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/std::make_shared(), + /*runtime_controller=*/std::move(mock_runtime_controller), + /*gpu_disabled_switch=*/std::make_shared()); + + Settings custom_settings = settings_; + custom_settings.persistent_isolate_data = + std::make_shared("foo"); + auto spawn = + engine->Spawn(delegate_, dispatcher_maker_, custom_settings, nullptr, + std::string(), io_manager_, snapshot_delegate_, nullptr); + EXPECT_TRUE(spawn != nullptr); + auto new_persistent_isolate_data = + const_cast(spawn->GetRuntimeController()) + ->GetPersistentIsolateData(); + EXPECT_EQ(custom_settings.persistent_isolate_data->GetMapping(), + new_persistent_isolate_data->GetMapping()); + EXPECT_EQ(custom_settings.persistent_isolate_data->GetSize(), + new_persistent_isolate_data->GetSize()); + }); +} + +TEST_F(EngineTest, PassesLoadDartDeferredLibraryErrorToRuntime) { + PostUITaskSync([this] { + intptr_t error_id = 123; + const std::string error_message = "error message"; + MockRuntimeDelegate client; + auto mock_runtime_controller = + std::make_unique(client, task_runners_); + EXPECT_CALL(*mock_runtime_controller, IsRootIsolateRunning()) + .WillRepeatedly(::testing::Return(true)); + EXPECT_CALL(*mock_runtime_controller, + LoadDartDeferredLibraryError(error_id, error_message, true)) + .Times(1); + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/std::make_shared(), + /*runtime_controller=*/std::move(mock_runtime_controller), + /*gpu_disabled_switch=*/std::make_shared()); + + engine->LoadDartDeferredLibraryError(error_id, error_message, true); + }); +} + +TEST_F(EngineTest, SpawnedEngineInheritsAssetManager) { + PostUITaskSync([this] { + MockRuntimeDelegate client; + auto mock_runtime_controller = + std::make_unique(client, task_runners_); + auto vm_ref = DartVMRef::Create(settings_); + EXPECT_CALL(*mock_runtime_controller, GetDartVM()) + .WillRepeatedly(::testing::Return(vm_ref.get())); + + // auto mock_font_collection = std::make_shared(); + // EXPECT_CALL(*mock_font_collection, RegisterFonts(::testing::_)) + // .WillOnce(::testing::Return()); + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/std::make_shared(), + /*runtime_controller=*/std::move(mock_runtime_controller), + /*gpu_disabled_switch=*/std::make_shared()); + + EXPECT_EQ(engine->GetAssetManager(), nullptr); + + auto asset_manager = std::make_shared(); + asset_manager->PushBack(std::make_unique()); + engine->UpdateAssetManager(asset_manager); + EXPECT_EQ(engine->GetAssetManager(), asset_manager); + + auto spawn = + engine->Spawn(delegate_, dispatcher_maker_, settings_, nullptr, + std::string(), io_manager_, snapshot_delegate_, nullptr); + EXPECT_TRUE(spawn != nullptr); + EXPECT_EQ(engine->GetAssetManager(), spawn->GetAssetManager()); + }); +} + +TEST_F(EngineTest, UpdateAssetManagerWithEqualManagers) { + PostUITaskSync([this] { + MockRuntimeDelegate client; + auto mock_runtime_controller = + std::make_unique(client, task_runners_); + auto vm_ref = DartVMRef::Create(settings_); + EXPECT_CALL(*mock_runtime_controller, GetDartVM()) + .WillRepeatedly(::testing::Return(vm_ref.get())); + + auto mock_font_collection = std::make_shared(); + EXPECT_CALL(*mock_font_collection, RegisterFonts(::testing::_)) + .WillOnce(::testing::Return()); + auto engine = std::make_unique( + /*delegate=*/delegate_, + /*dispatcher_maker=*/dispatcher_maker_, + /*image_decoder_task_runner=*/image_decoder_task_runner_, + /*task_runners=*/task_runners_, + /*settings=*/settings_, + /*animator=*/std::move(animator_), + /*io_manager=*/io_manager_, + /*font_collection=*/mock_font_collection, + /*runtime_controller=*/std::move(mock_runtime_controller), + /*gpu_disabled_switch=*/std::make_shared()); + + EXPECT_EQ(engine->GetAssetManager(), nullptr); + + auto asset_manager = std::make_shared(); + asset_manager->PushBack(std::make_unique()); + + auto asset_manager_2 = std::make_shared(); + asset_manager_2->PushBack(std::make_unique()); + + EXPECT_NE(asset_manager, asset_manager_2); + EXPECT_TRUE(*asset_manager == *asset_manager_2); + + engine->UpdateAssetManager(asset_manager); + EXPECT_EQ(engine->GetAssetManager(), asset_manager); + + engine->UpdateAssetManager(asset_manager_2); + // Didn't change because they're equivalent. + EXPECT_EQ(engine->GetAssetManager(), asset_manager); + }); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/input_events_unittests.cc b/flutter/engine/src/flutter/shell/common/input_events_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..a0a22d14ded42f946a6ee78d4a10e27dafe53c1a --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/input_events_unittests.cc @@ -0,0 +1,446 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/shell_test.h" +#include "flutter/testing/testing.h" + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace flutter { +namespace testing { + +// Throughout these tests, the choice of time unit is irrelevant as long as all +// times have the same units. +using UnitlessTime = int; + +// Signature of a generator function that takes the frame index as input and +// returns the time of that frame. +using Generator = std::function; + +namespace { + +constexpr int64_t kImplicitViewId = 0; + +} + +//---------------------------------------------------------------------------- +/// Simulate n input events where the i-th one is delivered at delivery_time(i). +/// +/// Simulation results will be written into events_consumed_at_frame whose +/// length will be equal to the number of frames drawn. Each element in the +/// vector is the number of input events consumed up to that frame. (We can't +/// return such vector because ASSERT_TRUE requires return type of void.) +/// +/// We assume (and check) that the delivery latency is some base latency plus a +/// random latency where the random latency must be within one frame: +/// +/// 1. latency = delivery_time(i) - j * frame_time = base_latency + +/// random_latency +/// 2. 0 <= base_latency, 0 <= random_latency < frame_time +/// +/// We also assume that there will be at least one input event per frame if +/// there were no latency. Let j = floor( (delivery_time(i) - base_latency) / +/// frame_time ) be the frame index if there were no latency. Then the set of j +/// should be all integers from 0 to continuous_frame_count - 1 for some +/// integer continuous_frame_count. +/// +/// (Note that there coulds be multiple input events within one frame.) +/// +/// The test here is insensitive to the choice of time unit as long as +/// delivery_time and frame_time are in the same unit. +static void TestSimulatedInputEvents( + ShellTest* fixture, + int num_events, + UnitlessTime base_latency, + Generator delivery_time, + UnitlessTime frame_time, + std::vector& events_consumed_at_frame, + bool restart_engine = false) { + ///// Begin constructing shell /////////////////////////////////////////////// + auto settings = fixture->CreateSettingsForFixture(); + std::unique_ptr shell = fixture->CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .simulate_vsync = true, + }), + }); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("onPointerDataPacketMain"); + + // The following 4 variables are only accessed in the UI thread by + // nativeOnPointerDataPacket and nativeOnBeginFrame between their + // initializations and `shell.reset()`. + events_consumed_at_frame.clear(); + bool will_draw_new_frame = true; + int events_consumed = 0; + int frame_drawn = 0; + auto nativeOnPointerDataPacket = [&events_consumed_at_frame, + &will_draw_new_frame, &events_consumed, + &frame_drawn](Dart_NativeArguments args) { + events_consumed += 1; + if (will_draw_new_frame) { + frame_drawn += 1; + will_draw_new_frame = false; + events_consumed_at_frame.push_back(events_consumed); + } else { + events_consumed_at_frame.back() = events_consumed; + } + }; + fixture->AddNativeCallback("NativeOnPointerDataPacket", + CREATE_NATIVE_ENTRY(nativeOnPointerDataPacket)); + + ASSERT_TRUE(configuration.IsValid()); + fixture->RunEngine(shell.get(), std::move(configuration)); + + if (restart_engine) { + auto new_configuration = RunConfiguration::InferFromSettings(settings); + new_configuration.SetEntrypoint("onPointerDataPacketMain"); + ASSERT_TRUE(new_configuration.IsValid()); + fixture->RestartEngine(shell.get(), std::move(new_configuration)); + } + ///// End constructing shell ///////////////////////////////////////////////// + + ASSERT_GE(base_latency, 0); + + // Check that delivery_time satisfies our assumptions. + int continuous_frame_count = 0; + for (int i = 0; i < num_events; i += 1) { + // j is the frame index of event i if there were no latency. + int j = static_cast((delivery_time(i) - base_latency) / frame_time); + if (j == continuous_frame_count) { + continuous_frame_count += 1; + } + double random_latency = delivery_time(i) - j * frame_time - base_latency; + ASSERT_GE(random_latency, 0); + ASSERT_LT(random_latency, frame_time); + + // If there were no latency, there should be at least one event per frame. + // Hence j should never skip any integer less than continuous_frame_count. + ASSERT_LT(j, continuous_frame_count); + } + + // This has to be running on a different thread than Platform thread to avoid + // dead locks. + auto simulation = std::async(std::launch::async, [&]() { + // i is the input event's index. + // j is the frame's index. + for (int i = 0, j = 0; i < num_events; j += 1) { + double t = j * frame_time; + while (i < num_events && delivery_time(i) <= t) { + // Use a different x every time for the pointer data converter to + // generate non-empty events. + ShellTest::DispatchFakePointerData(shell.get(), /*x=*/i); + i += 1; + } + ShellTest::VSyncFlush(shell.get(), &will_draw_new_frame); + } + // Finally, issue a vsync for the pending event that may be generated duing + // the last vsync. + ShellTest::VSyncFlush(shell.get(), &will_draw_new_frame); + }); + + simulation.wait(); + + TaskRunners task_runners = fixture->GetTaskRunnersForFixture(); + fml::AutoResetWaitableEvent latch; + task_runners.GetPlatformTaskRunner()->PostTask([&shell, &latch]() mutable { + shell.reset(); + latch.Signal(); + }); + latch.Wait(); + + // Make sure that all events have been consumed so + // https://github.com/flutter/flutter/issues/40863 won't happen again. + ASSERT_GT(events_consumed_at_frame.size(), 0u); + ASSERT_EQ(events_consumed_at_frame.back(), num_events); +} + +void CreateSimulatedPointerData(PointerData& data, + PointerData::Change change, + double dx, + double dy) { + data.time_stamp = 0; + data.change = change; + data.kind = PointerData::DeviceKind::kTouch; + data.signal_kind = PointerData::SignalKind::kNone; + data.device = 0; + data.pointer_identifier = 0; + data.physical_x = dx; + data.physical_y = dy; + data.physical_delta_x = 0.0; + data.physical_delta_y = 0.0; + data.buttons = 0; + data.obscured = 0; + data.synthesized = 0; + data.pressure = 0.0; + data.pressure_min = 0.0; + data.pressure_max = 0.0; + data.distance = 0.0; + data.distance_max = 0.0; + data.size = 0.0; + data.radius_major = 0.0; + data.radius_minor = 0.0; + data.radius_min = 0.0; + data.radius_max = 0.0; + data.orientation = 0.0; + data.tilt = 0.0; + data.platformData = 0; + data.scroll_delta_x = 0.0; + data.scroll_delta_y = 0.0; + data.view_id = kImplicitViewId; +} + +TEST_F(ShellTest, MissAtMostOneFrameForIrregularInputEvents) { + // We don't use `constexpr int frame_time` here because MSVC doesn't handle + // it well with lambda capture. + UnitlessTime frame_time = 10; + UnitlessTime base_latency = 0.5 * frame_time; + Generator extreme = [frame_time, base_latency](int i) { + return static_cast( + i * frame_time + base_latency + + (i % 2 == 0 ? 0.1 * frame_time : 0.9 * frame_time)); + }; + constexpr int n = 40; + std::vector events_consumed_at_frame; + TestSimulatedInputEvents(this, n, base_latency, extreme, frame_time, + events_consumed_at_frame); + int frame_drawn = events_consumed_at_frame.size(); + ASSERT_GE(frame_drawn, n - 1); + + // Make sure that it also works after an engine restart. + TestSimulatedInputEvents(this, n, base_latency, extreme, frame_time, + events_consumed_at_frame, true /* restart_engine */); + int frame_drawn_after_restart = events_consumed_at_frame.size(); + ASSERT_GE(frame_drawn_after_restart, n - 1); +} + +TEST_F(ShellTest, DelayAtMostOneEventForFasterThanVSyncInputEvents) { + // We don't use `constexpr int frame_time` here because MSVC doesn't handle + // it well with lambda capture. + UnitlessTime frame_time = 10; + UnitlessTime base_latency = 0.2 * frame_time; + Generator double_sampling = [frame_time, base_latency](int i) { + return static_cast(i * 0.5 * frame_time + base_latency); + }; + constexpr int n = 40; + std::vector events_consumed_at_frame; + TestSimulatedInputEvents(this, n, base_latency, double_sampling, frame_time, + events_consumed_at_frame); + + // Draw one extra frame due to delaying a pending packet for the next frame. + int frame_drawn = events_consumed_at_frame.size(); + ASSERT_EQ(frame_drawn, n / 2 + 1); + + for (int i = 0; i < n / 2; i += 1) { + ASSERT_GE(events_consumed_at_frame[i], 2 * i - 1); + } +} + +TEST_F(ShellTest, HandlesActualIphoneXsInputEvents) { + // Actual delivery times measured on iPhone Xs, in the unit of frame_time + // (16.67ms for 60Hz). + static constexpr double iphone_xs_times[] = {0.15, + 1.0773046874999999, + 2.1738720703124996, + 3.0579052734374996, + 4.0890087890624995, + 5.0952685546875, + 6.1251708984375, + 7.1253076171875, + 8.125927734374999, + 9.37248046875, + 10.133950195312499, + 11.161201171875, + 12.226992187499999, + 13.1443798828125, + 14.440327148437499, + 15.091684570312498, + 16.138681640625, + 17.126469726562497, + 18.1592431640625, + 19.371372070312496, + 20.033774414062496, + 21.021782226562497, + 22.070053710937497, + 23.325541992187496, + 24.119648437499997, + 25.084262695312496, + 26.077866210937497, + 27.036547851562496, + 28.035073242187497, + 29.081411132812498, + 30.066064453124998, + 31.089360351562497, + 32.086142578125, + 33.4618798828125, + 34.14697265624999, + 35.0513525390625, + 36.136025390624994, + 37.1618408203125, + 38.144472656249995, + 39.201123046875, + 40.4339501953125, + 41.1552099609375, + 42.102128906249995, + 43.0426318359375, + 44.070131835937495, + 45.08862304687499, + 46.091469726562494}; + constexpr int n = sizeof(iphone_xs_times) / sizeof(iphone_xs_times[0]); + // We don't use `constexpr int frame_time` here because MSVC doesn't handle + // it well with lambda capture. + UnitlessTime frame_time = 10000; + double base_latency_f = 0.0; + for (int i = 0; i < 10; i++) { + base_latency_f += 0.1; + // Everything is converted to int to avoid floating point error in + // TestSimulatedInputEvents. + UnitlessTime base_latency = + static_cast(base_latency_f * frame_time); + Generator iphone_xs_generator = [frame_time, base_latency](int i) { + return base_latency + + static_cast(iphone_xs_times[i] * frame_time); + }; + std::vector events_consumed_at_frame; + TestSimulatedInputEvents(this, n, base_latency, iphone_xs_generator, + frame_time, events_consumed_at_frame); + int frame_drawn = events_consumed_at_frame.size(); + ASSERT_GE(frame_drawn, n - 1); + } +} + +TEST_F(ShellTest, CanCorrectlyPipePointerPacket) { + // Sets up shell with test fixture. + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .simulate_vsync = true, + }), + }); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("onPointerDataPacketMain"); + // Sets up native handler. + fml::AutoResetWaitableEvent reportLatch; + std::vector result_sequence; + auto nativeOnPointerDataPacket = [&reportLatch, &result_sequence]( + Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + result_sequence = tonic::DartConverter>::FromArguments( + args, 0, exception); + reportLatch.Signal(); + }; + // Starts engine. + AddNativeCallback("NativeOnPointerDataPacket", + CREATE_NATIVE_ENTRY(nativeOnPointerDataPacket)); + ASSERT_TRUE(configuration.IsValid()); + RunEngine(shell.get(), std::move(configuration)); + // Starts test. + auto packet = std::make_unique(6); + PointerData data; + CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0.0, 0.0); + packet->SetPointerData(0, data); + CreateSimulatedPointerData(data, PointerData::Change::kHover, 3.0, 0.0); + packet->SetPointerData(1, data); + CreateSimulatedPointerData(data, PointerData::Change::kDown, 3.0, 0.0); + packet->SetPointerData(2, data); + CreateSimulatedPointerData(data, PointerData::Change::kMove, 3.0, 4.0); + packet->SetPointerData(3, data); + CreateSimulatedPointerData(data, PointerData::Change::kUp, 3.0, 4.0); + packet->SetPointerData(4, data); + CreateSimulatedPointerData(data, PointerData::Change::kRemove, 3.0, 4.0); + packet->SetPointerData(5, data); + ShellTest::DispatchPointerData(shell.get(), std::move(packet)); + ShellTest::VSyncFlush(shell.get()); + + reportLatch.Wait(); + size_t expect_length = 6; + ASSERT_EQ(result_sequence.size(), expect_length); + ASSERT_EQ(PointerData::Change(result_sequence[0]), PointerData::Change::kAdd); + ASSERT_EQ(PointerData::Change(result_sequence[1]), + PointerData::Change::kHover); + ASSERT_EQ(PointerData::Change(result_sequence[2]), + PointerData::Change::kDown); + ASSERT_EQ(PointerData::Change(result_sequence[3]), + PointerData::Change::kMove); + ASSERT_EQ(PointerData::Change(result_sequence[4]), PointerData::Change::kUp); + ASSERT_EQ(PointerData::Change(result_sequence[5]), + PointerData::Change::kRemove); + + // Cleans up shell. + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell)); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, CanCorrectlySynthesizePointerPacket) { + // Sets up shell with test fixture. + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .simulate_vsync = true, + }), + }); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("onPointerDataPacketMain"); + // Sets up native handler. + fml::AutoResetWaitableEvent reportLatch; + std::vector result_sequence; + auto nativeOnPointerDataPacket = [&reportLatch, &result_sequence]( + Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + result_sequence = tonic::DartConverter>::FromArguments( + args, 0, exception); + reportLatch.Signal(); + }; + // Starts engine. + AddNativeCallback("NativeOnPointerDataPacket", + CREATE_NATIVE_ENTRY(nativeOnPointerDataPacket)); + ASSERT_TRUE(configuration.IsValid()); + RunEngine(shell.get(), std::move(configuration)); + // Starts test. + auto packet = std::make_unique(4); + PointerData data; + CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0.0, 0.0); + packet->SetPointerData(0, data); + CreateSimulatedPointerData(data, PointerData::Change::kDown, 3.0, 0.0); + packet->SetPointerData(1, data); + CreateSimulatedPointerData(data, PointerData::Change::kUp, 3.0, 4.0); + packet->SetPointerData(2, data); + CreateSimulatedPointerData(data, PointerData::Change::kRemove, 3.0, 4.0); + packet->SetPointerData(3, data); + ShellTest::DispatchPointerData(shell.get(), std::move(packet)); + ShellTest::VSyncFlush(shell.get()); + + reportLatch.Wait(); + size_t expect_length = 6; + ASSERT_EQ(result_sequence.size(), expect_length); + ASSERT_EQ(PointerData::Change(result_sequence[0]), PointerData::Change::kAdd); + // The pointer data packet converter should synthesize a hover event. + ASSERT_EQ(PointerData::Change(result_sequence[1]), + PointerData::Change::kHover); + ASSERT_EQ(PointerData::Change(result_sequence[2]), + PointerData::Change::kDown); + // The pointer data packet converter should synthesize a move event. + ASSERT_EQ(PointerData::Change(result_sequence[3]), + PointerData::Change::kMove); + ASSERT_EQ(PointerData::Change(result_sequence[4]), PointerData::Change::kUp); + ASSERT_EQ(PointerData::Change(result_sequence[5]), + PointerData::Change::kRemove); + + // Cleans up shell. + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell)); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +} // namespace testing +} // namespace flutter + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/common/persistent_cache_unittests.cc b/flutter/engine/src/flutter/shell/common/persistent_cache_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..427da231efed07ad9043a288489d0ea94933c514 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/persistent_cache_unittests.cc @@ -0,0 +1,203 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/common/graphics/persistent_cache.h" + +#include + +#include "flutter/assets/directory_asset_bundle.h" +#include "flutter/flow/layers/container_layer.h" +#include "flutter/flow/layers/layer.h" +#include "flutter/fml/command_line.h" +#include "flutter/fml/file.h" +#include "flutter/fml/log_settings.h" +#include "flutter/fml/unique_fd.h" +#include "flutter/shell/common/shell_test.h" +#include "flutter/shell/common/switches.h" +#include "flutter/shell/version/version.h" +#include "flutter/testing/testing.h" + +namespace flutter { +namespace testing { + +using PersistentCacheTest = ShellTest; + +static void CheckTextSkData(const sk_sp& data, + const std::string& expected) { + std::string data_string(reinterpret_cast(data->bytes()), + data->size()); + ASSERT_EQ(data_string, expected); +} + +static void ResetAssetManager() { + PersistentCache::SetAssetManager(nullptr); + ASSERT_EQ(PersistentCache::GetCacheForProcess()->LoadSkSLs().size(), 0u); +} + +static void CheckTwoSkSLsAreLoaded() { + auto shaders = PersistentCache::GetCacheForProcess()->LoadSkSLs(); + ASSERT_EQ(shaders.size(), 2u); +} + +TEST_F(PersistentCacheTest, CanLoadSkSLsFromAsset) { + // Avoid polluting unit tests output by hiding INFO level logging. + fml::LogSettings warning_only = {fml::kLogWarning}; + fml::ScopedSetLogSettings scoped_set_log_settings(warning_only); + + // The SkSL key is Base32 encoded. "IE" is the encoding of "A" and "II" is the + // encoding of "B". + // + // The SkSL data is Base64 encoded. "eA==" is the encoding of "x" and "eQ==" + // is the encoding of "y". + const std::string kTestJson = + "{\n" + " \"data\": {\n" + " \"IE\": \"eA==\",\n" + " \"II\": \"eQ==\"\n" + " }\n" + "}\n"; + + // Temp dir for the asset. + fml::ScopedTemporaryDirectory asset_dir; + + auto data = std::make_unique( + std::vector{kTestJson.begin(), kTestJson.end()}); + fml::WriteAtomically(asset_dir.fd(), PersistentCache::kAssetFileName, *data); + + // 1st, test that RunConfiguration::InferFromSettings sets the asset manager. + ResetAssetManager(); + auto settings = CreateSettingsForFixture(); + settings.assets_path = asset_dir.path(); + RunConfiguration::InferFromSettings(settings); + CheckTwoSkSLsAreLoaded(); + + // 2nd, test that the RunConfiguration constructor sets the asset manager. + // (Android is directly calling that constructor without InferFromSettings.) + ResetAssetManager(); + auto asset_manager = std::make_shared(); + RunConfiguration config(nullptr, asset_manager); + asset_manager->PushBack(std::make_unique( + fml::OpenDirectory(asset_dir.path().c_str(), false, + fml::FilePermission::kRead), + false)); + CheckTwoSkSLsAreLoaded(); + + // 3rd, test the content of the SkSLs in the asset. + { + auto shaders = PersistentCache::GetCacheForProcess()->LoadSkSLs(); + ASSERT_EQ(shaders.size(), 2u); + + // Make sure that the 2 shaders are sorted by their keys. Their keys should + // be "A" and "B" (decoded from "II" and "IE"). + if (shaders[0].key->bytes()[0] == 'B') { + std::swap(shaders[0], shaders[1]); + } + + CheckTextSkData(shaders[0].key, "A"); + CheckTextSkData(shaders[1].key, "B"); + CheckTextSkData(shaders[0].value, "x"); + CheckTextSkData(shaders[1].value, "y"); + } + + // Cleanup. + fml::UnlinkFile(asset_dir.fd(), PersistentCache::kAssetFileName); +} + +TEST_F(PersistentCacheTest, CanRemoveOldPersistentCache) { + fml::ScopedTemporaryDirectory base_dir; + ASSERT_TRUE(base_dir.fd().is_valid()); + + fml::CreateDirectory(base_dir.fd(), + {"flutter_engine", GetFlutterEngineVersion(), "skia"}, + fml::FilePermission::kReadWrite); + + constexpr char kOldEngineVersion[] = "old"; + auto old_created = fml::CreateDirectory( + base_dir.fd(), {"flutter_engine", kOldEngineVersion, "skia"}, + fml::FilePermission::kReadWrite); + ASSERT_TRUE(old_created.is_valid()); + + PersistentCache::SetCacheDirectoryPath(base_dir.path()); + PersistentCache::ResetCacheForProcess(); + + auto engine_dir = fml::OpenDirectoryReadOnly(base_dir.fd(), "flutter_engine"); + auto current_dir = + fml::OpenDirectoryReadOnly(engine_dir, GetFlutterEngineVersion()); + auto old_dir = fml::OpenDirectoryReadOnly(engine_dir, kOldEngineVersion); + + ASSERT_TRUE(engine_dir.is_valid()); + ASSERT_TRUE(current_dir.is_valid()); + ASSERT_FALSE(old_dir.is_valid()); + + // Cleanup + fml::RemoveFilesInDirectory(base_dir.fd()); +} + +TEST_F(PersistentCacheTest, CanPurgePersistentCache) { + fml::ScopedTemporaryDirectory base_dir; + ASSERT_TRUE(base_dir.fd().is_valid()); + auto cache_dir = fml::CreateDirectory( + base_dir.fd(), + {"flutter_engine", GetFlutterEngineVersion(), "skia", GetSkiaVersion()}, + fml::FilePermission::kReadWrite); + PersistentCache::SetCacheDirectoryPath(base_dir.path()); + PersistentCache::ResetCacheForProcess(); + + // Generate a dummy persistent cache. + fml::DataMapping test_data(std::string("test")); + ASSERT_TRUE(fml::WriteAtomically(cache_dir, "test", test_data)); + auto file = fml::OpenFileReadOnly(cache_dir, "test"); + ASSERT_TRUE(file.is_valid()); + + // Run engine with purge_persistent_cache to remove the dummy cache. + auto settings = CreateSettingsForFixture(); + settings.purge_persistent_cache = true; + auto config = RunConfiguration::InferFromSettings(settings); + std::unique_ptr shell = CreateShell(settings); + RunEngine(shell.get(), std::move(config)); + + // Verify that the dummy is purged. + file = fml::OpenFileReadOnly(cache_dir, "test"); + ASSERT_FALSE(file.is_valid()); + + // Cleanup + fml::RemoveFilesInDirectory(base_dir.fd()); + DestroyShell(std::move(shell)); +} + +TEST_F(PersistentCacheTest, PurgeAllowsFutureSkSLCache) { + sk_sp shader_key = SkData::MakeWithCString("key"); + sk_sp shader_value = SkData::MakeWithCString("value"); + std::string shader_filename = PersistentCache::SkKeyToFilePath(*shader_key); + + fml::ScopedTemporaryDirectory base_dir; + ASSERT_TRUE(base_dir.fd().is_valid()); + PersistentCache::SetCacheDirectoryPath(base_dir.path()); + PersistentCache::ResetCacheForProcess(); + + // Run engine with purge_persistent_cache and cache_sksl. + auto settings = CreateSettingsForFixture(); + settings.purge_persistent_cache = true; + settings.cache_sksl = true; + auto config = RunConfiguration::InferFromSettings(settings); + std::unique_ptr shell = CreateShell(settings); + RunEngine(shell.get(), std::move(config)); + auto persistent_cache = PersistentCache::GetCacheForProcess(); + ASSERT_EQ(persistent_cache->LoadSkSLs().size(), 0u); + + // Store the cache and verify it's valid. + StorePersistentCache(persistent_cache, *shader_key, *shader_value); + std::promise io_flushed; + shell->GetTaskRunners().GetIOTaskRunner()->PostTask( + [&io_flushed]() { io_flushed.set_value(true); }); + io_flushed.get_future().get(); // Wait for the IO thread to flush the file. + ASSERT_GT(persistent_cache->LoadSkSLs().size(), 0u); + + // Cleanup + fml::RemoveFilesInDirectory(base_dir.fd()); + DestroyShell(std::move(shell)); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/pipeline.cc b/flutter/engine/src/flutter/shell/common/pipeline.cc new file mode 100644 index 0000000000000000000000000000000000000000..fb80c187181fdb1c4bec3b64568e1a1429b43d5e --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/pipeline.cc @@ -0,0 +1,14 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/pipeline.h" + +namespace flutter { + +size_t GetNextPipelineTraceID() { + static std::atomic_size_t PipelineLastTraceID = {0}; + return ++PipelineLastTraceID; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/pipeline.h b/flutter/engine/src/flutter/shell/common/pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..2657d96689a2319abd143a427d8a7871d62d3b51 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/pipeline.h @@ -0,0 +1,260 @@ +// 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_COMMON_PIPELINE_H_ +#define FLUTTER_SHELL_COMMON_PIPELINE_H_ + +#include +#include +#include + +#include "flutter/flow/frame_timings.h" +#include "flutter/flow/layers/layer_tree.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/ref_counted.h" +#include "flutter/fml/synchronization/semaphore.h" +#include "flutter/fml/trace_event.h" + +namespace flutter { + +struct PipelineProduceResult { + // Whether the item was successfully pushed into the pipeline. + bool success = false; + // Whether it is the first item of the pipeline. Only valid when 'success' is + // 'true'. + bool is_first_item = false; +}; + +enum class PipelineConsumeResult { + // NOLINTBEGIN(readability-identifier-naming) + NoneAvailable, + Done, + MoreAvailable, + // NOLINTEND(readability-identifier-naming) +}; + +size_t GetNextPipelineTraceID(); + +/// A thread-safe queue of resources for a single consumer and a single +/// producer, with a maximum queue depth. +/// +/// Pipelines support two key operations: produce and consume. +/// +/// The consumer calls |Consume| to wait for a resource to be produced and +/// consume it when ready. +/// +/// The producer calls |Produce| to generate a `ProducerContinuation` which +/// provides a means to enqueue a resource in the pipeline, if the pipeline is +/// below its maximum depth. When the resource has been prepared, the producer +/// calls `Complete` on the continuation, which enqueues the resource and +/// signals the waiting consumer. +/// +/// Pipelines generate the following tracing information: +/// * PipelineItem: async flow tracking time taken from the time a producer +/// calls |Produce| to the time a consumer consumes calls |Consume|. +/// * PipelineProduce: async flow tracking time taken from the time a producer +/// calls |Produce| to the time they complete the `ProducerContinuation` with +/// a resource. +/// * Pipeline Depth: counter of inflight resource producers. +/// +/// The primary use of this class is as the frame pipeline used in Flutter's +/// animator/rasterizer. +template +class Pipeline { + public: + using Resource = R; + using ResourcePtr = std::unique_ptr; + + /// Denotes a spot in the pipeline reserved for the producer to finish + /// preparing a completed pipeline resource. + class ProducerContinuation { + public: + ProducerContinuation() : trace_id_(0) {} + + ProducerContinuation(ProducerContinuation&& other) + : continuation_(other.continuation_), trace_id_(other.trace_id_) { + other.continuation_ = nullptr; + other.trace_id_ = 0; + } + + ProducerContinuation& operator=(ProducerContinuation&& other) { + std::swap(continuation_, other.continuation_); + std::swap(trace_id_, other.trace_id_); + return *this; + } + + ~ProducerContinuation() { + if (continuation_) { + continuation_(nullptr, trace_id_); + TRACE_EVENT_ASYNC_END0("flutter", "PipelineProduce", trace_id_); + // The continuation is being dropped on the floor. End the flow. + TRACE_FLOW_END("flutter", "PipelineItem", trace_id_); + TRACE_EVENT_ASYNC_END0("flutter", "PipelineItem", trace_id_); + } + } + + /// Completes the continuation with the specified resource. + [[nodiscard]] PipelineProduceResult Complete(ResourcePtr resource) { + PipelineProduceResult result; + if (continuation_) { + result = continuation_(std::move(resource), trace_id_); + continuation_ = nullptr; + TRACE_EVENT_ASYNC_END0("flutter", "PipelineProduce", trace_id_); + TRACE_FLOW_STEP("flutter", "PipelineItem", trace_id_); + } + return result; + } + + explicit operator bool() const { return continuation_ != nullptr; } + + private: + friend class Pipeline; + using Continuation = + std::function; + + Continuation continuation_; + uint64_t trace_id_; + + ProducerContinuation(const Continuation& continuation, uint64_t trace_id) + : continuation_(continuation), trace_id_(trace_id) { + TRACE_EVENT_ASYNC_BEGIN0_WITH_FLOW_IDS("flutter", "PipelineItem", + trace_id_, /*flow_id_count=*/1, + /*flow_ids=*/&trace_id); + TRACE_FLOW_BEGIN("flutter", "PipelineItem", trace_id_); + TRACE_EVENT_ASYNC_BEGIN0("flutter", "PipelineProduce", trace_id_); + } + + FML_DISALLOW_COPY_AND_ASSIGN(ProducerContinuation); + }; + + explicit Pipeline(uint32_t depth) + : empty_(depth), available_(0), inflight_(0) {} + + ~Pipeline() = default; + + bool IsValid() const { return empty_.IsValid() && available_.IsValid(); } + + /// Creates a `ProducerContinuation` that a producer can use to add a + /// resource to the queue. + /// + /// If the queue is already at its maximum depth, the `ProducerContinuation` + /// is returned with success = false. + ProducerContinuation Produce() { + if (!empty_.TryWait()) { + return {}; + } + ++inflight_; + FML_TRACE_COUNTER("flutter", "Pipeline Depth", + reinterpret_cast(this), // + "frames in flight", inflight_.load() // + ); + + return ProducerContinuation{ + std::bind(&Pipeline::ProducerCommit, this, std::placeholders::_1, + std::placeholders::_2), // continuation + GetNextPipelineTraceID()}; // trace id + } + + /// Creates a `ProducerContinuation` that will only push the task if the + /// queue is empty. + /// + /// Prefer using |Produce|. ProducerContinuation returned by this method + /// doesn't guarantee that the frame will be rendered. + ProducerContinuation ProduceIfEmpty() { + if (!empty_.TryWait()) { + return {}; + } + ++inflight_; + FML_TRACE_COUNTER("flutter", "Pipeline Depth", + reinterpret_cast(this), // + "frames in flight", inflight_.load() // + ); + + return ProducerContinuation{ + std::bind(&Pipeline::ProducerCommitIfEmpty, this, std::placeholders::_1, + std::placeholders::_2), // continuation + GetNextPipelineTraceID()}; // trace id + } + + using Consumer = std::function; + + /// @note Procedure doesn't copy all closures. + [[nodiscard]] PipelineConsumeResult Consume(const Consumer& consumer) { + if (consumer == nullptr) { + return PipelineConsumeResult::NoneAvailable; + } + + if (!available_.TryWait()) { + return PipelineConsumeResult::NoneAvailable; + } + + ResourcePtr resource; + size_t trace_id = 0; + size_t items_count = 0; + + { + std::scoped_lock lock(queue_mutex_); + std::tie(resource, trace_id) = std::move(queue_.front()); + queue_.pop_front(); + items_count = queue_.size(); + } + + consumer(std::move(resource)); + + empty_.Signal(); + --inflight_; + + TRACE_FLOW_END("flutter", "PipelineItem", trace_id); + TRACE_EVENT_ASYNC_END0("flutter", "PipelineItem", trace_id); + + return items_count > 0 ? PipelineConsumeResult::MoreAvailable + : PipelineConsumeResult::Done; + } + + private: + fml::Semaphore empty_; + fml::Semaphore available_; + std::atomic inflight_; + std::mutex queue_mutex_; + std::deque> queue_; + + /// Commits a produced resource to the queue and signals the consumer that a + /// resource is available. + PipelineProduceResult ProducerCommit(ResourcePtr resource, size_t trace_id) { + bool is_first_item = false; + { + std::scoped_lock lock(queue_mutex_); + is_first_item = queue_.empty(); + queue_.emplace_back(std::move(resource), trace_id); + } + + // Ensure the queue mutex is not held as that would be a pessimization. + available_.Signal(); + return {.success = true, .is_first_item = is_first_item}; + } + + PipelineProduceResult ProducerCommitIfEmpty(ResourcePtr resource, + size_t trace_id) { + { + std::scoped_lock lock(queue_mutex_); + if (!queue_.empty()) { + // Bail if the queue is not empty, opens up spaces to produce other + // frames. + empty_.Signal(); + return {.success = false, .is_first_item = false}; + } + queue_.emplace_back(std::move(resource), trace_id); + } + + // Ensure the queue mutex is not held as that would be a pessimization. + available_.Signal(); + return {.success = true, .is_first_item = true}; + } + + FML_DISALLOW_COPY_AND_ASSIGN(Pipeline); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_PIPELINE_H_ diff --git a/flutter/engine/src/flutter/shell/common/pipeline_unittests.cc b/flutter/engine/src/flutter/shell/common/pipeline_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..11b8ed334133a270bb2cb6456e03600fb74ef51a --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/pipeline_unittests.cc @@ -0,0 +1,148 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include "flutter/shell/common/pipeline.h" + +#include +#include +#include + +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +using IntPipeline = Pipeline; +using Continuation = IntPipeline::ProducerContinuation; + +TEST(PipelineTest, ConsumeOneVal) { + std::shared_ptr pipeline = std::make_shared(2); + + Continuation continuation = pipeline->Produce(); + + const int test_val = 1; + PipelineProduceResult result = + continuation.Complete(std::make_unique(test_val)); + ASSERT_EQ(result.success, true); + ASSERT_EQ(result.is_first_item, true); + + PipelineConsumeResult consume_result = pipeline->Consume( + [&test_val](std::unique_ptr v) { ASSERT_EQ(*v, test_val); }); + + ASSERT_EQ(consume_result, PipelineConsumeResult::Done); +} + +TEST(PipelineTest, ContinuationCanOnlyBeUsedOnce) { + std::shared_ptr pipeline = std::make_shared(2); + + Continuation continuation = pipeline->Produce(); + + const int test_val = 1; + PipelineProduceResult result = + continuation.Complete(std::make_unique(test_val)); + ASSERT_EQ(result.success, true); + ASSERT_EQ(result.is_first_item, true); + + PipelineConsumeResult consume_result_1 = pipeline->Consume( + [&test_val](std::unique_ptr v) { ASSERT_EQ(*v, test_val); }); + + result = continuation.Complete(std::make_unique(test_val)); + ASSERT_EQ(result.success, false); + ASSERT_EQ(consume_result_1, PipelineConsumeResult::Done); + + PipelineConsumeResult consume_result_2 = + pipeline->Consume([](std::unique_ptr v) { FAIL(); }); + + result = continuation.Complete(std::make_unique(test_val)); + ASSERT_EQ(result.success, false); + ASSERT_EQ(consume_result_2, PipelineConsumeResult::NoneAvailable); +} + +TEST(PipelineTest, PushingMoreThanDepthCompletesFirstSubmission) { + const int depth = 1; + std::shared_ptr pipeline = std::make_shared(depth); + + Continuation continuation_1 = pipeline->Produce(); + Continuation continuation_2 = pipeline->Produce(); + + const int test_val_1 = 1, test_val_2 = 2; + PipelineProduceResult result = + continuation_1.Complete(std::make_unique(test_val_1)); + ASSERT_EQ(result.success, true); + ASSERT_EQ(result.is_first_item, true); + result = continuation_2.Complete(std::make_unique(test_val_2)); + ASSERT_EQ(result.success, false); + + PipelineConsumeResult consume_result_1 = pipeline->Consume( + [&test_val_1](std::unique_ptr v) { ASSERT_EQ(*v, test_val_1); }); + + ASSERT_EQ(consume_result_1, PipelineConsumeResult::Done); +} + +TEST(PipelineTest, PushingMultiProcessesInOrder) { + const int depth = 2; + std::shared_ptr pipeline = std::make_shared(depth); + + Continuation continuation_1 = pipeline->Produce(); + Continuation continuation_2 = pipeline->Produce(); + + const int test_val_1 = 1, test_val_2 = 2; + PipelineProduceResult result = + continuation_1.Complete(std::make_unique(test_val_1)); + ASSERT_EQ(result.success, true); + ASSERT_EQ(result.is_first_item, true); + result = continuation_2.Complete(std::make_unique(test_val_2)); + ASSERT_EQ(result.success, true); + ASSERT_EQ(result.is_first_item, false); + + PipelineConsumeResult consume_result_1 = pipeline->Consume( + [&test_val_1](std::unique_ptr v) { ASSERT_EQ(*v, test_val_1); }); + ASSERT_EQ(consume_result_1, PipelineConsumeResult::MoreAvailable); + + PipelineConsumeResult consume_result_2 = pipeline->Consume( + [&test_val_2](std::unique_ptr v) { ASSERT_EQ(*v, test_val_2); }); + ASSERT_EQ(consume_result_2, PipelineConsumeResult::Done); +} + +TEST(PipelineTest, ProduceIfEmptyDoesNotConsumeWhenQueueIsNotEmpty) { + const int depth = 2; + std::shared_ptr pipeline = std::make_shared(depth); + + Continuation continuation_1 = pipeline->Produce(); + Continuation continuation_2 = pipeline->ProduceIfEmpty(); + + const int test_val_1 = 1, test_val_2 = 2; + PipelineProduceResult result = + continuation_1.Complete(std::make_unique(test_val_1)); + ASSERT_EQ(result.success, true); + ASSERT_EQ(result.is_first_item, true); + result = continuation_2.Complete(std::make_unique(test_val_2)); + ASSERT_EQ(result.success, false); + + PipelineConsumeResult consume_result_1 = pipeline->Consume( + [&test_val_1](std::unique_ptr v) { ASSERT_EQ(*v, test_val_1); }); + ASSERT_EQ(consume_result_1, PipelineConsumeResult::Done); +} + +TEST(PipelineTest, ProduceIfEmptySuccessfulIfQueueIsEmpty) { + const int depth = 1; + std::shared_ptr pipeline = std::make_shared(depth); + + Continuation continuation_1 = pipeline->ProduceIfEmpty(); + + const int test_val_1 = 1; + PipelineProduceResult result = + continuation_1.Complete(std::make_unique(test_val_1)); + ASSERT_EQ(result.success, true); + ASSERT_EQ(result.is_first_item, true); + + PipelineConsumeResult consume_result_1 = pipeline->Consume( + [&test_val_1](std::unique_ptr v) { ASSERT_EQ(*v, test_val_1); }); + ASSERT_EQ(consume_result_1, PipelineConsumeResult::Done); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/platform_message_handler.h b/flutter/engine/src/flutter/shell/common/platform_message_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..d890495cef294945c239558fdb775bf5361a01c5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/platform_message_handler.h @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_PLATFORM_MESSAGE_HANDLER_H_ +#define FLUTTER_SHELL_COMMON_PLATFORM_MESSAGE_HANDLER_H_ + +#include + +#include "flutter/fml/mapping.h" + +namespace flutter { + +class PlatformMessage; + +/// An interface over the ability to handle PlatformMessages that are being sent +/// from Flutter to the host platform. +class PlatformMessageHandler { + public: + virtual ~PlatformMessageHandler() = default; + + /// Ultimately sends the PlatformMessage to the host platform. + /// This method is invoked on the ui thread. + virtual void HandlePlatformMessage( + std::unique_ptr message) = 0; + + /// Returns true if the platform message will ALWAYS be dispatched to the + /// platform thread. + /// + /// Platforms that support Background Platform Channels will return + /// false. + virtual bool DoesHandlePlatformMessageOnPlatformThread() const = 0; + + /// Performs the return procedure for an associated call to + /// HandlePlatformMessage. + /// This method should be thread-safe and able to be invoked on any thread. + virtual void InvokePlatformMessageResponseCallback( + int response_id, + std::unique_ptr mapping) = 0; + + /// Performs the return procedure for an associated call to + /// HandlePlatformMessage where there is no return value. + /// This method should be thread-safe and able to be invoked on any thread. + virtual void InvokePlatformMessageEmptyResponseCallback(int response_id) = 0; +}; +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_PLATFORM_MESSAGE_HANDLER_H_ diff --git a/flutter/engine/src/flutter/shell/common/platform_view.cc b/flutter/engine/src/flutter/shell/common/platform_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..9ca28042011892b1bcbf9dad31322d2b82c2a578 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/platform_view.cc @@ -0,0 +1,233 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/platform_view.h" + +#include + +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/shell/common/vsync_waiter_fallback.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLInterface.h" + +namespace flutter { + +PlatformView::PlatformView(Delegate& delegate, const TaskRunners& task_runners) + : delegate_(delegate), task_runners_(task_runners), weak_factory_(this) {} + +PlatformView::~PlatformView() = default; + +std::unique_ptr PlatformView::CreateVSyncWaiter() { + FML_DLOG(WARNING) + << "This platform does not provide a Vsync waiter implementation. A " + "simple timer based fallback is being used."; + return std::make_unique(task_runners_); +} + +void PlatformView::DispatchPlatformMessage( + std::unique_ptr message) { + delegate_.OnPlatformViewDispatchPlatformMessage(std::move(message)); +} + +void PlatformView::DispatchPointerDataPacket( + std::unique_ptr packet) { + delegate_.OnPlatformViewDispatchPointerDataPacket(std::move(packet)); +} + +void PlatformView::DispatchSemanticsAction(int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args) { + delegate_.OnPlatformViewDispatchSemanticsAction(view_id, node_id, action, + std::move(args)); +} + +void PlatformView::SetSemanticsEnabled(bool enabled) { + delegate_.OnPlatformViewSetSemanticsEnabled(enabled); +} + +void PlatformView::SetAccessibilityFeatures(int32_t flags) { + delegate_.OnPlatformViewSetAccessibilityFeatures(flags); +} + +void PlatformView::SetViewportMetrics(int64_t view_id, + const ViewportMetrics& metrics) { + delegate_.OnPlatformViewSetViewportMetrics(view_id, metrics); +} + +void PlatformView::NotifyCreated() { + std::unique_ptr surface; + // Threading: We want to use the platform view on the non-platform thread. + // Using the weak pointer is illegal. But, we are going to introduce a latch + // so that the platform view is not collected till the surface is obtained. + auto* platform_view = this; + fml::ManualResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetRasterTaskRunner(), [platform_view, &surface, &latch]() { + surface = platform_view->CreateRenderingSurface(); + if (surface && !surface->IsValid()) { + surface.reset(); + } + latch.Signal(); + }); + latch.Wait(); + if (!surface) { + FML_LOG(ERROR) << "Failed to create platform view rendering surface"; + return; + } + delegate_.OnPlatformViewCreated(std::move(surface)); +} + +void PlatformView::NotifyDestroyed() { + delegate_.OnPlatformViewDestroyed(); +} + +void PlatformView::ScheduleFrame() { + delegate_.OnPlatformViewScheduleFrame(); +} + +void PlatformView::AddView(int64_t view_id, + const ViewportMetrics& viewport_metrics, + AddViewCallback callback) { + delegate_.OnPlatformViewAddView(view_id, viewport_metrics, + std::move(callback)); +} + +void PlatformView::RemoveView(int64_t view_id, RemoveViewCallback callback) { + delegate_.OnPlatformViewRemoveView(view_id, std::move(callback)); +} + +void PlatformView::SendViewFocusEvent(const ViewFocusEvent& event) { + delegate_.OnPlatformViewSendViewFocusEvent(event); +} + +sk_sp PlatformView::CreateResourceContext() const { + FML_DLOG(WARNING) << "This platform does not set up the resource " + "context on the IO thread for async texture uploads."; + return nullptr; +} + +std::shared_ptr PlatformView::GetImpellerContext() const { + return nullptr; +} + +void PlatformView::ReleaseResourceContext() const {} + +PointerDataDispatcherMaker PlatformView::GetDispatcherMaker() { + return [](DefaultPointerDataDispatcher::Delegate& delegate) { + return std::make_unique(delegate); + }; +} + +fml::WeakPtr PlatformView::GetWeakPtr() const { + return weak_factory_.GetWeakPtr(); +} + +void PlatformView::UpdateSemantics( + int64_t view_id, + SemanticsNodeUpdates update, // NOLINT(performance-unnecessary-value-param) + // NOLINTNEXTLINE(performance-unnecessary-value-param) + CustomAccessibilityActionUpdates actions) {} + +void PlatformView::SendChannelUpdate(const std::string& name, bool listening) {} + +void PlatformView::HandlePlatformMessage( + std::unique_ptr message) { + if (auto response = message->response()) { + response->CompleteEmpty(); + } +} + +void PlatformView::OnPreEngineRestart() const {} + +void PlatformView::RegisterTexture(std::shared_ptr texture) { + delegate_.OnPlatformViewRegisterTexture(std::move(texture)); +} + +void PlatformView::UnregisterTexture(int64_t texture_id) { + delegate_.OnPlatformViewUnregisterTexture(texture_id); +} + +void PlatformView::MarkTextureFrameAvailable(int64_t texture_id) { + delegate_.OnPlatformViewMarkTextureFrameAvailable(texture_id); +} + +std::unique_ptr PlatformView::CreateRenderingSurface() { + // We have a default implementation because tests create a platform view but + // never a rendering surface. + FML_DCHECK(false) << "This platform does not provide a rendering surface but " + "it was notified of surface rendering surface creation."; + return nullptr; +} + +std::shared_ptr +PlatformView::CreateExternalViewEmbedder() { + FML_DLOG(WARNING) + << "This platform doesn't support embedding external views."; + return nullptr; +} + +void PlatformView::SetNextFrameCallback(const fml::closure& closure) { + if (!closure) { + return; + } + + delegate_.OnPlatformViewSetNextFrameCallback(closure); +} + +std::unique_ptr> +PlatformView::ComputePlatformResolvedLocales( + const std::vector& supported_locale_data) { + std::unique_ptr> out = + std::make_unique>(); + return out; +} + +void PlatformView::RequestDartDeferredLibrary(intptr_t loading_unit_id) {} + +void PlatformView::LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) {} + +void PlatformView::LoadDartDeferredLibraryError( + intptr_t loading_unit_id, + const std::string + error_message, // NOLINT(performance-unnecessary-value-param) + bool transient) {} + +void PlatformView::UpdateAssetResolverByType( + std::unique_ptr updated_asset_resolver, + AssetResolver::AssetResolverType type) { + delegate_.UpdateAssetResolverByType(std::move(updated_asset_resolver), type); +} + +std::unique_ptr +PlatformView::CreateSnapshotSurfaceProducer() { + return nullptr; +} + +std::shared_ptr +PlatformView::GetPlatformMessageHandler() const { + return nullptr; +} + +const Settings& PlatformView::GetSettings() const { + return delegate_.OnPlatformViewGetSettings(); +} + +double PlatformView::GetScaledFontSize(double unscaled_font_size, + int configuration_id) const { + // Unreachable by default, as most platforms do not support nonlinear scaling + // and the Flutter application never invokes this method. + FML_UNREACHABLE(); + return -1; +} + +void PlatformView::RequestViewFocusChange( + const ViewFocusChangeRequest& request) { + // No-op by default. +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/platform_view.h b/flutter/engine/src/flutter/shell/common/platform_view.h new file mode 100644 index 0000000000000000000000000000000000000000..7be2b1ca0974fb868066c1fa85b0147ec8dbbb87 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/platform_view.h @@ -0,0 +1,994 @@ +// 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_COMMON_PLATFORM_VIEW_H_ +#define FLUTTER_SHELL_COMMON_PLATFORM_VIEW_H_ + +#include +#include + +#include "flutter/common/graphics/texture.h" +#include "flutter/common/task_runners.h" +#include "flutter/flow/embedded_views.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/lib/ui/semantics/custom_accessibility_action.h" +#include "flutter/lib/ui/semantics/semantics_node.h" +#include "flutter/lib/ui/window/key_data_packet.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/lib/ui/window/pointer_data_packet.h" +#include "flutter/lib/ui/window/viewport_metrics.h" +#include "flutter/shell/common/platform_message_handler.h" +#include "flutter/shell/common/pointer_data_dispatcher.h" +#include "flutter/shell/common/vsync_waiter.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace impeller { + +class Context; + +} // namespace impeller + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Platform views are created by the shell on the platform task +/// runner. Unless explicitly specified, all platform view methods +/// are called on the platform task runner as well. Platform views +/// are usually sub-classed on a per platform basis and the bulk of +/// the window system integration happens using that subclass. Since +/// most platform window toolkits are usually only safe to access on +/// a single "main" thread, any interaction that requires access to +/// the underlying platform's window toolkit is routed through the +/// platform view associated with that shell. This involves +/// operations like settings up and tearing down the render surface, +/// platform messages, interacting with accessibility features on +/// the platform, input events, etc. +/// +class PlatformView { + public: + using AddViewCallback = std::function; + using RemoveViewCallback = std::function; + //---------------------------------------------------------------------------- + /// @brief Used to forward events from the platform view to interested + /// subsystems. This forwarding is done by the shell which sets + /// itself up as the delegate of the platform view. + /// + class Delegate { + public: + using AddViewCallback = PlatformView::AddViewCallback; + using RemoveViewCallback = PlatformView::RemoveViewCallback; + using KeyDataResponse = std::function; + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the platform view was created + /// with the given render surface. This surface is platform + /// (iOS, Android) and client-rendering API (OpenGL, Software, + /// Metal, Vulkan) specific. This is usually a sign to the + /// rasterizer to set up and begin rendering to that surface. + /// + /// @param[in] surface The surface + /// + virtual void OnPlatformViewCreated(std::unique_ptr surface) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the platform view was destroyed. + /// This is usually a sign to the rasterizer to suspend + /// rendering a previously configured surface and collect any + /// intermediate resources. + /// + virtual void OnPlatformViewDestroyed() = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the platform needs to schedule a + /// frame to regenerate the layer tree and redraw the surface. + /// + virtual void OnPlatformViewScheduleFrame() = 0; + + /// @brief Allocate resources for a new non-implicit view and inform + /// Dart about the view, and on success, schedules a new frame. + /// + /// After the operation, |callback| should be invoked with whether + /// the operation is successful. + /// + /// Adding |kFlutterImplicitViewId| or an existing view ID should + /// result in failure. + /// + /// @param[in] view_id The view ID of the new view. + /// @param[in] viewport_metrics The initial viewport metrics for the view. + /// @param[in] callback The callback that's invoked once the shell + /// has attempted to add the view. + /// + virtual void OnPlatformViewAddView(int64_t view_id, + const ViewportMetrics& viewport_metrics, + AddViewCallback callback) = 0; + + /// @brief Deallocate resources for a removed view and inform + /// Dart about the removal. + /// + /// After the operation, |callback| should be invoked with whether + /// the operation is successful. + /// + /// Removing |kFlutterImplicitViewId| or an non-existent view ID + /// should result in failure. + /// + /// @param[in] view_id The view ID of the view to be removed. + /// @param[in] callback The callback that's invoked once the shell has + /// attempted to remove the view. + /// + virtual void OnPlatformViewRemoveView(int64_t view_id, + RemoveViewCallback callback) = 0; + + /// @brief Notify the delegate that platform view focus state has changed. + /// + /// @param[in] event The focus event describing the change. + virtual void OnPlatformViewSendViewFocusEvent( + const ViewFocusEvent& event) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the specified callback needs to + /// be invoked after the rasterizer is done rendering the next + /// frame. This callback will be called on the render thread and + /// it is caller responsibility to perform any re-threading as + /// necessary. Due to the asynchronous nature of rendering in + /// Flutter, embedders usually add a placeholder over the + /// contents in which Flutter is going to render when Flutter is + /// first initialized. This callback may be used as a signal to + /// remove that placeholder. + /// + /// @attention The callback will be invoked on the render thread and not + /// the calling thread. + /// + /// @param[in] closure The callback to execute on the next frame. + /// + virtual void OnPlatformViewSetNextFrameCallback( + const fml::closure& closure) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate the viewport metrics of a view have + /// been updated. The rasterizer will need to be reconfigured to + /// render the frame in the updated viewport metrics. + /// + /// @param[in] view_id The ID for the view that `metrics` describes. + /// @param[in] metrics The updated viewport metrics. + /// + virtual void OnPlatformViewSetViewportMetrics( + int64_t view_id, + const ViewportMetrics& metrics) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the platform has dispatched a + /// platform message from the embedder to the Flutter + /// application. This message must be forwarded to the running + /// isolate hosted by the engine on the UI thread. + /// + /// @param[in] message The platform message to dispatch to the running + /// root isolate. + /// + virtual void OnPlatformViewDispatchPlatformMessage( + std::unique_ptr message) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the platform view has encountered + /// a pointer event. This pointer event needs to be forwarded to + /// the running root isolate hosted by the engine on the UI + /// thread. + /// + /// @param[in] packet The pointer data packet containing multiple pointer + /// events. + /// + virtual void OnPlatformViewDispatchPointerDataPacket( + std::unique_ptr packet) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the platform view has encountered + /// an accessibility related action on the specified node. This + /// event must be forwarded to the running root isolate hosted + /// by the engine on the UI thread. + /// + /// @param[in] view_id The identifier of the view that contains this node. + /// @param[in] node_id The identifier of the accessibility node. + /// @param[in] action The accessibility related action performed on the + /// node of the specified ID. + /// @param[in] args An optional list of argument that apply to the + /// specified action. + /// + virtual void OnPlatformViewDispatchSemanticsAction( + int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the embedder has expressed an + /// opinion about whether the accessibility tree needs to be + /// enabled or disabled. This information needs to be forwarded + /// to the root isolate running on the UI thread. + /// + /// @param[in] enabled Whether the accessibility tree is enabled or + /// disabled. + /// + virtual void OnPlatformViewSetSemanticsEnabled(bool enabled) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the embedder has expressed an + /// opinion about the features to enable in the accessibility + /// tree. + /// + /// The engine does not care about the accessibility feature + /// flags as all it does is forward this information from the + /// embedder to the framework. However, curious readers may + /// refer to `AccessibilityFeatures` in `window.dart` for + /// currently supported accessibility feature flags. + /// + /// @param[in] flags The features to enable in the accessibility tree. + /// + virtual void OnPlatformViewSetAccessibilityFeatures(int32_t flags) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the embedder has specified a + /// texture that it want the rasterizer to composite within the + /// Flutter layer tree. All textures must have a unique + /// identifier. When the rasterizer encounters an external + /// texture within its hierarchy, it gives the embedder a chance + /// to update that texture on the raster thread before it + /// composites the same on-screen. + /// + /// @param[in] texture The texture that is being updated by the embedder + /// but composited by Flutter in its own hierarchy. + /// + virtual void OnPlatformViewRegisterTexture( + std::shared_ptr texture) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the embedder will no longer + /// attempt to composite the specified texture within the layer + /// tree. This allows the rasterizer to collect associated + /// resources. + /// + /// @param[in] texture_id The identifier of the texture to unregister. If + /// the texture has not been previously registered, + /// this call does nothing. + /// + virtual void OnPlatformViewUnregisterTexture(int64_t texture_id) = 0; + + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that the embedder has updated the + /// contents of the texture with the specified identifier. + /// Typically, Flutter will only render a frame if there is an + /// updated layer tree. However, in cases where the layer tree + /// is static but one of the externally composited textures has + /// been updated by the embedder, the embedder needs to notify + /// the rasterizer to render a new frame. In such cases, the + /// existing layer tree may be reused with the frame composited + /// with all updated external textures. + /// + /// @param[in] texture_id The identifier of the texture that has been + /// updated. + /// + virtual void OnPlatformViewMarkTextureFrameAvailable( + int64_t texture_id) = 0; + + //-------------------------------------------------------------------------- + /// @brief Loads the dart shared library into the dart VM. When the + /// dart library is loaded successfully, the dart future + /// returned by the originating loadLibrary() call completes. + /// + /// The Dart compiler may generate separate shared libraries + /// files called 'loading units' when libraries are imported + /// as deferred. Each of these shared libraries are identified + /// by a unique loading unit id. Callers should open and resolve + /// a SymbolMapping from the shared library. The Mappings should + /// be moved into this method, as ownership will be assumed by + /// the dart root isolate after successful loading and released + /// after shutdown of the root isolate. The loading unit may not + /// be used after isolate shutdown. If loading fails, the + /// mappings will be released. + /// + /// This method is paired with a RequestDartDeferredLibrary + /// invocation that provides the embedder with the loading unit + /// id of the deferred library to load. + /// + /// + /// @param[in] loading_unit_id The unique id of the deferred library's + /// loading unit. + /// + /// @param[in] snapshot_data Dart snapshot data of the loading unit's + /// shared library. + /// + /// @param[in] snapshot_data Dart snapshot instructions of the loading + /// unit's shared library. + /// + virtual void LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) = 0; + + //-------------------------------------------------------------------------- + /// @brief Indicates to the dart VM that the request to load a deferred + /// library with the specified loading unit id has failed. + /// + /// The dart future returned by the initiating loadLibrary() + /// call will complete with an error. + /// + /// @param[in] loading_unit_id The unique id of the deferred library's + /// loading unit, as passed in by + /// RequestDartDeferredLibrary. + /// + /// @param[in] error_message The error message that will appear in the + /// dart Future. + /// + /// @param[in] transient A transient error is a failure due to + /// temporary conditions such as no network. + /// Transient errors allow the dart VM to + /// re-request the same deferred library and + /// loading_unit_id again. Non-transient + /// errors are permanent and attempts to + /// re-request the library will instantly + /// complete with an error. + virtual void LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string error_message, + bool transient) = 0; + + //-------------------------------------------------------------------------- + /// @brief Replaces the asset resolver handled by the engine's + /// AssetManager of the specified `type` with + /// `updated_asset_resolver`. The matching AssetResolver is + /// removed and replaced with `updated_asset_resolvers`. + /// + /// AssetResolvers should be updated when the existing resolver + /// becomes obsolete and a newer one becomes available that + /// provides updated access to the same type of assets as the + /// existing one. This update process is meant to be performed + /// at runtime. + /// + /// If a null resolver is provided, nothing will be done. If no + /// matching resolver is found, the provided resolver will be + /// added to the end of the AssetManager resolvers queue. The + /// replacement only occurs with the first matching resolver. + /// Any additional matching resolvers are untouched. + /// + /// @param[in] updated_asset_resolver The asset resolver to replace the + /// resolver of matching type with. + /// + /// @param[in] type The type of AssetResolver to update. Only resolvers of + /// the specified type will be replaced by the updated + /// resolver. + /// + virtual void UpdateAssetResolverByType( + std::unique_ptr updated_asset_resolver, + AssetResolver::AssetResolverType type) = 0; + + //-------------------------------------------------------------------------- + /// @brief Called by the platform view on the platform thread to get + /// the settings object associated with the platform view + /// instance. + /// + /// @return The settings. + /// + virtual const Settings& OnPlatformViewGetSettings() const = 0; + }; + + //---------------------------------------------------------------------------- + /// @brief Creates a platform view with the specified delegate and task + /// runner. The base class by itself does not do much but is + /// suitable for use in test environments where full platform + /// integration may not be necessary. The platform view may only + /// be created, accessed and destroyed on the platform task + /// runner. + /// + /// @param delegate The delegate. This is typically the shell. + /// @param[in] task_runners The task runners used by this platform view. + /// + explicit PlatformView(Delegate& delegate, const TaskRunners& task_runners); + + //---------------------------------------------------------------------------- + /// @brief Destroys the platform view. The platform view is owned by the + /// shell and will be destroyed by the same on the platform tasks + /// runner. + /// + virtual ~PlatformView(); + + //---------------------------------------------------------------------------- + /// @brief Invoked by the shell to obtain a platform specific vsync + /// waiter. It is optional for platforms to override this method + /// and provide a custom vsync waiter because a timer based + /// fall-back waiter is used by default. However, it is highly + /// recommended that platform provide their own Vsync waiter as + /// the timer based fall-back will not render frames aligned with + /// vsync boundaries. + /// + /// @attention If a timer based fall-back is used, a warning is logged to the + /// console. In case this method is overridden in a subclass, it + /// must return a valid vsync waiter. Returning null will lead to + /// internal errors. If a valid vsync waiter cannot be returned, + /// subclasses should just call the based class method instead. + /// + /// @return A vsync waiter. If is an internal error to return a null + /// waiter. + /// + virtual std::unique_ptr CreateVSyncWaiter(); + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to dispatch a platform message to a + /// running root isolate hosted by the engine. If an isolate is + /// not running, the message is dropped. If there is no one on the + /// other side listening on the channel, the message is dropped. + /// When a platform message is dropped, any response handles + /// associated with that message will be dropped as well. All + /// users of platform messages must assume that message may not be + /// delivered and/or their response handles may not be invoked. + /// Platform messages are not buffered. + /// + /// For embedders that wish to respond to platform message + /// directed from the framework to the embedder, the + /// `HandlePlatformMessage` method may be overridden. + /// + /// @see HandlePlatformMessage() + /// + /// @param[in] message The platform message to deliver to the root isolate. + /// + void DispatchPlatformMessage(std::unique_ptr message); + + //---------------------------------------------------------------------------- + /// @brief Overridden by embedders to perform actions in response to + /// platform messages sent from the framework to the embedder. + /// Default implementation of this method simply returns an empty + /// response. + /// + /// Embedders that wish to send platform messages to the framework + /// may use the `DispatchPlatformMessage` method. This method is + /// for messages that go the other way. + /// + /// @see DispatchPlatformMessage() + /// + /// @param[in] message The message + /// + virtual void HandlePlatformMessage(std::unique_ptr message); + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to dispatch an accessibility action to a + /// running isolate hosted by the engine. + /// + /// @param[in] view_id The identifier of the view. + /// @param[in] node_id The identifier of the accessibility node on which to + /// perform the action. + /// @param[in] action The action + /// @param[in] args The arguments + /// + void DispatchSemanticsAction(int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args); + + //---------------------------------------------------------------------------- + /// @brief Used by embedder to notify the running isolate hosted by the + /// engine on the UI thread that the accessibility tree needs to + /// be generated. + /// + /// @attention Subclasses may choose to override this method to perform + /// platform specific functions. However, they must call the base + /// class method at some point in their implementation. + /// + /// @param[in] enabled Whether the accessibility tree needs to be generated. + /// + virtual void SetSemanticsEnabled(bool enabled); + + //---------------------------------------------------------------------------- + /// @brief Used by the embedder to specify the features to enable in the + /// accessibility tree generated by the isolate. This information + /// is forwarded to the root isolate hosted by the engine on the + /// UI thread. + /// + /// The engine does not care about the accessibility feature flags + /// as all it does is forward this information from the embedder + /// to the framework. However, curious readers may refer to + /// `AccessibilityFeatures` in `window.dart` for currently + /// supported accessibility feature flags. + /// + /// @attention Subclasses may choose to override this method to perform + /// platform specific functions. However, they must call the base + /// class method at some point in their implementation. + /// + /// @param[in] flags The features to enable in the accessibility tree. + /// + virtual void SetAccessibilityFeatures(int32_t flags); + + //---------------------------------------------------------------------------- + /// @brief Used by the framework to tell the embedder to apply the + /// specified semantics node updates. The default implementation + /// of this method does nothing. + /// + /// @see SemanticsNode, SemticsNodeUpdates, + /// CustomAccessibilityActionUpdates + /// + /// @param[in] view_id The ID of the view that this update is for + /// @param[in] updates A map with the stable semantics node identifier as + /// key and the node properties as the value. + /// @param[in] actions A map with the stable semantics node identifier as + /// key and the custom node action as the value. + /// + virtual void UpdateSemantics(int64_t view_id, + SemanticsNodeUpdates updates, + CustomAccessibilityActionUpdates actions); + + //---------------------------------------------------------------------------- + /// @brief Used by the framework to tell the embedder that it has + /// registered a listener on a given channel. + /// + /// @param[in] name The name of the channel on which the listener has + /// set or cleared a listener. + /// @param[in] listening True if a listener has been set, false if it has + /// been cleared. + /// + virtual void SendChannelUpdate(const std::string& name, bool listening); + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to specify the updated viewport metrics for + /// a view. In response to this call, on the raster thread, the + /// rasterizer may need to be reconfigured to the updated viewport + /// dimensions. On the UI thread, the framework may need to start + /// generating a new frame for the updated viewport metrics as + /// well. + /// + /// @param[in] view_id The ID for the view that `metrics` describes. + /// @param[in] metrics The updated viewport metrics. + /// + void SetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics); + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to notify the shell that a platform view + /// has been created. This notification is used to create a + /// rendering surface and pick the client rendering API to use to + /// render into this surface. No frames will be scheduled or + /// rendered before this call. The surface must remain valid till + /// the corresponding call to NotifyDestroyed. + /// + void NotifyCreated(); + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to notify the shell that the platform view + /// has been destroyed. This notification used to collect the + /// rendering surface and all associated resources. Frame + /// scheduling is also suspended. + /// + /// @attention Subclasses may choose to override this method to perform + /// platform specific functions. However, they must call the base + /// class method at some point in their implementation. + /// + virtual void NotifyDestroyed(); + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to schedule a frame. In response to this + /// call, the framework may need to start generating a new frame. + /// + void ScheduleFrame(); + + /// @brief Used by embedders to notify the shell of a new non-implicit view. + /// + /// This method notifies the shell to allocate resources and inform + /// Dart about the view, and on success, schedules a new frame. + /// Finally, it invokes |callback| with whether the operation is + /// successful. + /// + /// This operation is asynchronous; avoid using the view until + /// |callback| returns true. Callers should prepare resources for the + /// view (if any) in advance but be ready to clean up on failure. + /// + /// The callback is called on a different thread. + /// + /// Do not use for implicit views, which are added internally during + /// shell initialization. Adding |kFlutterImplicitViewId| or an + /// existing view ID will fail, indicated by |callback| returning + /// false. + /// + /// @param[in] view_id The view ID of the new view. + /// @param[in] viewport_metrics The initial viewport metrics for the view. + /// @param[in] callback The callback that's invoked once the shell + /// has attempted to add the view. + /// + void AddView(int64_t view_id, + const ViewportMetrics& viewport_metrics, + AddViewCallback callback); + + /// @brief Used by embedders to notify the shell of a removed non-implicit + /// view. + /// + /// This method notifies the shell to deallocate resources and inform + /// Dart about the removal. Finally, it invokes |callback| with + /// whether the operation is successful. + /// + /// This operation is asynchronous. The embedder should not deallocate + /// resources until the |callback| is invoked. + /// + /// The callback is called on a different thread. + /// + /// Do not use for implicit views, which are never removed throughout + /// the lifetime of the app. + /// Removing |kFlutterImplicitViewId| or an + /// non-existent view ID will fail, indicated by |callback| returning + /// false. + /// + /// @param[in] view_id The view ID of the view to be removed. + /// @param[in] callback The callback that's invoked once the shell has + /// attempted to remove the view. + /// + void RemoveView(int64_t view_id, RemoveViewCallback callback); + + void SendViewFocusEvent(const ViewFocusEvent& event); + + //---------------------------------------------------------------------------- + /// @brief Used by the shell to obtain a Skia GPU context that is capable + /// of operating on the IO thread. The context must be in the same + /// share-group as the Skia GPU context used on the render thread. + /// This context will always be used on the IO thread. Because it + /// is in the same share-group as the separate render thread + /// context, any GPU resources uploaded in this context will be + /// visible to the render thread context (synchronization of GPU + /// resources is managed by Skia). + /// + /// If such context cannot be created on the IO thread, callers + /// may return `nullptr`. This will mean that all texture uploads + /// will be queued onto the render thread which will cause + /// performance issues. When this context is `nullptr`, an error + /// is logged to the console. It is highly recommended that all + /// platforms provide a resource context. + /// + /// @attention Unlike all other methods on the platform view, this will be + /// called on IO task runner. + /// + /// @return The Skia GPU context that is in the same share-group as the + /// main render thread GPU context. May be `nullptr` in case such + /// a context cannot be created. + /// + virtual sk_sp CreateResourceContext() const; + + virtual std::shared_ptr GetImpellerContext() const; + + //---------------------------------------------------------------------------- + /// @brief Used by the shell to notify the embedder that the resource + /// context previously obtained via a call to + /// `CreateResourceContext()` is being collected. The embedder + /// is free to collect an platform specific resources + /// associated with this context. + /// + /// @attention Unlike all other methods on the platform view, this will be + /// called on IO task runner. + /// + virtual void ReleaseResourceContext() const; + + //-------------------------------------------------------------------------- + /// @brief Returns a platform-specific PointerDataDispatcherMaker so the + /// `Engine` can construct the PointerDataPacketDispatcher based + /// on platforms. + virtual PointerDataDispatcherMaker GetDispatcherMaker(); + + //---------------------------------------------------------------------------- + /// @brief Returns a weak pointer to the platform view. Since the + /// platform view may only be created, accessed and destroyed + /// on the platform thread, any access to the platform view + /// from a non-platform task runner needs a weak pointer to + /// the platform view along with a reference to the platform + /// task runner. A task must be posted to the platform task + /// runner with the weak pointer captured in the same. The + /// platform view method may only be called in the posted task + /// once the weak pointer validity has been checked. This + /// method is used by callers to obtain that weak pointer. + /// + /// @return The weak pointer to the platform view. + /// + fml::WeakPtr GetWeakPtr() const; + + //---------------------------------------------------------------------------- + /// @brief Gives embedders a chance to react to a "cold restart" of the + /// running isolate. The default implementation of this method + /// does nothing. + /// + /// While a "hot restart" patches a running isolate, a "cold + /// restart" restarts the root isolate in a running shell. + /// + virtual void OnPreEngineRestart() const; + + //---------------------------------------------------------------------------- + /// @brief Sets a callback that gets executed when the rasterizer renders + /// the next frame. Due to the asynchronous nature of + /// rendering in Flutter, embedders usually add a placeholder + /// over the contents in which Flutter is going to render when + /// Flutter is first initialized. This callback may be used as + /// a signal to remove that placeholder. The callback is + /// executed on the render task runner and not the platform + /// task runner. It is the embedder's responsibility to + /// re-thread as necessary. + /// + /// @attention The callback is executed on the render task runner and not the + /// platform task runner. Embedders must re-thread as necessary. + /// + /// @param[in] closure The callback to execute on the render thread when the + /// next frame gets rendered. + /// + void SetNextFrameCallback(const fml::closure& closure); + + //---------------------------------------------------------------------------- + /// @brief Dispatches pointer events from the embedder to the + /// framework. Each pointer data packet may contain multiple + /// pointer input events. Each call to this method wakes up + /// the UI thread. + /// + /// @param[in] packet The pointer data packet to dispatch to the framework. + /// + void DispatchPointerDataPacket(std::unique_ptr packet); + + //-------------------------------------------------------------------------- + /// @brief Used by the embedder to specify a texture that it wants the + /// rasterizer to composite within the Flutter layer tree. All + /// textures must have a unique identifier. When the + /// rasterizer encounters an external texture within its + /// hierarchy, it gives the embedder a chance to update that + /// texture on the raster thread before it composites the same + /// on-screen. + /// + /// @attention This method must only be called once per texture. When the + /// texture is updated, calling `MarkTextureFrameAvailable` + /// with the specified texture identifier is sufficient to + /// make Flutter re-render the frame with the updated texture + /// composited in-line. + /// + /// @see UnregisterTexture, MarkTextureFrameAvailable + /// + /// @param[in] texture The texture that is being updated by the embedder + /// but composited by Flutter in its own hierarchy. + /// + void RegisterTexture(std::shared_ptr texture); + + //-------------------------------------------------------------------------- + /// @brief Used by the embedder to notify the rasterizer that it will + /// no longer attempt to composite the specified texture within + /// the layer tree. This allows the rasterizer to collect + /// associated resources. + /// + /// @attention This call must only be called once per texture identifier. + /// + /// @see RegisterTexture, MarkTextureFrameAvailable + /// + /// @param[in] texture_id The identifier of the texture to unregister. If + /// the texture has not been previously registered, + /// this call does nothing. + /// + void UnregisterTexture(int64_t texture_id); + + //-------------------------------------------------------------------------- + /// @brief Used by the embedder to notify the rasterizer that the context + /// of the previously registered texture have been updated. + /// Typically, Flutter will only render a frame if there is an + /// updated layer tree. However, in cases where the layer tree + /// is static but one of the externally composited textures + /// has been updated by the embedder, the embedder needs to + /// notify the rasterizer to render a new frame. In such + /// cases, the existing layer tree may be reused with the + /// frame re-composited with all updated external textures. + /// Unlike the calls to register and unregister the texture, + /// this call must be made each time a new texture frame is + /// available. + /// + /// @see RegisterTexture, UnregisterTexture + /// + /// @param[in] texture_id The identifier of the texture that has been + /// updated. + /// + void MarkTextureFrameAvailable(int64_t texture_id); + + //-------------------------------------------------------------------------- + /// @brief Directly invokes platform-specific APIs to compute the + /// locale the platform would have natively resolved to. + /// + /// @param[in] supported_locale_data The vector of strings that represents + /// the locales supported by the app. + /// Each locale consists of three + /// strings: languageCode, countryCode, + /// and scriptCode in that order. + /// + /// @return A vector of 3 strings languageCode, countryCode, and + /// scriptCode that represents the locale selected by the + /// platform. Empty strings mean the value was unassigned. Empty + /// vector represents a null locale. + /// + virtual std::unique_ptr> + ComputePlatformResolvedLocales( + const std::vector& supported_locale_data); + + virtual std::shared_ptr CreateExternalViewEmbedder(); + + //-------------------------------------------------------------------------- + /// @brief Invoked when the dart VM requests that a deferred library + /// be loaded. Notifies the engine that the deferred library + /// identified by the specified loading unit id should be + /// downloaded and loaded into the Dart VM via + /// `LoadDartDeferredLibrary` + /// + /// Upon encountering errors or otherwise failing to load a + /// loading unit with the specified id, the failure should be + /// directly reported to dart by calling + /// `LoadDartDeferredLibraryFailure` to ensure the waiting dart + /// future completes with an error. + /// + /// @param[in] loading_unit_id The unique id of the deferred library's + /// loading unit. This id is to be passed + /// back into LoadDartDeferredLibrary + /// in order to identify which deferred + /// library to load. + /// + virtual void RequestDartDeferredLibrary(intptr_t loading_unit_id); + + //-------------------------------------------------------------------------- + /// @brief Loads the Dart shared library into the Dart VM. When the + /// Dart library is loaded successfully, the Dart future + /// returned by the originating loadLibrary() call completes. + /// + /// The Dart compiler may generate separate shared libraries + /// files called 'loading units' when libraries are imported + /// as deferred. Each of these shared libraries are identified + /// by a unique loading unit id. Callers should open and resolve + /// a SymbolMapping from the shared library. The Mappings should + /// be moved into this method, as ownership will be assumed by the + /// dart isolate after successful loading and released after + /// shutdown of the dart isolate. If loading fails, the mappings + /// will naturally go out of scope. + /// + /// This method is paired with a RequestDartDeferredLibrary + /// invocation that provides the embedder with the loading unit id + /// of the deferred library to load. + /// + /// + /// @param[in] loading_unit_id The unique id of the deferred library's + /// loading unit, as passed in by + /// RequestDartDeferredLibrary. + /// + /// @param[in] snapshot_data Dart snapshot data of the loading unit's + /// shared library. + /// + /// @param[in] snapshot_data Dart snapshot instructions of the loading + /// unit's shared library. + /// + virtual void LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions); + + //-------------------------------------------------------------------------- + /// @brief Indicates to the dart VM that the request to load a deferred + /// library with the specified loading unit id has failed. + /// + /// The dart future returned by the initiating loadLibrary() call + /// will complete with an error. + /// + /// @param[in] loading_unit_id The unique id of the deferred library's + /// loading unit, as passed in by + /// RequestDartDeferredLibrary. + /// + /// @param[in] error_message The error message that will appear in the + /// dart Future. + /// + /// @param[in] transient A transient error is a failure due to + /// temporary conditions such as no network. + /// Transient errors allow the dart VM to + /// re-request the same deferred library and + /// loading_unit_id again. Non-transient + /// errors are permanent and attempts to + /// re-request the library will instantly + /// complete with an error. + /// + virtual void LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string error_message, + bool transient); + + //-------------------------------------------------------------------------- + /// @brief Replaces the asset resolver handled by the engine's + /// AssetManager of the specified `type` with + /// `updated_asset_resolver`. The matching AssetResolver is + /// removed and replaced with `updated_asset_resolvers`. + /// + /// AssetResolvers should be updated when the existing resolver + /// becomes obsolete and a newer one becomes available that + /// provides updated access to the same type of assets as the + /// existing one. This update process is meant to be performed + /// at runtime. + /// + /// If a null resolver is provided, nothing will be done. If no + /// matching resolver is found, the provided resolver will be + /// added to the end of the AssetManager resolvers queue. The + /// replacement only occurs with the first matching resolver. + /// Any additional matching resolvers are untouched. + /// + /// @param[in] updated_asset_resolver The asset resolver to replace the + /// resolver of matching type with. + /// + /// @param[in] type The type of AssetResolver to update. Only resolvers of + /// the specified type will be replaced by the updated + /// resolver. + /// + virtual void UpdateAssetResolverByType( + std::unique_ptr updated_asset_resolver, + AssetResolver::AssetResolverType type); + + //-------------------------------------------------------------------------- + /// @brief Creates an object that produces surfaces suitable for raster + /// snapshotting. The rasterizer will request this surface if no + /// on screen surface is currently available when an application + /// requests a snapshot, e.g. if `Scene.toImage` or + /// `Picture.toImage` are called while the application is in the + /// background. + /// + /// Not all backends support this kind of surface usage, and the + /// default implementation returns nullptr. Platforms should + /// override this if they can support GPU operations in the + /// background and support GPU resource context usage. + /// + virtual std::unique_ptr + CreateSnapshotSurfaceProducer(); + + //-------------------------------------------------------------------------- + /// @brief Specifies a delegate that will receive PlatformMessages from + /// Flutter to the host platform. + /// + /// @details If this returns `null` that means PlatformMessages should be sent + /// to the PlatformView. That is to protect legacy behavior, any embedder + /// that wants to support executing Platform Channel handlers on background + /// threads should be returning a thread-safe PlatformMessageHandler instead. + virtual std::shared_ptr GetPlatformMessageHandler() + const; + + //---------------------------------------------------------------------------- + /// @brief Get the settings for this platform view instance. + /// + /// @return The settings. + /// + const Settings& GetSettings() const; + + //-------------------------------------------------------------------------- + /// @brief Synchronously invokes platform-specific APIs to apply the + /// system text scaling on the given unscaled font size. + /// + /// Platforms that support this feature (currently it's only + /// implemented for Android SDK level 34+) will send a valid + /// configuration_id to potential callers, before this method can + /// be called. + /// + /// @param[in] unscaled_font_size The unscaled font size specified by the + /// app developer. The value is in logical + /// pixels, and is guaranteed to be finite and + /// non-negative. + /// @param[in] configuration_id The unique id of the configuration to use + /// for computing the scaled font size. + /// + /// @return The scaled font size in logical pixels, or -1 if the given + /// configuration_id did not match a valid configuration. + /// + virtual double GetScaledFontSize(double unscaled_font_size, + int configuration_id) const; + + //-------------------------------------------------------------------------- + /// @brief Notifies the client that the Flutter view focus state has + /// changed and the platform view should be updated. + /// + /// Called on platform thread. + /// + /// @param[in] request The request to change the focus state of the view. + virtual void RequestViewFocusChange(const ViewFocusChangeRequest& request); + + protected: + // This is the only method called on the raster task runner. + virtual std::unique_ptr CreateRenderingSurface(); + + PlatformView::Delegate& delegate_; + const TaskRunners task_runners_; + fml::WeakPtrFactory weak_factory_; // Must be the last member. + + private: + FML_DISALLOW_COPY_AND_ASSIGN(PlatformView); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_PLATFORM_VIEW_H_ diff --git a/flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.cc b/flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.cc new file mode 100644 index 0000000000000000000000000000000000000000..58bf4b110b78c952db8f411240c50568c226835e --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.cc @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/pointer_data_dispatcher.h" + +#include "flutter/fml/trace_event.h" + +namespace flutter { + +PointerDataDispatcher::~PointerDataDispatcher() = default; +DefaultPointerDataDispatcher::~DefaultPointerDataDispatcher() = default; + +SmoothPointerDataDispatcher::SmoothPointerDataDispatcher(Delegate& delegate) + : DefaultPointerDataDispatcher(delegate), weak_factory_(this) {} +SmoothPointerDataDispatcher::~SmoothPointerDataDispatcher() = default; + +void DefaultPointerDataDispatcher::DispatchPacket( + std::unique_ptr packet, + uint64_t trace_flow_id) { + TRACE_EVENT0_WITH_FLOW_IDS("flutter", + "DefaultPointerDataDispatcher::DispatchPacket", + /*flow_id_count=*/1, &trace_flow_id); + TRACE_FLOW_STEP("flutter", "PointerEvent", trace_flow_id); + delegate_.DoDispatchPacket(std::move(packet), trace_flow_id); +} + +void SmoothPointerDataDispatcher::DispatchPacket( + std::unique_ptr packet, + uint64_t trace_flow_id) { + TRACE_EVENT0_WITH_FLOW_IDS("flutter", + "SmoothPointerDataDispatcher::DispatchPacket", + /*flow_id_count=*/1, &trace_flow_id); + TRACE_FLOW_STEP("flutter", "PointerEvent", trace_flow_id); + + if (is_pointer_data_in_progress_) { + if (pending_packet_ != nullptr) { + DispatchPendingPacket(); + } + pending_packet_ = std::move(packet); + pending_trace_flow_id_ = trace_flow_id; + } else { + FML_DCHECK(pending_packet_ == nullptr); + DefaultPointerDataDispatcher::DispatchPacket(std::move(packet), + trace_flow_id); + } + is_pointer_data_in_progress_ = true; + ScheduleSecondaryVsyncCallback(); +} + +void SmoothPointerDataDispatcher::ScheduleSecondaryVsyncCallback() { + delegate_.ScheduleSecondaryVsyncCallback( + reinterpret_cast(this), + [dispatcher = weak_factory_.GetWeakPtr()]() { + if (dispatcher && dispatcher->is_pointer_data_in_progress_) { + if (dispatcher->pending_packet_ != nullptr) { + dispatcher->DispatchPendingPacket(); + } else { + dispatcher->is_pointer_data_in_progress_ = false; + } + } + }); +} + +void SmoothPointerDataDispatcher::DispatchPendingPacket() { + FML_DCHECK(pending_packet_ != nullptr); + FML_DCHECK(is_pointer_data_in_progress_); + DefaultPointerDataDispatcher::DispatchPacket(std::move(pending_packet_), + pending_trace_flow_id_); + pending_packet_ = nullptr; + pending_trace_flow_id_ = -1; + ScheduleSecondaryVsyncCallback(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.h b/flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.h new file mode 100644 index 0000000000000000000000000000000000000000..b749bfeee99de4e2e51bbc36261577710b192541 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.h @@ -0,0 +1,177 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_POINTER_DATA_DISPATCHER_H_ +#define FLUTTER_SHELL_COMMON_POINTER_DATA_DISPATCHER_H_ + +#include "flutter/runtime/runtime_controller.h" +#include "flutter/shell/common/animator.h" + +namespace flutter { + +class PointerDataDispatcher; + +//------------------------------------------------------------------------------ +/// The `Engine` pointer data dispatcher that forwards the packet received from +/// `PlatformView::DispatchPointerDataPacket` on the platform thread, to +/// `Window::DispatchPointerDataPacket` on the UI thread. +/// +/// This class is used to filter the packets so the Flutter framework on the UI +/// thread will receive packets with some desired properties. See +/// `SmoothPointerDataDispatcher` for an example which filters irregularly +/// delivered packets, and dispatches them in sync with the VSYNC signal. +/// +/// This object will be owned by the engine because it relies on the engine's +/// `Animator` (which owns `VsyncWaiter`) and `RuntimeController` to do the +/// filtering. This object is currently designed to be only called from the UI +/// thread (no thread safety is guaranteed). +/// +/// The `PlatformView` decides which subclass of `PointerDataDispatcher` is +/// constructed by sending a `PointerDataDispatcherMaker` to the engine's +/// constructor in `Shell::CreateShellOnPlatformThread`. This is needed because: +/// (1) Different platforms (e.g., Android, iOS) have different dispatchers +/// so the decision has to be made per `PlatformView`. +/// (2) The `PlatformView` can only be accessed from the PlatformThread while +/// this class (as owned by engine) can only be accessed in the UI thread. +/// Hence `PlatformView` creates a `PointerDataDispatchMaker` on the +/// platform thread, and sends it to the UI thread for the final +/// construction of the `PointerDataDispatcher`. +class PointerDataDispatcher { + public: + /// The interface for Engine to implement. + class Delegate { + public: + /// Actually dispatch the packet using Engine's `animator_` and + /// `runtime_controller_`. + virtual void DoDispatchPacket(std::unique_ptr packet, + uint64_t trace_flow_id) = 0; + + //-------------------------------------------------------------------------- + /// @brief Schedule a secondary callback to be executed right after the + /// main `VsyncWaiter::AsyncWaitForVsync` callback (which is added + /// by `Animator::RequestFrame`). + /// + /// Like the callback in `AsyncWaitForVsync`, this callback is + /// only scheduled to be called once per |id|, and it will be + /// called in the UI thread. If there is no AsyncWaitForVsync + /// callback (`Animator::RequestFrame` is not called), this + /// secondary callback will still be executed at vsync. + /// + /// This callback is used to provide the vsync signal needed by + /// `SmoothPointerDataDispatcher`, and for `Animator` input flow + /// events. + virtual void ScheduleSecondaryVsyncCallback( + uintptr_t id, + const fml::closure& callback) = 0; + }; + + //---------------------------------------------------------------------------- + /// @brief Signal that `PlatformView` has a packet to be dispatched. + /// + /// @param[in] packet The `PointerDataPacket` to be dispatched. + /// @param[in] trace_flow_id The id for `Animator::EnqueueTraceFlowId`. + virtual void DispatchPacket(std::unique_ptr packet, + uint64_t trace_flow_id) = 0; + + //---------------------------------------------------------------------------- + /// @brief Default destructor. + virtual ~PointerDataDispatcher(); +}; + +//------------------------------------------------------------------------------ +/// The default dispatcher that forwards the packet without any modification. +/// +class DefaultPointerDataDispatcher : public PointerDataDispatcher { + public: + explicit DefaultPointerDataDispatcher(Delegate& delegate) + : delegate_(delegate) {} + + // |PointerDataDispatcer| + void DispatchPacket(std::unique_ptr packet, + uint64_t trace_flow_id) override; + + virtual ~DefaultPointerDataDispatcher(); + + protected: + Delegate& delegate_; + + FML_DISALLOW_COPY_AND_ASSIGN(DefaultPointerDataDispatcher); +}; + +//------------------------------------------------------------------------------ +/// A dispatcher that may temporarily store and defer the last received +/// PointerDataPacket if multiple packets are received in one VSYNC. The +/// deferred packet will be sent in the next vsync in order to smooth out the +/// events. This filters out irregular input events delivery to provide a smooth +/// scroll on iPhone X/Xs. +/// +/// It works as follows: +/// +/// When `DispatchPacket` is called while a previous pointer data dispatch is +/// still in progress (its frame isn't finished yet), it means that an input +/// event is delivered to us too fast. That potentially means a later event will +/// be too late which could cause the missing of a frame. Hence we'll cache it +/// in `pending_packet_` for the next frame to smooth it out. +/// +/// If the input event is sent to us regularly at the same rate of VSYNC (say +/// at 60Hz), this would be identical to `DefaultPointerDataDispatcher` where +/// `runtime_controller_->DispatchPointerDataPacket` is always called right +/// away. That's because `is_pointer_data_in_progress_` will always be false +/// when `DispatchPacket` is called since it will be cleared by the end of a +/// frame through `ScheduleSecondaryVsyncCallback`. This is the case for all +/// Android/iOS devices before iPhone X/XS. +/// +/// If the input event is irregular, but with a random latency of no more than +/// one frame, this would guarantee that we'll miss at most 1 frame. Without +/// this, we could miss half of the frames. +/// +/// If the input event is delivered at a higher rate than that of VSYNC, this +/// would at most add a latency of one event delivery. For example, if the +/// input event is delivered at 120Hz (this is only true for iPad pro, not even +/// iPhone X), this may delay the handling of an input event by 8ms. +/// +/// The assumption of this solution is that the sampling itself is still +/// regular. Only the event delivery is allowed to be irregular. So far this +/// assumption seems to hold on all devices. If it's changed in the future, +/// we'll need a different solution. +/// +/// See also input_events_unittests.cc where we test all our claims above. +class SmoothPointerDataDispatcher : public DefaultPointerDataDispatcher { + public: + explicit SmoothPointerDataDispatcher(Delegate& delegate); + + // |PointerDataDispatcer| + void DispatchPacket(std::unique_ptr packet, + uint64_t trace_flow_id) override; + + virtual ~SmoothPointerDataDispatcher(); + + private: + void DispatchPendingPacket(); + void ScheduleSecondaryVsyncCallback(); + + // If non-null, this will be a pending pointer data packet for the next frame + // to consume. This is used to smooth out the irregular drag events delivery. + // See also `DispatchPointerDataPacket` and input_events_unittests.cc. + std::unique_ptr pending_packet_; + int pending_trace_flow_id_ = -1; + bool is_pointer_data_in_progress_ = false; + + // WeakPtrFactory must be the last member. + fml::WeakPtrFactory weak_factory_; + FML_DISALLOW_COPY_AND_ASSIGN(SmoothPointerDataDispatcher); +}; + +//-------------------------------------------------------------------------- +/// @brief Signature for constructing PointerDataDispatcher. +/// +/// @param[in] delegate the `Flutter::Engine` +/// +using PointerDataDispatcherMaker = + std::function( + PointerDataDispatcher::Delegate&)>; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_POINTER_DATA_DISPATCHER_H_ diff --git a/flutter/engine/src/flutter/shell/common/rasterizer.cc b/flutter/engine/src/flutter/shell/common/rasterizer.cc new file mode 100644 index 0000000000000000000000000000000000000000..287d5b0168ac3cf82e940b60fc729fa8c2129c92 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/rasterizer.cc @@ -0,0 +1,1169 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/rasterizer.h" + +#include +#include +#include + +#include "display_list/dl_builder.h" +#include "flow/frame_timings.h" +#include "flutter/common/constants.h" +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/flow/layers/offscreen_surface.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/shell/common/base64.h" +#include "flutter/shell/common/serialization_callbacks.h" +#include "fml/closure.h" +#include "fml/make_copyable.h" +#include "fml/synchronization/waitable_event.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkData.h" +#include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkImageInfo.h" +#include "third_party/skia/include/core/SkMatrix.h" +#include "third_party/skia/include/core/SkPictureRecorder.h" +#include "third_party/skia/include/core/SkRect.h" +#include "third_party/skia/include/core/SkSerialProcs.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/encode/SkPngEncoder.h" +#include "third_party/skia/include/gpu/GpuTypes.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/GrTypes.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" + +#if IMPELLER_SUPPORTS_RENDERING +#include "impeller/core/formats.h" // nogncheck +#include "impeller/display_list/aiks_context.h" // nogncheck +#include "impeller/display_list/dl_dispatcher.h" // nogncheck +#endif + +namespace flutter { + +// The rasterizer will tell Skia to purge cached resources that have not been +// used within this interval. +[[maybe_unused]] static constexpr std::chrono::milliseconds + kSkiaCleanupExpiration(15000); + +Rasterizer::Rasterizer(Delegate& delegate, + MakeGpuImageBehavior gpu_image_behavior) + : delegate_(delegate), + gpu_image_behavior_(gpu_image_behavior), + compositor_context_(std::make_unique(*this)), + snapshot_controller_( + SnapshotController::Make(*this, delegate.GetSettings())), + weak_factory_(this) { + FML_DCHECK(compositor_context_); +} + +Rasterizer::~Rasterizer() = default; + +fml::TaskRunnerAffineWeakPtr Rasterizer::GetWeakPtr() const { + return weak_factory_.GetWeakPtr(); +} + +fml::TaskRunnerAffineWeakPtr Rasterizer::GetSnapshotDelegate() + const { + return weak_factory_.GetWeakPtr(); +} + +void Rasterizer::SetImpellerContext( + std::weak_ptr impeller_context) { + impeller_context_ = std::move(impeller_context); +} + +void Rasterizer::Setup(std::unique_ptr surface) { + surface_ = std::move(surface); + + if (max_cache_bytes_.has_value()) { + SetResourceCacheMaxBytes(max_cache_bytes_.value(), + user_override_resource_cache_bytes_); + } + + auto context_switch = surface_->MakeRenderContextCurrent(); + if (context_switch->GetResult()) { + compositor_context_->OnGrContextCreated(); + } + + if (external_view_embedder_ && + external_view_embedder_->SupportsDynamicThreadMerging() && + !raster_thread_merger_) { + const auto platform_id = + delegate_.GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId(); + const auto gpu_id = + delegate_.GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(); + raster_thread_merger_ = fml::RasterThreadMerger::CreateOrShareThreadMerger( + delegate_.GetParentRasterThreadMerger(), platform_id, gpu_id); + } + if (raster_thread_merger_) { + raster_thread_merger_->SetMergeUnmergeCallback([this]() { + // Clear the GL context after the thread configuration has changed. + if (surface_) { + surface_->ClearRenderContext(); + } + }); + } +} + +void Rasterizer::TeardownExternalViewEmbedder() { + if (external_view_embedder_) { + external_view_embedder_->Teardown(); + } +} + +void Rasterizer::Teardown() { + is_torn_down_ = true; + if (surface_) { + auto context_switch = surface_->MakeRenderContextCurrent(); + if (context_switch->GetResult()) { + compositor_context_->OnGrContextDestroyed(); +#if !SLIMPELLER + if (auto* context = surface_->GetContext()) { + context->purgeUnlockedResources(GrPurgeResourceOptions::kAllResources); + } +#endif // !SLIMPELLER + } + surface_.reset(); + } + + view_records_.clear(); + + if (raster_thread_merger_.get() != nullptr && + raster_thread_merger_.get()->IsMerged()) { + FML_DCHECK(raster_thread_merger_->IsEnabled()); + raster_thread_merger_->UnMergeNowIfLastOne(); + raster_thread_merger_->SetMergeUnmergeCallback(nullptr); + } +} + +bool Rasterizer::IsTornDown() { + return is_torn_down_; +} + +std::optional Rasterizer::GetLastDrawStatus( + int64_t view_id) { + auto found = view_records_.find(view_id); + if (found != view_records_.end()) { + return found->second.last_draw_status; + } else { + return std::optional(); + } +} + +void Rasterizer::EnableThreadMergerIfNeeded() { + if (raster_thread_merger_) { + raster_thread_merger_->Enable(); + } +} + +void Rasterizer::DisableThreadMergerIfNeeded() { + if (raster_thread_merger_) { + raster_thread_merger_->Disable(); + } +} + +void Rasterizer::NotifyLowMemoryWarning() const { +#if !SLIMPELLER + if (!surface_) { + FML_DLOG(INFO) + << "Rasterizer::NotifyLowMemoryWarning called with no surface."; + return; + } + auto context = surface_->GetContext(); + if (!context) { + FML_DLOG(INFO) + << "Rasterizer::NotifyLowMemoryWarning called with no GrContext."; + return; + } + auto context_switch = surface_->MakeRenderContextCurrent(); + if (!context_switch->GetResult()) { + return; + } + context->performDeferredCleanup(std::chrono::milliseconds(0)); +#endif // !SLIMPELLER +} + +void Rasterizer::CollectView(int64_t view_id) { + if (external_view_embedder_) { + external_view_embedder_->CollectView(view_id); + } + view_records_.erase(view_id); +} + +std::shared_ptr Rasterizer::GetTextureRegistry() { + return compositor_context_->texture_registry(); +} + +GrDirectContext* Rasterizer::GetGrContext() { + return surface_ ? surface_->GetContext() : nullptr; +} + +flutter::LayerTree* Rasterizer::GetLastLayerTree(int64_t view_id) { + auto found = view_records_.find(view_id); + if (found == view_records_.end()) { + return nullptr; + } + auto& last_task = found->second.last_successful_task; + if (last_task == nullptr) { + return nullptr; + } + return last_task->layer_tree.get(); +} + +void Rasterizer::DrawLastLayerTrees( + std::unique_ptr frame_timings_recorder) { + if (!surface_) { + return; + } + std::vector> tasks; + for (auto& [view_id, view_record] : view_records_) { + if (view_record.last_successful_task) { + tasks.push_back(std::move(view_record.last_successful_task)); + } + } + if (tasks.empty()) { + return; + } + + DoDrawResult result = + DrawToSurfaces(*frame_timings_recorder, std::move(tasks)); + + // EndFrame should perform cleanups for the external_view_embedder. + if (external_view_embedder_ && external_view_embedder_->GetUsedThisFrame()) { + bool should_resubmit_frame = ShouldResubmitFrame(result); + external_view_embedder_->SetUsedThisFrame(false); + external_view_embedder_->EndFrame(should_resubmit_frame, + raster_thread_merger_); + } +} + +DrawStatus Rasterizer::Draw(const std::shared_ptr& pipeline) { + TRACE_EVENT0("flutter", "GPURasterizer::Draw"); + if (raster_thread_merger_ && + !raster_thread_merger_->IsOnRasterizingThread()) { + // we yield and let this frame be serviced on the right thread. + return DrawStatus::kYielded; + } + FML_DCHECK(delegate_.GetTaskRunners() + .GetRasterTaskRunner() + ->RunsTasksOnCurrentThread()); + + DoDrawResult draw_result; + FramePipeline::Consumer consumer = [&draw_result, + this](std::unique_ptr item) { + draw_result = DoDraw(std::move(item->frame_timings_recorder), + std::move(item->layer_tree_tasks)); + }; + + PipelineConsumeResult consume_result = pipeline->Consume(consumer); + if (consume_result == PipelineConsumeResult::NoneAvailable) { + return DrawStatus::kPipelineEmpty; + } + // if the raster status is to resubmit the frame, we push the frame to the + // front of the queue and also change the consume status to more available. + + bool should_resubmit_frame = ShouldResubmitFrame(draw_result); + if (should_resubmit_frame) { + FML_CHECK(draw_result.resubmitted_item); + auto front_continuation = pipeline->ProduceIfEmpty(); + PipelineProduceResult pipeline_result = + front_continuation.Complete(std::move(draw_result.resubmitted_item)); + if (pipeline_result.success) { + consume_result = PipelineConsumeResult::MoreAvailable; + } + } else if (draw_result.status == DoDrawStatus::kEnqueuePipeline) { + consume_result = PipelineConsumeResult::MoreAvailable; + } + + // EndFrame should perform cleanups for the external_view_embedder. + if (external_view_embedder_ && external_view_embedder_->GetUsedThisFrame()) { + external_view_embedder_->SetUsedThisFrame(false); + external_view_embedder_->EndFrame(should_resubmit_frame, + raster_thread_merger_); + } + + // Consume as many pipeline items as possible. But yield the event loop + // between successive tries. + switch (consume_result) { + case PipelineConsumeResult::MoreAvailable: { + delegate_.GetTaskRunners().GetRasterTaskRunner()->PostTask( + [weak_this = weak_factory_.GetWeakPtr(), pipeline]() { + if (weak_this) { + weak_this->Draw(pipeline); + } + }); + break; + } + default: + break; + } + + return ToDrawStatus(draw_result.status); +} + +bool Rasterizer::ShouldResubmitFrame(const DoDrawResult& result) { + if (result.resubmitted_item) { + FML_CHECK(!result.resubmitted_item->layer_tree_tasks.empty()); + return true; + } + return false; +} + +DrawStatus Rasterizer::ToDrawStatus(DoDrawStatus status) { + switch (status) { + case DoDrawStatus::kEnqueuePipeline: + return DrawStatus::kDone; + case DoDrawStatus::kNotSetUp: + return DrawStatus::kNotSetUp; + case DoDrawStatus::kGpuUnavailable: + return DrawStatus::kGpuUnavailable; + case DoDrawStatus::kDone: + return DrawStatus::kDone; + } + FML_UNREACHABLE(); +} + +#if !SLIMPELLER +namespace { +std::unique_ptr MakeBitmapImage( + const sk_sp& display_list, + const SkImageInfo& image_info) { + FML_DCHECK(display_list); + // Use 16384 as a proxy for the maximum texture size for a GPU image. + // This is meant to be large enough to avoid false positives in test contexts, + // but not so artificially large to be completely unrealistic on any platform. + // This limit is taken from the Metal specification. D3D, Vulkan, and GL + // generally have lower limits. + if (image_info.width() > 16384 || image_info.height() > 16384) { + return std::make_unique( + GrBackendTexture(), nullptr, nullptr, + "unable to create bitmap render target at specified size " + + std::to_string(image_info.width()) + "x" + + std::to_string(image_info.height())); + }; + + sk_sp surface = SkSurfaces::Raster(image_info); + auto canvas = DlSkCanvasAdapter(surface->getCanvas()); + canvas.Clear(DlColor::kTransparent()); + canvas.DrawDisplayList(display_list); + + sk_sp image = surface->makeImageSnapshot(); + return std::make_unique( + GrBackendTexture(), nullptr, image, + image ? "" : "Unable to create image"); +} +} // namespace +#endif // !SLIMPELLER + +std::unique_ptr Rasterizer::MakeSkiaGpuImage( + sk_sp display_list, + const SkImageInfo& image_info) { +#if SLIMPELLER + FML_LOG(FATAL) << "Impeller opt-out unavailable."; + return nullptr; +#else // SLIMPELLER + TRACE_EVENT0("flutter", "Rasterizer::MakeGpuImage"); + FML_DCHECK(display_list); + + std::unique_ptr result; + delegate_.GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers() + .SetIfTrue([&result, &image_info, &display_list] { + // TODO(dnfield): This isn't safe if display_list contains any GPU + // resources like an SkImage_gpu. + result = MakeBitmapImage(display_list, image_info); + }) + .SetIfFalse([&result, &image_info, &display_list, + surface = surface_.get(), + gpu_image_behavior = gpu_image_behavior_] { + if (!surface || + gpu_image_behavior == MakeGpuImageBehavior::kBitmap) { + // TODO(dnfield): This isn't safe if display_list contains any GPU + // resources like an SkImage_gpu. + result = MakeBitmapImage(display_list, image_info); + return; + } + + auto context_switch = surface->MakeRenderContextCurrent(); + if (!context_switch->GetResult()) { + result = MakeBitmapImage(display_list, image_info); + return; + } + + auto* context = surface->GetContext(); + if (!context) { + result = MakeBitmapImage(display_list, image_info); + return; + } + + GrBackendTexture texture = context->createBackendTexture( + image_info.width(), image_info.height(), image_info.colorType(), + skgpu::Mipmapped::kNo, GrRenderable::kYes); + if (!texture.isValid()) { + result = std::make_unique( + GrBackendTexture(), nullptr, nullptr, + "unable to create texture render target at specified size " + + std::to_string(image_info.width()) + "x" + + std::to_string(image_info.height())); + return; + } + + sk_sp sk_surface = SkSurfaces::WrapBackendTexture( + context, texture, kTopLeft_GrSurfaceOrigin, /*sampleCnt=*/0, + image_info.colorType(), image_info.refColorSpace(), nullptr); + if (!sk_surface) { + result = std::make_unique( + GrBackendTexture(), nullptr, nullptr, + "unable to create rendering surface for image"); + return; + } + + auto canvas = DlSkCanvasAdapter(sk_surface->getCanvas()); + canvas.Clear(DlColor::kTransparent()); + canvas.DrawDisplayList(display_list); + + result = std::make_unique( + texture, sk_ref_sp(context), nullptr, ""); + })); + return result; +#endif // !SLIMPELLER +} + +void Rasterizer::MakeRasterSnapshot( + sk_sp display_list, + SkISize picture_size, + std::function)> callback) { + return snapshot_controller_->MakeRasterSnapshot(display_list, picture_size, + callback); +} + +sk_sp Rasterizer::MakeRasterSnapshotSync( + sk_sp display_list, + SkISize picture_size) { + return snapshot_controller_->MakeRasterSnapshotSync(display_list, + picture_size); +} + +sk_sp Rasterizer::ConvertToRasterImage(sk_sp image) { + TRACE_EVENT0("flutter", __FUNCTION__); + return snapshot_controller_->ConvertToRasterImage(image); +} + +// |SnapshotDelegate| +void Rasterizer::CacheRuntimeStage( + const std::shared_ptr& runtime_stage) { + if (snapshot_controller_) { + snapshot_controller_->CacheRuntimeStage(runtime_stage); + } +} + +fml::Milliseconds Rasterizer::GetFrameBudget() const { + return delegate_.GetFrameBudget(); +}; + +Rasterizer::DoDrawResult Rasterizer::DoDraw( + std::unique_ptr frame_timings_recorder, + std::vector> tasks) { + TRACE_EVENT_WITH_FRAME_NUMBER(frame_timings_recorder, "flutter", + "Rasterizer::DoDraw", /*flow_id_count=*/0, + /*flow_ids=*/nullptr); + FML_DCHECK(delegate_.GetTaskRunners() + .GetRasterTaskRunner() + ->RunsTasksOnCurrentThread()); + frame_timings_recorder->AssertInState(FrameTimingsRecorder::State::kBuildEnd); + + if (tasks.empty()) { + return DoDrawResult{DoDrawStatus::kDone}; + } + if (!surface_) { + return DoDrawResult{DoDrawStatus::kNotSetUp}; + } + +#if !SLIMPELLER + PersistentCache* persistent_cache = PersistentCache::GetCacheForProcess(); + persistent_cache->ResetStoredNewShaders(); +#endif // !SLIMPELLER + + DoDrawResult result = + DrawToSurfaces(*frame_timings_recorder, std::move(tasks)); + + FML_DCHECK(result.status != DoDrawStatus::kEnqueuePipeline); + if (result.status == DoDrawStatus::kGpuUnavailable) { + return DoDrawResult{DoDrawStatus::kGpuUnavailable}; + } + +#if !SLIMPELLER + if (persistent_cache->IsDumpingSkp() && + persistent_cache->StoredNewShaders()) { + auto screenshot = + ScreenshotLastLayerTree(ScreenshotType::SkiaPicture, false); + persistent_cache->DumpSkp(*screenshot.data); + } +#endif // !SLIMPELLER + + // TODO(liyuqian): in Fuchsia, the rasterization doesn't finish when + // Rasterizer::DoDraw finishes. Future work is needed to adapt the timestamp + // for Fuchsia to capture SceneUpdateContext::ExecutePaintTasks. + delegate_.OnFrameRasterized(frame_timings_recorder->GetRecordedTime()); + +// SceneDisplayLag events are disabled on Fuchsia. +// see: https://github.com/flutter/flutter/issues/56598 +#if !defined(OS_FUCHSIA) + const fml::TimePoint raster_finish_time = + frame_timings_recorder->GetRasterEndTime(); + fml::TimePoint frame_target_time = + frame_timings_recorder->GetVsyncTargetTime(); + if (raster_finish_time > frame_target_time) { + fml::TimePoint latest_frame_target_time = + delegate_.GetLatestFrameTargetTime(); + const auto frame_budget_millis = delegate_.GetFrameBudget().count(); + if (latest_frame_target_time < raster_finish_time) { + latest_frame_target_time = + latest_frame_target_time + + fml::TimeDelta::FromMillisecondsF(frame_budget_millis); + } + const auto frame_lag = + (latest_frame_target_time - frame_target_time).ToMillisecondsF(); + const int vsync_transitions_missed = round(frame_lag / frame_budget_millis); + fml::tracing::TraceEventAsyncComplete( + "flutter", // category + "SceneDisplayLag", // name + raster_finish_time, // begin_time + latest_frame_target_time, // end_time + "frame_target_time", // arg_key_1 + frame_target_time, // arg_val_1 + "current_frame_target_time", // arg_key_2 + latest_frame_target_time, // arg_val_2 + "vsync_transitions_missed", // arg_key_3 + vsync_transitions_missed // arg_val_3 + ); + } +#endif + + // Pipeline pressure is applied from a couple of places: + // rasterizer: When there are more items as of the time of Consume. + // animator (via shell): Frame gets produces every vsync. + // Enqueing here is to account for the following scenario: + // T = 1 + // - one item (A) in the pipeline + // - rasterizer starts (and merges the threads) + // - pipeline consume result says no items to process + // T = 2 + // - animator produces (B) to the pipeline + // - applies pipeline pressure via platform thread. + // T = 3 + // - rasterizes finished (and un-merges the threads) + // - |Draw| for B yields as its on the wrong thread. + // This enqueue ensures that we attempt to consume from the right + // thread one more time after un-merge. + if (raster_thread_merger_) { + if (raster_thread_merger_->DecrementLease() == + fml::RasterThreadStatus::kUnmergedNow) { + return DoDrawResult{ + .status = DoDrawStatus::kEnqueuePipeline, + .resubmitted_item = std::move(result.resubmitted_item), + }; + } + } + + return result; +} + +Rasterizer::DoDrawResult Rasterizer::DrawToSurfaces( + FrameTimingsRecorder& frame_timings_recorder, + std::vector> tasks) { + TRACE_EVENT0("flutter", "Rasterizer::DrawToSurfaces"); + FML_DCHECK(surface_); + frame_timings_recorder.AssertInState(FrameTimingsRecorder::State::kBuildEnd); + + DoDrawResult result{ + .status = DoDrawStatus::kDone, + }; + if (surface_->AllowsDrawingWhenGpuDisabled()) { + result.resubmitted_item = + DrawToSurfacesUnsafe(frame_timings_recorder, std::move(tasks)); + } else { + delegate_.GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers() + .SetIfTrue([&] { + result.status = DoDrawStatus::kGpuUnavailable; + frame_timings_recorder.RecordRasterStart(fml::TimePoint::Now()); + frame_timings_recorder.RecordRasterEnd(); + }) + .SetIfFalse([&] { + result.resubmitted_item = DrawToSurfacesUnsafe( + frame_timings_recorder, std::move(tasks)); + })); + } + frame_timings_recorder.AssertInState(FrameTimingsRecorder::State::kRasterEnd); + + return result; +} + +std::unique_ptr Rasterizer::DrawToSurfacesUnsafe( + FrameTimingsRecorder& frame_timings_recorder, + std::vector> tasks) { + compositor_context_->ui_time().SetLapTime( + frame_timings_recorder.GetBuildDuration()); + + // First traverse: Filter out discarded trees + auto task_iter = tasks.begin(); + while (task_iter != tasks.end()) { + LayerTreeTask& task = **task_iter; + if (delegate_.ShouldDiscardLayerTree(task.view_id, *task.layer_tree)) { + EnsureViewRecord(task.view_id).last_draw_status = + DrawSurfaceStatus::kDiscarded; + task_iter = tasks.erase(task_iter); + } else { + ++task_iter; + } + } + if (tasks.empty()) { + frame_timings_recorder.RecordRasterStart(fml::TimePoint::Now()); + frame_timings_recorder.RecordRasterEnd(); + return nullptr; + } + + if (external_view_embedder_) { + FML_DCHECK(!external_view_embedder_->GetUsedThisFrame()); + external_view_embedder_->SetUsedThisFrame(true); + external_view_embedder_->BeginFrame(surface_->GetContext(), + raster_thread_merger_); + } + + std::optional presentation_time = std::nullopt; + // TODO (https://github.com/flutter/flutter/issues/105596): this can be in + // the past and might need to get snapped to future as this frame could + // have been resubmitted. `presentation_time` on SubmitInfo is not set + // in this case. + { + const auto vsync_target_time = frame_timings_recorder.GetVsyncTargetTime(); + if (vsync_target_time > fml::TimePoint::Now()) { + presentation_time = vsync_target_time; + } + } + + frame_timings_recorder.RecordRasterStart(fml::TimePoint::Now()); + + // Second traverse: draw all layer trees. + std::vector> resubmitted_tasks; + for (std::unique_ptr& task : tasks) { + int64_t view_id = task->view_id; + std::unique_ptr layer_tree = std::move(task->layer_tree); + float device_pixel_ratio = task->device_pixel_ratio; + + DrawSurfaceStatus status = DrawToSurfaceUnsafe( + view_id, *layer_tree, device_pixel_ratio, presentation_time); + FML_DCHECK(status != DrawSurfaceStatus::kDiscarded); + + auto& view_record = EnsureViewRecord(task->view_id); + view_record.last_draw_status = status; + if (status == DrawSurfaceStatus::kSuccess) { + view_record.last_successful_task = std::make_unique( + view_id, std::move(layer_tree), device_pixel_ratio); + } else if (status == DrawSurfaceStatus::kRetry) { + resubmitted_tasks.push_back(std::make_unique( + view_id, std::move(layer_tree), device_pixel_ratio)); + } + } + // TODO(dkwingsmt): Pass in raster cache(s) for all views. + // See https://github.com/flutter/flutter/issues/135530, item 4. + frame_timings_recorder.RecordRasterEnd( + NOT_SLIMPELLER(&compositor_context_->raster_cache())); + + FireNextFrameCallbackIfPresent(); + +#if !SLIMPELLER + if (surface_->GetContext()) { + surface_->GetContext()->performDeferredCleanup(kSkiaCleanupExpiration); + } +#endif // !SLIMPELLER + + if (resubmitted_tasks.empty()) { + return nullptr; + } else { + return std::make_unique( + std::move(resubmitted_tasks), + frame_timings_recorder.CloneUntil( + FrameTimingsRecorder::State::kBuildEnd)); + } +} + +/// \see Rasterizer::DrawToSurfaces +DrawSurfaceStatus Rasterizer::DrawToSurfaceUnsafe( + int64_t view_id, + flutter::LayerTree& layer_tree, + float device_pixel_ratio, + std::optional presentation_time) { + FML_DCHECK(surface_); + + DlCanvas* embedder_root_canvas = nullptr; + if (external_view_embedder_) { + external_view_embedder_->PrepareFlutterView( + ToSkISize(layer_tree.frame_size()), device_pixel_ratio); + // TODO(dkwingsmt): Add view ID here. + embedder_root_canvas = external_view_embedder_->GetRootCanvas(); + } + + // On Android, the external view embedder deletes surfaces in `BeginFrame`. + // + // Deleting a surface also clears the GL context. Therefore, acquire the + // frame after calling `BeginFrame` as this operation resets the GL context. + auto frame = surface_->AcquireFrame(ToSkISize(layer_tree.frame_size())); + if (frame == nullptr) { + return DrawSurfaceStatus::kFailed; + } + + // If the external view embedder has specified an optional root surface, the + // root surface transformation is set by the embedder instead of + // having to apply it here. + SkMatrix root_surface_transformation = + embedder_root_canvas ? SkMatrix{} : surface_->GetRootTransformation(); + + auto root_surface_canvas = + embedder_root_canvas ? embedder_root_canvas : frame->Canvas(); + auto compositor_frame = compositor_context_->AcquireFrame( + surface_->GetContext(), // skia GrContext + root_surface_canvas, // root surface canvas + external_view_embedder_.get(), // external view embedder + root_surface_transformation, // root surface transformation + true, // instrumentation enabled + frame->framebuffer_info() + .supports_readback, // surface supports pixel reads + raster_thread_merger_, // thread merger + surface_->GetAiksContext().get() // aiks context + ); + if (compositor_frame) { + NOT_SLIMPELLER(compositor_context_->raster_cache().BeginFrame()); + + std::unique_ptr damage; + // when leaf layer tracing is enabled we wish to repaint the whole frame + // for accurate performance metrics. + if (frame->framebuffer_info().supports_partial_repaint) { + // Disable partial repaint if external_view_embedder_ SubmitFlutterView is + // involved - ExternalViewEmbedder unconditionally clears the entire + // surface and also partial repaint with platform view present is + // something that still need to be figured out. + bool force_full_repaint = + external_view_embedder_ && + (!raster_thread_merger_ || raster_thread_merger_->IsMerged()); + + damage = std::make_unique(); + auto existing_damage = frame->framebuffer_info().existing_damage; + if (existing_damage.has_value() && !force_full_repaint) { + damage->SetPreviousLayerTree(GetLastLayerTree(view_id)); + damage->AddAdditionalDamage(ToDlIRect(existing_damage.value())); + damage->SetClipAlignment( + frame->framebuffer_info().horizontal_clip_alignment, + frame->framebuffer_info().vertical_clip_alignment); + } + } + + bool ignore_raster_cache = true; + if (surface_->EnableRasterCache()) { + ignore_raster_cache = false; + } + + RasterStatus frame_status = + compositor_frame->Raster(layer_tree, // layer tree + ignore_raster_cache, // ignore raster cache + damage.get() // frame damage + ); + if (frame_status == RasterStatus::kSkipAndRetry) { + return DrawSurfaceStatus::kRetry; + } + + SurfaceFrame::SubmitInfo submit_info; + submit_info.presentation_time = presentation_time; + if (damage) { + submit_info.frame_damage = ToOptSkIRect(damage->GetFrameDamage()); + submit_info.buffer_damage = ToOptSkIRect(damage->GetBufferDamage()); + } + + frame->set_submit_info(submit_info); + + if (external_view_embedder_ && + (!raster_thread_merger_ || raster_thread_merger_->IsMerged())) { + FML_DCHECK(!frame->IsSubmitted()); + external_view_embedder_->SubmitFlutterView( + view_id, surface_->GetContext(), surface_->GetAiksContext(), + std::move(frame)); + } else { + frame->Submit(); + } + +#if !SLIMPELLER + // Do not update raster cache metrics for kResubmit because that status + // indicates that the frame was not actually painted. + if (frame_status != RasterStatus::kResubmit) { + compositor_context_->raster_cache().EndFrame(); + } +#endif // !SLIMPELLER + + if (frame_status == RasterStatus::kResubmit) { + return DrawSurfaceStatus::kRetry; + } else { + FML_CHECK(frame_status == RasterStatus::kSuccess); + return DrawSurfaceStatus::kSuccess; + } + } + + return DrawSurfaceStatus::kFailed; +} + +Rasterizer::ViewRecord& Rasterizer::EnsureViewRecord(int64_t view_id) { + return view_records_[view_id]; +} + +static sk_sp ScreenshotLayerTreeAsPicture( + flutter::LayerTree* tree, + flutter::CompositorContext& compositor_context) { +#if SLIMPELLER + return nullptr; +#else // SLIMPELLER + FML_DCHECK(tree != nullptr); + SkPictureRecorder recorder; + recorder.beginRecording( + SkRect::MakeWH(tree->frame_size().width, tree->frame_size().height)); + + SkMatrix root_surface_transformation; + root_surface_transformation.reset(); + DlSkCanvasAdapter canvas(recorder.getRecordingCanvas()); + + // TODO(amirh): figure out how to take a screenshot with embedded UIView. + // https://github.com/flutter/flutter/issues/23435 + auto frame = compositor_context.AcquireFrame(nullptr, &canvas, nullptr, + root_surface_transformation, + false, true, nullptr, nullptr); + frame->Raster(*tree, true, nullptr); + +#if defined(OS_FUCHSIA) + SkSerialProcs procs = {0}; + procs.fImageProc = SerializeImageWithoutData; + procs.fTypefaceProc = SerializeTypefaceWithoutData; +#else + SkSerialProcs procs = {0}; + procs.fTypefaceProc = SerializeTypefaceWithData; + procs.fImageProc = [](SkImage* img, void*) -> sk_sp { + return SkPngEncoder::Encode(nullptr, img, SkPngEncoder::Options{}); + }; +#endif + + return recorder.finishRecordingAsPicture()->serialize(&procs); +#endif // SLIMPELLER +} + +static void RenderFrameForScreenshot( + flutter::CompositorContext& compositor_context, + DlCanvas* canvas, + flutter::LayerTree* tree, + GrDirectContext* surface_context, + const std::shared_ptr& aiks_context) { + // There is no root surface transformation for the screenshot layer. Reset + // the matrix to identity. + SkMatrix root_surface_transformation; + root_surface_transformation.reset(); + + auto frame = compositor_context.AcquireFrame( + /*gr_context=*/surface_context, + /*canvas=*/canvas, + /*view_embedder=*/nullptr, + /*root_surface_transformation=*/root_surface_transformation, + /*instrumentation_enabled=*/false, + /*surface_supports_readback=*/true, + /*raster_thread_merger=*/nullptr, + /*aiks_context=*/aiks_context.get()); + canvas->Clear(DlColor::kTransparent()); + frame->Raster(*tree, true, nullptr); + canvas->Flush(); +} + +#if IMPELLER_SUPPORTS_RENDERING +Rasterizer::ScreenshotFormat ToScreenshotFormat(impeller::PixelFormat format) { + switch (format) { + case impeller::PixelFormat::kUnknown: + case impeller::PixelFormat::kA8UNormInt: + case impeller::PixelFormat::kR8UNormInt: + case impeller::PixelFormat::kR8G8UNormInt: + case impeller::PixelFormat::kR8G8B8A8UNormIntSRGB: + case impeller::PixelFormat::kB8G8R8A8UNormIntSRGB: + case impeller::PixelFormat::kB10G10R10XRSRGB: + case impeller::PixelFormat::kS8UInt: + case impeller::PixelFormat::kD24UnormS8Uint: + case impeller::PixelFormat::kD32FloatS8UInt: + case impeller::PixelFormat::kR32G32B32A32Float: + case impeller::PixelFormat::kB10G10R10XR: + case impeller::PixelFormat::kB10G10R10A10XR: + FML_DCHECK(false); + return Rasterizer::ScreenshotFormat::kUnknown; + case impeller::PixelFormat::kR8G8B8A8UNormInt: + return Rasterizer::ScreenshotFormat::kR8G8B8A8UNormInt; + case impeller::PixelFormat::kB8G8R8A8UNormInt: + return Rasterizer::ScreenshotFormat::kB8G8R8A8UNormInt; + case impeller::PixelFormat::kR16G16B16A16Float: + return Rasterizer::ScreenshotFormat::kR16G16B16A16Float; + } +} + +static std::pair, Rasterizer::ScreenshotFormat> +ScreenshotLayerTreeAsImageImpeller( + const std::shared_ptr& aiks_context, + flutter::LayerTree* tree, + flutter::CompositorContext& compositor_context, + bool compressed) { + if (compressed) { + FML_LOG(ERROR) << "Compressed screenshots not supported for Impeller"; + return {nullptr, Rasterizer::ScreenshotFormat::kUnknown}; + } + + DisplayListBuilder builder(DlRect::MakeSize(tree->frame_size())); + + RenderFrameForScreenshot(compositor_context, &builder, tree, nullptr, + aiks_context); + + std::shared_ptr texture = impeller::DisplayListToTexture( + builder.Build(), impeller::ISize(tree->frame_size()), *aiks_context); + if (!texture) { + FML_LOG(ERROR) << "Failed to render to texture"; + return {nullptr, Rasterizer::ScreenshotFormat::kUnknown}; + } + + impeller::DeviceBufferDescriptor buffer_desc; + buffer_desc.storage_mode = impeller::StorageMode::kHostVisible; + buffer_desc.size = + texture->GetTextureDescriptor().GetByteSizeOfBaseMipLevel(); + auto impeller_context = aiks_context->GetContext(); + auto buffer = + impeller_context->GetResourceAllocator()->CreateBuffer(buffer_desc); + auto command_buffer = impeller_context->CreateCommandBuffer(); + command_buffer->SetLabel("BlitTextureToBuffer Command Buffer"); + auto pass = command_buffer->CreateBlitPass(); + pass->AddCopy(texture, buffer); + pass->EncodeCommands(); + fml::AutoResetWaitableEvent latch; + sk_sp sk_data; + auto completion = [buffer, &buffer_desc, &sk_data, + &latch](impeller::CommandBuffer::Status status) { + fml::ScopedCleanupClosure cleanup([&latch]() { latch.Signal(); }); + if (status != impeller::CommandBuffer::Status::kCompleted) { + FML_LOG(ERROR) << "Failed to complete blit pass."; + return; + } + sk_data = SkData::MakeWithCopy(buffer->OnGetContents(), buffer_desc.size); + }; + + if (!impeller_context->GetCommandQueue() + ->Submit({command_buffer}, completion) + .ok()) { + FML_LOG(ERROR) << "Failed to submit commands."; + } + latch.Wait(); + return std::make_pair( + sk_data, ToScreenshotFormat(texture->GetTextureDescriptor().format)); +} +#endif + +std::pair, Rasterizer::ScreenshotFormat> +Rasterizer::ScreenshotLayerTreeAsImage( + flutter::LayerTree* tree, + flutter::CompositorContext& compositor_context, + bool compressed) { +#if IMPELLER_SUPPORTS_RENDERING + if (delegate_.GetSettings().enable_impeller) { + return ScreenshotLayerTreeAsImageImpeller(GetAiksContext(), tree, + compositor_context, compressed); + } +#endif // IMPELLER_SUPPORTS_RENDERING + +#if SLIMPELLER + FML_LOG(FATAL) << "Impeller opt-out unavailable."; + return {nullptr, ScreenshotFormat::kUnknown}; +#else // SLIMPELLER + GrDirectContext* surface_context = GetGrContext(); + // Attempt to create a snapshot surface depending on whether we have access + // to a valid GPU rendering context. + std::unique_ptr snapshot_surface = + std::make_unique(surface_context, tree->frame_size()); + + if (!snapshot_surface->IsValid()) { + FML_LOG(ERROR) << "Screenshot: unable to create snapshot surface"; + return {nullptr, ScreenshotFormat::kUnknown}; + } + + // Draw the current layer tree into the snapshot surface. + DlCanvas* canvas = snapshot_surface->GetCanvas(); + + // snapshot_surface->makeImageSnapshot needs the GL context to be set if the + // render context is GL. frame->Raster() pops the gl context in platforms + // that gl context switching are used. (For example, older iOS that uses GL) + // We reset the GL context using the context switch. + auto context_switch = surface_->MakeRenderContextCurrent(); + if (!context_switch->GetResult()) { + FML_LOG(ERROR) << "Screenshot: unable to make image screenshot"; + return {nullptr, ScreenshotFormat::kUnknown}; + } + + RenderFrameForScreenshot(compositor_context, canvas, tree, surface_context, + nullptr); + + return std::make_pair(snapshot_surface->GetRasterData(compressed), + ScreenshotFormat::kUnknown); +#endif // !SLIMPELLER +} + +Rasterizer::Screenshot Rasterizer::ScreenshotLastLayerTree( + Rasterizer::ScreenshotType type, + bool base64_encode) { + if (delegate_.GetSettings().enable_impeller && + type == ScreenshotType::SkiaPicture) { + FML_DCHECK(false); + FML_LOG(ERROR) << "Last layer tree cannot be screenshotted as a " + "SkiaPicture when using Impeller."; + return {}; + } + // TODO(dkwingsmt): Support screenshotting all last layer trees + // when the shell protocol supports multi-views. + // https://github.com/flutter/flutter/issues/135534 + // https://github.com/flutter/flutter/issues/135535 + auto* layer_tree = GetLastLayerTree(kFlutterImplicitViewId); + if (layer_tree == nullptr) { + FML_LOG(ERROR) << "Last layer tree was null when screenshotting."; + return {}; + } + + std::pair, ScreenshotFormat> data{nullptr, + ScreenshotFormat::kUnknown}; + std::string format; + + switch (type) { + case ScreenshotType::SkiaPicture: + format = "ScreenshotType::SkiaPicture"; + data.first = + ScreenshotLayerTreeAsPicture(layer_tree, *compositor_context_); + break; + case ScreenshotType::UncompressedImage: + format = "ScreenshotType::UncompressedImage"; + data = + ScreenshotLayerTreeAsImage(layer_tree, *compositor_context_, false); + break; + case ScreenshotType::CompressedImage: + format = "ScreenshotType::CompressedImage"; + data = ScreenshotLayerTreeAsImage(layer_tree, *compositor_context_, true); + break; + case ScreenshotType::SurfaceData: { + Surface::SurfaceData surface_data = surface_->GetSurfaceData(); + format = surface_data.pixel_format; + data.first = surface_data.data; + break; + } + } + + if (data.first == nullptr) { + FML_LOG(ERROR) << "Screenshot data was null."; + return {}; + } + + if (base64_encode) { + size_t b64_size = Base64::EncodedSize(data.first->size()); + auto b64_data = SkData::MakeUninitialized(b64_size); + Base64::Encode(data.first->data(), data.first->size(), + b64_data->writable_data()); + return Rasterizer::Screenshot{b64_data, ToSkISize(layer_tree->frame_size()), + format, data.second}; + } + + return Rasterizer::Screenshot{data.first, ToSkISize(layer_tree->frame_size()), + format, data.second}; +} + +void Rasterizer::SetNextFrameCallback(const fml::closure& callback) { + next_frame_callback_ = callback; +} + +void Rasterizer::SetExternalViewEmbedder( + const std::shared_ptr& view_embedder) { + external_view_embedder_ = view_embedder; +} + +void Rasterizer::SetSnapshotSurfaceProducer( + std::unique_ptr producer) { + snapshot_surface_producer_ = std::move(producer); +} + +fml::RefPtr Rasterizer::GetRasterThreadMerger() { + return raster_thread_merger_; +} + +void Rasterizer::FireNextFrameCallbackIfPresent() { + if (!next_frame_callback_) { + return; + } + // It is safe for the callback to set a new callback. + auto callback = next_frame_callback_; + next_frame_callback_ = nullptr; + callback(); +} + +void Rasterizer::SetResourceCacheMaxBytes(size_t max_bytes, bool from_user) { +#if !SLIMPELLER + user_override_resource_cache_bytes_ |= from_user; + + if (!from_user && user_override_resource_cache_bytes_) { + // We should not update the setting here if a user has explicitly set a + // value for this over the flutter/skia channel. + return; + } + + max_cache_bytes_ = max_bytes; + if (!surface_) { + return; + } + + GrDirectContext* context = surface_->GetContext(); + if (context) { + auto context_switch = surface_->MakeRenderContextCurrent(); + if (!context_switch->GetResult()) { + return; + } + + context->setResourceCacheLimit(max_bytes); + } +#endif // !SLIMPELLER +} + +std::optional Rasterizer::GetResourceCacheMaxBytes() const { +#if SLIMPELLER + return std::nullopt; +#else // SLIMPELLER + if (!surface_) { + return std::nullopt; + } + GrDirectContext* context = surface_->GetContext(); + if (context) { + return context->getResourceCacheLimit(); + } + return std::nullopt; +#endif // SLIMPELLER +} + +Rasterizer::Screenshot::Screenshot() {} + +Rasterizer::Screenshot::Screenshot(sk_sp p_data, + SkISize p_size, + const std::string& p_format, + ScreenshotFormat p_pixel_format) + : data(std::move(p_data)), + frame_size(p_size), + format(p_format), + pixel_format(p_pixel_format) {} + +Rasterizer::Screenshot::Screenshot(const Screenshot& other) = default; + +Rasterizer::Screenshot::~Screenshot() = default; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/rasterizer.h b/flutter/engine/src/flutter/shell/common/rasterizer.h new file mode 100644 index 0000000000000000000000000000000000000000..806d83c28281135654a0808d1958aa79cc4a837f --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/rasterizer.h @@ -0,0 +1,779 @@ +// 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_COMMON_RASTERIZER_H_ +#define FLUTTER_SHELL_COMMON_RASTERIZER_H_ + +#include +#include +#include + +#include "flutter/common/settings.h" +#include "flutter/common/task_runners.h" +#include "flutter/display_list/image/dl_image.h" +#include "flutter/flow/compositor_context.h" +#include "flutter/flow/embedded_views.h" +#include "flutter/flow/frame_timings.h" +#include "flutter/flow/layers/layer_tree.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/closure.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/fml/raster_thread_merger.h" +#include "flutter/fml/synchronization/sync_switch.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/fml/time/time_point.h" +#if IMPELLER_SUPPORTS_RENDERING +#include "impeller/core/formats.h" // nogncheck +#include "impeller/display_list/aiks_context.h" // nogncheck +#include "impeller/renderer/context.h" // nogncheck +#include "impeller/typographer/backends/skia/typographer_context_skia.h" // nogncheck +#endif // IMPELLER_SUPPORTS_RENDERING +#include "flutter/lib/ui/snapshot_delegate.h" +#include "flutter/shell/common/pipeline.h" +#include "flutter/shell/common/snapshot_controller.h" +#include "flutter/shell/common/snapshot_surface_producer.h" +#include "third_party/skia/include/core/SkData.h" +#include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkRect.h" +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +#if !IMPELLER_SUPPORTS_RENDERING +namespace impeller { +class Context; +class AiksContext; +} // namespace impeller +#endif // !IMPELLER_SUPPORTS_RENDERING + +namespace flutter { + +// The result status of Rasterizer::Draw. This is only used for unit tests. +enum class DrawStatus { + // The drawing was done without any specified status. + kDone, + // Failed to rasterize the frame because the Rasterizer is not set up. + kNotSetUp, + // Nothing was done, because the call was not on the raster thread. Yielded to + // let this frame be serviced on the right thread. + kYielded, + // Nothing was done, because the pipeline was empty. + kPipelineEmpty, + // Nothing was done, because the GPU was unavailable. + kGpuUnavailable, +}; + +// The result status of drawing to a view. This is only used for unit tests. +enum class DrawSurfaceStatus { + // The layer tree was successfully rasterized. + kSuccess, + // The layer tree must be submitted again. + // + // This can occur on Android when switching the background surface to + // FlutterImageView. On Android, the first frame doesn't make the image + // available to the ImageReader right away. The second frame does. + // TODO(egarciad): https://github.com/flutter/flutter/issues/65652 + // + // This can also occur when the frame is dropped to wait for the thread + // merger to merge the raster and platform threads. + kRetry, + // Failed to rasterize the frame. + kFailed, + // Layer tree was discarded because its size does not match the view size. + // This typically occurs during resizing. + kDiscarded, +}; + +// The information to draw to all views of a frame. +struct FrameItem { + FrameItem(std::vector> tasks, + std::unique_ptr frame_timings_recorder) + : layer_tree_tasks(std::move(tasks)), + frame_timings_recorder(std::move(frame_timings_recorder)) {} + std::vector> layer_tree_tasks; + std::unique_ptr frame_timings_recorder; +}; + +using FramePipeline = Pipeline; + +//------------------------------------------------------------------------------ +/// The rasterizer is a component owned by the shell that resides on the raster +/// task runner. Each shell owns exactly one instance of a rasterizer. The +/// rasterizer may only be created, used and collected on the raster task +/// runner. +/// +/// The rasterizer owns the instance of the currently active on-screen render +/// surface. On this surface, it renders the contents of layer trees submitted +/// to it by the `Engine` (which lives on the UI task runner). +/// +/// The primary components owned by the rasterizer are the compositor context +/// and the on-screen render surface. The compositor context has all the GPU +/// state necessary to render frames to the render surface. +/// +class Rasterizer final : public SnapshotDelegate, + public Stopwatch::RefreshRateUpdater, + public SnapshotController::Delegate { + public: + //---------------------------------------------------------------------------- + /// @brief Used to forward events from the rasterizer to interested + /// subsystems. Currently, the shell sets itself up as the + /// rasterizer delegate to listen for frame rasterization events. + /// It can then forward these events to the engine. + /// + /// Like all rasterizer operation, the rasterizer delegate call + /// are made on the raster task runner. Any delegate must ensure + /// that they can handle the threading implications. + /// + class Delegate { + public: + //-------------------------------------------------------------------------- + /// @brief Notifies the delegate that a frame has been rendered. The + /// rasterizer collects profiling information for each part of + /// the frame workload. This profiling information is made + /// available to the delegate for forwarding to subsystems + /// interested in collecting such profiles. Currently, the shell + /// (the delegate) forwards this to the engine where Dart code + /// can react to this information. + /// + /// @see `FrameTiming` + /// + /// @param[in] frame_timing Instrumentation information for each phase of + /// the frame workload. + /// + virtual void OnFrameRasterized(const FrameTiming& frame_timing) = 0; + + /// Time limit for a smooth frame. + /// + /// See: `DisplayManager::GetMainDisplayRefreshRate`. + virtual fml::Milliseconds GetFrameBudget() = 0; + + /// Target time for the latest frame. See also `Shell::OnAnimatorBeginFrame` + /// for when this time gets updated. + virtual fml::TimePoint GetLatestFrameTargetTime() const = 0; + + /// Task runners used by the shell. + virtual const TaskRunners& GetTaskRunners() const = 0; + + /// The raster thread merger from parent shell's rasterizer. + virtual const fml::RefPtr + GetParentRasterThreadMerger() const = 0; + + /// Accessor for the shell's GPU sync switch, which determines whether GPU + /// operations are allowed on the current thread. + /// + /// For example, on some platforms when the application is backgrounded it + /// is critical that GPU operations are not processed. + virtual std::shared_ptr GetIsGpuDisabledSyncSwitch() + const = 0; + + virtual const Settings& GetSettings() const = 0; + + virtual bool ShouldDiscardLayerTree(int64_t view_id, + const flutter::LayerTree& tree) = 0; + }; + + //---------------------------------------------------------------------------- + /// @brief How to handle calls to MakeSkiaGpuImage. + enum class MakeGpuImageBehavior { + /// MakeSkiaGpuImage returns a GPU resident image, if possible. + kGpu, + /// MakeSkiaGpuImage returns a checkerboard bitmap. This is useful in test + /// contexts where no GPU surface is available. + kBitmap, + }; + + //---------------------------------------------------------------------------- + /// @brief Creates a new instance of a rasterizer. Rasterizers may only + /// be created on the raster task runner. Rasterizers are + /// currently only created by the shell (which also sets itself up + /// as the rasterizer delegate). + /// + /// @param[in] delegate The rasterizer delegate. + /// @param[in] gpu_image_behavior How to handle calls to + /// MakeSkiaGpuImage. + /// + explicit Rasterizer( + Delegate& delegate, + MakeGpuImageBehavior gpu_image_behavior = MakeGpuImageBehavior::kGpu); + + //---------------------------------------------------------------------------- + /// @brief Destroys the rasterizer. This must happen on the raster task + /// runner. All GPU resources are collected before this call + /// returns. Any context set up by the embedder to hold these + /// resources can be immediately collected as well. + /// + ~Rasterizer(); + + void SetImpellerContext(std::weak_ptr impeller_context); + + //---------------------------------------------------------------------------- + /// @brief Rasterizers may be created well before an on-screen surface is + /// available for rendering. Shells usually create a rasterizer in + /// their constructors. Once an on-screen surface is available + /// however, one may be provided to the rasterizer using this + /// call. No rendering may occur before this call. The surface is + /// held till the balancing call to `Rasterizer::Teardown` is + /// made. Calling a setup before tearing down the previous surface + /// (if this is not the first time the surface has been set up) is + /// user error. + /// + /// @see `Rasterizer::Teardown` + /// + /// @param[in] surface The on-screen render surface. + /// + void Setup(std::unique_ptr surface); + + //---------------------------------------------------------------------------- + /// @brief Releases the previously set up on-screen render surface and + /// collects associated resources. No more rendering may occur + /// till the next call to `Rasterizer::Setup` with a new render + /// surface. Calling a teardown without a setup is user error. + /// Calling this method multiple times is safe. + /// + void Teardown(); + + //---------------------------------------------------------------------------- + /// @brief Releases any resource used by the external view embedder. + /// For example, overlay surfaces or Android views. + /// On Android, this method post a task to the platform thread, + /// and waits until it completes. + void TeardownExternalViewEmbedder(); + + //---------------------------------------------------------------------------- + /// @brief Notifies the rasterizer that there is a low memory situation + /// and it must purge as many unnecessary resources as possible. + /// Currently, the Skia context associated with onscreen rendering + /// is told to free GPU resources. + /// + void NotifyLowMemoryWarning() const; + + //---------------------------------------------------------------------------- + /// @brief Gets a weak pointer to the rasterizer. The rasterizer may only + /// be accessed on the raster task runner. + /// + /// @return The weak pointer to the rasterizer. + /// + fml::TaskRunnerAffineWeakPtr GetWeakPtr() const; + + fml::TaskRunnerAffineWeakPtr GetSnapshotDelegate() const; + + //---------------------------------------------------------------------------- + /// @brief Deallocate the resources for displaying a view. + /// + /// This method must be called on the raster task runner when a + /// view is removed from the engine. + /// + /// When the rasterizer is requested to draw an unrecognized view, + /// it implicitly allocates necessary resources. These resources + /// must be explicitly deallocated. + /// + /// @param[in] view_id The ID of the view. + /// + void CollectView(int64_t view_id); + + //---------------------------------------------------------------------------- + /// @brief Returns the last successfully drawn layer tree for the given + /// view, or nullptr if there isn't any. This is useful during + /// `DrawLastLayerTrees` and computing frame damage. + /// + /// @bug https://github.com/flutter/flutter/issues/33939 + /// + /// @return A pointer to the last layer or `nullptr` if this rasterizer + /// has never rendered a frame to the given view. + /// + flutter::LayerTree* GetLastLayerTree(int64_t view_id); + + //---------------------------------------------------------------------------- + /// @brief Draws the last layer trees with their last configuration. This + /// may seem entirely redundant at first glance. After all, on + /// surface loss and re-acquisition, the framework generates a new + /// layer tree. Otherwise, why render the same contents to the + /// screen again? This is used as an optimization in cases where + /// there are external textures (video or camera streams for + /// example) in referenced in the layer tree. These textures may + /// be updated at a cadence different from that of the Flutter + /// application. Flutter can re-render the layer tree with just + /// the updated textures instead of waiting for the framework to + /// do the work to generate the layer tree describing the same + /// contents. + /// + /// Calling this method clears all last layer trees + /// (GetLastLayerTree). + /// + void DrawLastLayerTrees( + std::unique_ptr frame_timings_recorder); + + // |SnapshotDelegate| + GrDirectContext* GetGrContext() override; + + std::shared_ptr GetTextureRegistry() override; + + //---------------------------------------------------------------------------- + /// @brief Takes the next item from the layer tree pipeline and executes + /// the raster thread frame workload for that pipeline item to + /// render a frame on the on-screen surface. + /// + /// Why does the draw call take a layer tree pipeline and not the + /// layer tree directly? + /// + /// The pipeline is the way book-keeping of frame workloads + /// distributed across the multiple threads is managed. The + /// rasterizer deals with the pipelines directly (instead of layer + /// trees which is what it actually renders) because the pipeline + /// consumer's workload must be accounted for within the pipeline + /// itself. If the rasterizer took the layer tree directly, it + /// would have to be taken out of the pipeline. That would signal + /// the end of the frame workload and the pipeline would be ready + /// for new frames. But the last frame has not been rendered by + /// the frame yet! On the other hand, the pipeline must own the + /// layer tree it renders because it keeps a reference to the last + /// layer tree around till a new frame is rendered. So a simple + /// reference wont work either. The `Rasterizer::DoDraw` method + /// actually performs the GPU operations within the layer tree + /// pipeline. + /// + /// @see `Rasterizer::DoDraw` + /// + /// @param[in] pipeline The layer tree pipeline to take the next layer tree + /// to render from. + /// + DrawStatus Draw(const std::shared_ptr& pipeline); + + //---------------------------------------------------------------------------- + /// @brief The type of the screenshot to obtain of the previously + /// rendered layer tree. + /// + enum class ScreenshotType { + // NOLINTBEGIN(readability-identifier-naming) + //-------------------------------------------------------------------------- + /// A format used to denote a Skia picture. A Skia picture is a serialized + /// representation of an `SkPicture` that can be used to introspect the + /// series of commands used to draw that picture. + /// + /// Skia pictures are typically stored as files with the .skp extension on + /// disk. These files may be viewed in an interactive debugger available at + /// https://debugger.skia.org/ + /// + SkiaPicture, + + //-------------------------------------------------------------------------- + /// A format used to denote uncompressed image data. For Skia, this format + /// is 32 bits per pixel, 8 bits per component and + /// denoted by the `kN32_SkColorType ` Skia color type. For Impeller, its + /// format is specified in Screenshot::pixel_format. + /// + UncompressedImage, + + //-------------------------------------------------------------------------- + /// A format used to denote compressed image data. The PNG compressed + /// container is used. + /// + CompressedImage, + + //-------------------------------------------------------------------------- + /// Reads the data directly from the Rasterizer's surface. The pixel format + /// is determined from the surface. This is the only way to read wide gamut + /// color data, but isn't supported everywhere. + SurfaceData, + // NOLINTEND(readability-identifier-naming) + }; + + // Specifies the format of pixel data in a Screenshot. + enum class ScreenshotFormat { + // Unknown format, or Skia default. + kUnknown, + // RGBA 8 bits per channel. + kR8G8B8A8UNormInt, + // BGRA 8 bits per channel. + kB8G8R8A8UNormInt, + // RGBA 16 bit floating point per channel. + kR16G16B16A16Float, + }; + + //---------------------------------------------------------------------------- + /// @brief A POD type used to return the screenshot data along with the + /// size of the frame. + /// + struct Screenshot { + //-------------------------------------------------------------------------- + /// The data used to describe the screenshot. The data format depends on the + /// type of screenshot taken and any further encoding done to the same. + /// + /// @see `ScreenshotType` + /// + sk_sp data; + + //-------------------------------------------------------------------------- + /// The size of the screenshot in texels. + /// + SkISize frame_size = SkISize::MakeEmpty(); + + //-------------------------------------------------------------------------- + /// Characterization of the format of the data in `data`. + /// + std::string format; + + //-------------------------------------------------------------------------- + /// The pixel format of the data in `data`. + /// + /// If the impeller backend is not used, this value is always kUnknown and + /// the data is in RGBA8888 format. + ScreenshotFormat pixel_format = ScreenshotFormat::kUnknown; + + //-------------------------------------------------------------------------- + /// @brief Creates an empty screenshot + /// + Screenshot(); + + //-------------------------------------------------------------------------- + /// @brief Creates a screenshot with the specified data and size. + /// + /// @param[in] p_data The screenshot data + /// @param[in] p_size The screenshot size. + /// @param[in] p_format The screenshot format. + /// @param[in] p_pixel_format The screenshot format. + /// + Screenshot(sk_sp p_data, + SkISize p_size, + const std::string& p_format, + ScreenshotFormat p_pixel_format); + + //-------------------------------------------------------------------------- + /// @brief The copy constructor for a screenshot. + /// + /// @param[in] other The screenshot to copy from. + /// + Screenshot(const Screenshot& other); + + //-------------------------------------------------------------------------- + /// @brief Destroys the screenshot object and releases underlying data. + /// + ~Screenshot(); + }; + + //---------------------------------------------------------------------------- + /// @brief Screenshots the last layer tree to one of the supported + /// screenshot types and optionally Base 64 encodes that data for + /// easier transmission and packaging (usually over the service + /// protocol for instrumentation tools running on the host). + /// + /// @param[in] type The type of the screenshot to gather. + /// @param[in] base64_encode Whether Base 64 encoding must be applied to the + /// data after a screenshot has been captured. + /// + /// @return A non-empty screenshot if one could be captured. A screenshot + /// capture may fail if there were no layer trees previously + /// rendered by this rasterizer, or, due to an unspecified + /// internal error. Internal error will be logged to the console. + /// + Screenshot ScreenshotLastLayerTree(ScreenshotType type, bool base64_encode); + + //---------------------------------------------------------------------------- + /// @brief Sets a callback that will be executed when the next layer tree + /// in rendered to the on-screen surface. This is used by + /// embedders to listen for one time operations like listening for + /// when the first frame is rendered so that they may hide splash + /// screens. + /// + /// The callback is only executed once and dropped on the GPU + /// thread when executed (lambda captures must be able to deal + /// with the threading repercussions of this behavior). + /// + /// @param[in] callback The callback to execute when the next layer tree is + /// rendered on-screen. + /// + void SetNextFrameCallback(const fml::closure& callback); + + //---------------------------------------------------------------------------- + /// @brief Set the External View Embedder. This is done on shell + /// initialization. This is non-null on platforms that support + /// embedding externally composited views. + /// + /// @param[in] view_embedder The external view embedder object. + /// + void SetExternalViewEmbedder( + const std::shared_ptr& view_embedder); + + //---------------------------------------------------------------------------- + /// @brief Set the snapshot surface producer. This is done on shell + /// initialization. This is non-null on platforms that support taking + /// GPU accelerated raster snapshots in the background. + /// + /// @param[in] producer A surface producer for raster snapshotting when the + /// onscreen surface is not available. + /// + void SetSnapshotSurfaceProducer( + std::unique_ptr producer); + + //---------------------------------------------------------------------------- + /// @brief Returns a pointer to the compositor context used by this + /// rasterizer. This pointer will never be `nullptr`. + /// + /// @return The compositor context used by this rasterizer. + /// + flutter::CompositorContext* compositor_context() { + return compositor_context_.get(); + } + + //---------------------------------------------------------------------------- + /// @brief Returns the raster thread merger used by this rasterizer. + /// This may be `nullptr`. + /// + /// @return The raster thread merger used by this rasterizer. + /// + fml::RefPtr GetRasterThreadMerger(); + + //---------------------------------------------------------------------------- + /// @brief Skia has no notion of time. To work around the performance + /// implications of this, it may cache GPU resources to reference + /// them from one frame to the next. Using this call, embedders + /// may set the maximum bytes cached by Skia in its caches + /// dedicated to on-screen rendering. + /// + /// @attention This cache setting will be invalidated when the surface is + /// torn down via `Rasterizer::Teardown`. This call must be made + /// again with new limits after surface re-acquisition. + /// + /// @attention This cache does not describe the entirety of GPU resources + /// that may be cached. The `RasterCache` also holds very large + /// GPU resources. + /// + /// @see `RasterCache` + /// + /// @param[in] max_bytes The maximum byte size of resource that may be + /// cached for GPU rendering. + /// @param[in] from_user Whether this request was from user code, e.g. via + /// the flutter/skia message channel, in which case + /// it should not be overridden by the platform. + /// + void SetResourceCacheMaxBytes(size_t max_bytes, bool from_user); + + //---------------------------------------------------------------------------- + /// @brief The current value of Skia's resource cache size, if a surface + /// is present. + /// + /// @attention This cache does not describe the entirety of GPU resources + /// that may be cached. The `RasterCache` also holds very large + /// GPU resources. + /// + /// @see `RasterCache` + /// + /// @return The size of Skia's resource cache, if available. + /// + std::optional GetResourceCacheMaxBytes() const; + + //---------------------------------------------------------------------------- + /// @brief Enables the thread merger if the external view embedder + /// supports dynamic thread merging. + /// + /// @attention This method is thread-safe. When the thread merger is enabled, + /// the raster task queue can run in the platform thread at any + /// time. + /// + /// @see `ExternalViewEmbedder` + /// + void EnableThreadMergerIfNeeded(); + + //---------------------------------------------------------------------------- + /// @brief Disables the thread merger if the external view embedder + /// supports dynamic thread merging. + /// + /// @attention This method is thread-safe. When the thread merger is + /// disabled, the raster task queue will continue to run in the + /// same thread until |EnableThreadMergerIfNeeded| is called. + /// + /// @see `ExternalViewEmbedder` + /// + void DisableThreadMergerIfNeeded(); + + //---------------------------------------------------------------------------- + /// @brief Returns whether TearDown has been called. + /// + /// This method is used only in unit tests. + /// + bool IsTornDown(); + + //---------------------------------------------------------------------------- + /// @brief Returns the last status of drawing the specific view. + /// + /// This method is used only in unit tests. + /// + std::optional GetLastDrawStatus(int64_t view_id); + + private: + // The result status of DoDraw, DrawToSurfaces, and DrawToSurfacesUnsafe. + enum class DoDrawStatus { + // The drawing was done without any specified status. + kDone, + // Frame has been successfully rasterized, but there are additional items + // in the pipeline waiting to be consumed. This is currently only used when + // thread configuration change occurs. + kEnqueuePipeline, + // Failed to rasterize the frame because the Rasterizer is not set up. + kNotSetUp, + // Nothing was done, because GPU was unavailable. + kGpuUnavailable, + }; + + // The result of DoDraw. + struct DoDrawResult { + // The overall status of the drawing process. + // + // The status of drawing a specific view is available at GetLastDrawStatus. + DoDrawStatus status = DoDrawStatus::kDone; + + // The frame item that needs to be submitted again. + // + // See RasterStatus::kResubmit and kSkipAndRetry for when it happens. + // + // If `resubmitted_item` is not null, its `tasks` is guaranteed to be + // non-empty. + std::unique_ptr resubmitted_item; + }; + + struct ViewRecord { + std::unique_ptr last_successful_task; + std::optional last_draw_status; + }; + + // |SnapshotDelegate| + std::unique_ptr MakeSkiaGpuImage( + sk_sp display_list, + const SkImageInfo& image_info) override; + + // |SnapshotDelegate| + void MakeRasterSnapshot( + sk_sp display_list, + SkISize picture_size, + std::function)> callback) override; + + // |SnapshotDelegate| + sk_sp MakeRasterSnapshotSync(sk_sp display_list, + SkISize picture_size) override; + + // |SnapshotDelegate| + sk_sp ConvertToRasterImage(sk_sp image) override; + + // |SnapshotDelegate| + void CacheRuntimeStage( + const std::shared_ptr& runtime_stage) override; + + // |Stopwatch::Delegate| + /// Time limit for a smooth frame. + /// + /// See: `DisplayManager::GetMainDisplayRefreshRate`. + fml::Milliseconds GetFrameBudget() const override; + + // |SnapshotController::Delegate| + const std::unique_ptr& GetSurface() const override { + return surface_; + } + + // |SnapshotController::Delegate| + bool IsAiksContextInitialized() const override { +#if IMPELLER_SUPPORTS_RENDERING + return surface_ && surface_->GetAiksContext(); +#else + return false; +#endif + } + + // |SnapshotController::Delegate| + std::shared_ptr GetAiksContext() const override { +#if IMPELLER_SUPPORTS_RENDERING + if (surface_) { + return surface_->GetAiksContext(); + } + if (auto context = impeller_context_.lock()) { + return std::make_shared( + context, impeller::TypographerContextSkia::Make()); + } +#endif + return nullptr; + } + + // |SnapshotController::Delegate| + const std::unique_ptr& GetSnapshotSurfaceProducer() + const override { + return snapshot_surface_producer_; + } + + // |SnapshotController::Delegate| + std::shared_ptr GetIsGpuDisabledSyncSwitch() + const override { + return delegate_.GetIsGpuDisabledSyncSwitch(); + } + + std::pair, ScreenshotFormat> ScreenshotLayerTreeAsImage( + flutter::LayerTree* tree, + flutter::CompositorContext& compositor_context, + bool compressed); + + // This method starts with the frame timing recorder at build end. This + // method might push it to raster end and get the recorded time, or abort in + // the middle and not get the recorded time. + DoDrawResult DoDraw( + std::unique_ptr frame_timings_recorder, + std::vector> tasks); + + // This method pushes the frame timing recorder from build end to raster end. + DoDrawResult DrawToSurfaces( + FrameTimingsRecorder& frame_timings_recorder, + std::vector> tasks); + + // Draws the specified layer trees to views, assuming we have access to the + // GPU. + // + // If any layer trees need resubmitting, this method returns the frame item to + // be resubmitted. Otherwise, it returns nullptr. + // + // Unsafe because it assumes we have access to the GPU which isn't the case + // when iOS is backgrounded, for example. + // + // This method pushes the frame timing recorder from build end to raster end. + std::unique_ptr DrawToSurfacesUnsafe( + FrameTimingsRecorder& frame_timings_recorder, + std::vector> tasks); + + // Draws the layer tree to the specified view, assuming we have access to the + // GPU. + // + // This method is not affiliated with the frame timing recorder, but must be + // included between the RasterStart and RasterEnd. + DrawSurfaceStatus DrawToSurfaceUnsafe( + int64_t view_id, + flutter::LayerTree& layer_tree, + float device_pixel_ratio, + std::optional presentation_time); + + ViewRecord& EnsureViewRecord(int64_t view_id); + + void FireNextFrameCallbackIfPresent(); + + static bool ShouldResubmitFrame(const DoDrawResult& result); + static DrawStatus ToDrawStatus(DoDrawStatus status); + + bool is_torn_down_ = false; + Delegate& delegate_; + [[maybe_unused]] MakeGpuImageBehavior gpu_image_behavior_; + std::weak_ptr impeller_context_; + std::unique_ptr surface_; + std::unique_ptr snapshot_surface_producer_; + std::unique_ptr compositor_context_; + std::unordered_map view_records_; + fml::closure next_frame_callback_; + bool user_override_resource_cache_bytes_ = false; + std::optional max_cache_bytes_; + fml::RefPtr raster_thread_merger_; + std::shared_ptr external_view_embedder_; + std::unique_ptr snapshot_controller_; + + // WeakPtrFactory must be the last member. + fml::TaskRunnerAffineWeakPtrFactory weak_factory_; + FML_DISALLOW_COPY_AND_ASSIGN(Rasterizer); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_RASTERIZER_H_ diff --git a/flutter/engine/src/flutter/shell/common/rasterizer_unittests.cc b/flutter/engine/src/flutter/shell/common/rasterizer_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..629fc57a8051b79dc3988fdf44b2e8137fc9ed75 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/rasterizer_unittests.cc @@ -0,0 +1,1411 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include "flow/surface_frame.h" +#include "flutter/shell/common/rasterizer.h" + +#include +#include + +#include "flutter/flow/frame_timings.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/testing/testing.h" + +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrTypes.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" + +#include "gmock/gmock.h" + +using testing::_; +using testing::ByMove; +using testing::NiceMock; +using testing::Return; +using testing::ReturnRef; + +namespace flutter { +namespace { + +constexpr float kDevicePixelRatio = 2.0f; +constexpr int64_t kImplicitViewId = 0; + +std::vector> SingleLayerTreeList( + int64_t view_id, + std::unique_ptr layer_tree, + float pixel_ratio) { + std::vector> tasks; + tasks.push_back(std::make_unique( + view_id, std::move(layer_tree), pixel_ratio)); + return tasks; +} + +class MockDelegate : public Rasterizer::Delegate { + public: + MOCK_METHOD(void, + OnFrameRasterized, + (const FrameTiming& frame_timing), + (override)); + MOCK_METHOD(fml::Milliseconds, GetFrameBudget, (), (override)); + MOCK_METHOD(fml::TimePoint, GetLatestFrameTargetTime, (), (const, override)); + MOCK_METHOD(const TaskRunners&, GetTaskRunners, (), (const, override)); + MOCK_METHOD(const fml::RefPtr, + GetParentRasterThreadMerger, + (), + (const, override)); + MOCK_METHOD(std::shared_ptr, + GetIsGpuDisabledSyncSwitch, + (), + (const, override)); + MOCK_METHOD(const Settings&, GetSettings, (), (const, override)); + MOCK_METHOD(bool, + ShouldDiscardLayerTree, + (int64_t, const flutter::LayerTree&), + (override)); +}; + +class MockSurface : public Surface { + public: + MOCK_METHOD(bool, IsValid, (), (override)); + MOCK_METHOD(std::unique_ptr, + AcquireFrame, + (const SkISize& size), + (override)); + MOCK_METHOD(SkMatrix, GetRootTransformation, (), (const, override)); + MOCK_METHOD(GrDirectContext*, GetContext, (), (override)); + MOCK_METHOD(std::unique_ptr, + MakeRenderContextCurrent, + (), + (override)); + MOCK_METHOD(bool, ClearRenderContext, (), (override)); + MOCK_METHOD(bool, AllowsDrawingWhenGpuDisabled, (), (const, override)); +}; + +class MockExternalViewEmbedder : public ExternalViewEmbedder { + public: + MOCK_METHOD(DlCanvas*, GetRootCanvas, (), (override)); + MOCK_METHOD(void, CancelFrame, (), (override)); + MOCK_METHOD( + void, + BeginFrame, + (GrDirectContext * context, + const fml::RefPtr& raster_thread_merger), + (override)); + MOCK_METHOD(void, + PrepareFlutterView, + (SkISize frame_size, double device_pixel_ratio), + (override)); + MOCK_METHOD(void, + PrerollCompositeEmbeddedView, + (int64_t view_id, std::unique_ptr params), + (override)); + MOCK_METHOD( + PostPrerollResult, + PostPrerollAction, + (const fml::RefPtr& raster_thread_merger), + (override)); + MOCK_METHOD(DlCanvas*, CompositeEmbeddedView, (int64_t view_id), (override)); + MOCK_METHOD(void, + SubmitFlutterView, + (int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame), + (override)); + MOCK_METHOD( + void, + EndFrame, + (bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger), + (override)); + MOCK_METHOD(bool, SupportsDynamicThreadMerging, (), (override)); +}; +} // namespace + +TEST(RasterizerTest, create) { + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + auto rasterizer = std::make_unique(delegate); + EXPECT_TRUE(rasterizer != nullptr); +} + +TEST(RasterizerTest, isAiksContextInitialized) { + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + auto rasterizer = std::make_shared(delegate); + + EXPECT_TRUE(rasterizer != nullptr); + std::shared_ptr snapshot_delegate = rasterizer; + + EXPECT_FALSE(snapshot_delegate->IsAiksContextInitialized()); +} + +static std::unique_ptr CreateFinishedBuildRecorder( + fml::TimePoint timestamp) { + std::unique_ptr recorder = + std::make_unique(); + recorder->RecordVsync(timestamp, timestamp); + recorder->RecordBuildStart(timestamp); + recorder->RecordBuildEnd(timestamp); + return recorder; +} + +static std::unique_ptr CreateFinishedBuildRecorder() { + return CreateFinishedBuildRecorder(fml::TimePoint::Now()); +} + +TEST(RasterizerTest, drawEmptyPipeline) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + ON_CALL(delegate, GetTaskRunners()).WillByDefault(ReturnRef(task_runners)); + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + rasterizer->Setup(std::move(surface)); + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + latch.Signal(); + }); + latch.Wait(); +} + +TEST(RasterizerTest, + drawWithExternalViewEmbedderExternalViewEmbedderSubmitFrameCalled) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)); + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + + std::shared_ptr> external_view_embedder = + std::make_shared>(); + rasterizer->SetExternalViewEmbedder(external_view_embedder); + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + auto surface_frame = std::make_unique( + /*surface=*/ + nullptr, framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillOnce(Return(true)); + EXPECT_CALL(*surface, AcquireFrame(SkISize())) + .WillOnce(Return(ByMove(std::move(surface_frame)))); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + + EXPECT_CALL(*external_view_embedder, + BeginFrame(/*context=*/nullptr, + /*raster_thread_merger=*/ + fml::RefPtr(nullptr))) + .Times(1); + EXPECT_CALL(*external_view_embedder, PrepareFlutterView( + /*frame_size=*/SkISize(), + /*device_pixel_ratio=*/2.0)) + .Times(1); + EXPECT_CALL(*external_view_embedder, + SubmitFlutterView(/*flutter_view_id=*/kImplicitViewId, _, _, _)) + .Times(1); + EXPECT_CALL( + *external_view_embedder, + EndFrame(/*should_resubmit_frame=*/false, + /*raster_thread_merger=*/fml::RefPtr( + nullptr))) + .Times(1); + + rasterizer->Setup(std::move(surface)); + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique(/*root_layer=*/nullptr, + /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + latch.Signal(); + }); + latch.Wait(); +} + +TEST( + RasterizerTest, + drawWithExternalViewEmbedderAndThreadMergerNotMergedExternalViewEmbedderSubmitFrameNotCalled) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)); + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + std::shared_ptr> external_view_embedder = + std::make_shared>(); + rasterizer->SetExternalViewEmbedder(external_view_embedder); + EXPECT_CALL(*external_view_embedder, SupportsDynamicThreadMerging) + .WillRepeatedly(Return(true)); + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + auto surface_frame = std::make_unique( + /*surface=*/ + nullptr, framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillOnce(Return(true)); + EXPECT_CALL(*surface, AcquireFrame(SkISize())) + .WillOnce(Return(ByMove(std::move(surface_frame)))); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + + EXPECT_CALL(*external_view_embedder, BeginFrame(/*context=*/nullptr, + /*raster_thread_merger=*/_)) + .Times(1); + EXPECT_CALL(*external_view_embedder, PrepareFlutterView( + /*frame_size=*/SkISize(), + /*device_pixel_ratio=*/2.0)) + .Times(1); + EXPECT_CALL(*external_view_embedder, + SubmitFlutterView(/*flutter_view_id=*/kImplicitViewId, _, _, _)) + .Times(0); + EXPECT_CALL(*external_view_embedder, EndFrame(/*should_resubmit_frame=*/false, + /*raster_thread_merger=*/_)) + .Times(1); + + rasterizer->Setup(std::move(surface)); + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + latch.Signal(); + }); + latch.Wait(); +} + +TEST( + RasterizerTest, + drawWithExternalViewEmbedderAndThreadsMergedExternalViewEmbedderSubmitFrameCalled) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + fml::MessageLoop::EnsureInitializedForCurrentThread(); + TaskRunners task_runners("test", + fml::MessageLoop::GetCurrent().GetTaskRunner(), + fml::MessageLoop::GetCurrent().GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)); + + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + + std::shared_ptr> external_view_embedder = + std::make_shared>(); + rasterizer->SetExternalViewEmbedder(external_view_embedder); + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + auto surface_frame = std::make_unique( + /*surface=*/ + nullptr, framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillOnce(Return(true)); + EXPECT_CALL(*surface, AcquireFrame(SkISize())) + .WillOnce(Return(ByMove(std::move(surface_frame)))); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + EXPECT_CALL(*external_view_embedder, SupportsDynamicThreadMerging) + .WillRepeatedly(Return(true)); + + EXPECT_CALL(*external_view_embedder, BeginFrame(/*context=*/nullptr, + /*raster_thread_merger=*/_)) + .Times(1); + EXPECT_CALL(*external_view_embedder, PrepareFlutterView( + /*frame_size=*/SkISize(), + /*device_pixel_ratio=*/2.0)) + .Times(1); + EXPECT_CALL(*external_view_embedder, + SubmitFlutterView(/*flutter_view_id=*/kImplicitViewId, _, _, _)) + .Times(1); + EXPECT_CALL(*external_view_embedder, EndFrame(/*should_resubmit_frame=*/false, + /*raster_thread_merger=*/_)) + .Times(1); + + rasterizer->Setup(std::move(surface)); + + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique(/*root_layer=*/nullptr, + /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); +} + +TEST(RasterizerTest, + drawLastLayerTreeWithThreadsMergedExternalViewEmbedderAndEndFrameCalled) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + fml::MessageLoop::EnsureInitializedForCurrentThread(); + TaskRunners task_runners("test", + fml::MessageLoop::GetCurrent().GetTaskRunner(), + fml::MessageLoop::GetCurrent().GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)); + + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + + std::shared_ptr> external_view_embedder = + std::make_shared>(); + rasterizer->SetExternalViewEmbedder(external_view_embedder); + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + auto surface_frame1 = std::make_unique( + /*surface=*/ + nullptr, framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + auto surface_frame2 = std::make_unique( + /*surface=*/ + nullptr, framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()) + .WillRepeatedly(Return(true)); + // Prepare two frames for Draw() and DrawLastLayerTrees(). + EXPECT_CALL(*surface, AcquireFrame(SkISize())) + .WillOnce(Return(ByMove(std::move(surface_frame1)))) + .WillOnce(Return(ByMove(std::move(surface_frame2)))); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + EXPECT_CALL(*external_view_embedder, SupportsDynamicThreadMerging) + .WillRepeatedly(Return(true)); + + EXPECT_CALL(*external_view_embedder, BeginFrame(/*context=*/nullptr, + /*raster_thread_merger=*/_)) + .Times(2); + EXPECT_CALL(*external_view_embedder, PrepareFlutterView( + /*frame_size=*/SkISize(), + /*device_pixel_ratio=*/2.0)) + .Times(2); + EXPECT_CALL(*external_view_embedder, + SubmitFlutterView(/*flutter_view_id=*/kImplicitViewId, _, _, _)) + .Times(2); + EXPECT_CALL(*external_view_embedder, EndFrame(/*should_resubmit_frame=*/false, + /*raster_thread_merger=*/_)) + .Times(2); + + rasterizer->Setup(std::move(surface)); + + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique(/*root_layer=*/nullptr, + /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + + // The Draw() will respectively call BeginFrame(), SubmitFlutterView() and + // EndFrame() one time. + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + + // The DrawLastLayerTrees() will respectively call BeginFrame(), + // SubmitFlutterView() and EndFrame() one more time, totally 2 times. + rasterizer->DrawLastLayerTrees(CreateFinishedBuildRecorder()); +} + +TEST(RasterizerTest, externalViewEmbedderDoesntEndFrameWhenNoSurfaceIsSet) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + auto rasterizer = std::make_unique(delegate); + + std::shared_ptr> external_view_embedder = + std::make_shared>(); + rasterizer->SetExternalViewEmbedder(external_view_embedder); + + EXPECT_CALL( + *external_view_embedder, + EndFrame(/*should_resubmit_frame=*/false, + /*raster_thread_merger=*/fml::RefPtr( + nullptr))) + .Times(0); + + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + latch.Signal(); + }); + latch.Wait(); +} + +TEST(RasterizerTest, externalViewEmbedderDoesntEndFrameWhenNotUsedThisFrame) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + auto is_gpu_disabled_sync_switch = + std::make_shared(false); + ON_CALL(delegate, GetIsGpuDisabledSyncSwitch()) + .WillByDefault(Return(is_gpu_disabled_sync_switch)); + + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + + std::shared_ptr> external_view_embedder = + std::make_shared>(); + rasterizer->SetExternalViewEmbedder(external_view_embedder); + rasterizer->Setup(std::move(surface)); + + EXPECT_CALL(*external_view_embedder, BeginFrame(/*context=*/nullptr, + /*raster_thread_merger=*/_)) + .Times(0); + EXPECT_CALL(*external_view_embedder, PrepareFlutterView( + /*frame_size=*/SkISize(), + /*device_pixel_ratio=*/2.0)) + .Times(0); + EXPECT_CALL( + *external_view_embedder, + EndFrame(/*should_resubmit_frame=*/false, + /*raster_thread_merger=*/fml::RefPtr( + nullptr))) + .Times(0); + + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + // Always discard the layer tree. + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(true)); + DrawStatus status = rasterizer->Draw(pipeline); + EXPECT_EQ(status, DrawStatus::kDone); + EXPECT_EQ(rasterizer->GetLastDrawStatus(kImplicitViewId), + DrawSurfaceStatus::kDiscarded); + latch.Signal(); + }); + latch.Wait(); +} + +TEST(RasterizerTest, externalViewEmbedderDoesntEndFrameWhenPipelineIsEmpty) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + + std::shared_ptr> external_view_embedder = + std::make_shared>(); + rasterizer->SetExternalViewEmbedder(external_view_embedder); + rasterizer->Setup(std::move(surface)); + + EXPECT_CALL( + *external_view_embedder, + EndFrame(/*should_resubmit_frame=*/false, + /*raster_thread_merger=*/fml::RefPtr( + nullptr))) + .Times(0); + + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + DrawStatus status = rasterizer->Draw(pipeline); + EXPECT_EQ(status, DrawStatus::kPipelineEmpty); + latch.Signal(); + }); + latch.Wait(); +} + +TEST(RasterizerTest, drawMultipleViewsWithExternalViewEmbedder) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)); + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + std::shared_ptr> external_view_embedder = + std::make_shared>(); + rasterizer->SetExternalViewEmbedder(external_view_embedder); + EXPECT_CALL(*external_view_embedder, SupportsDynamicThreadMerging) + .WillRepeatedly(Return(false)); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillOnce(Return(true)); + EXPECT_CALL(*surface, AcquireFrame(SkISize())).Times(2); + ON_CALL(*surface, AcquireFrame).WillByDefault([](const SkISize& size) { + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + return std::make_unique( + /*surface=*/ + nullptr, framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + }); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + + EXPECT_CALL(*external_view_embedder, BeginFrame(/*context=*/nullptr, + /*raster_thread_merger=*/_)) + .Times(1); + EXPECT_CALL(*external_view_embedder, + PrepareFlutterView(/*frame_size=*/SkISize(), + /*device_pixel_ratio=*/1.5)) + .Times(1); + EXPECT_CALL(*external_view_embedder, + SubmitFlutterView(/*flutter_view_id=*/0, _, _, _)) + .Times(1); + EXPECT_CALL(*external_view_embedder, + PrepareFlutterView(/*frame_size=*/SkISize(), + /*device_pixel_ratio=*/2.0)) + .Times(1); + EXPECT_CALL(*external_view_embedder, + SubmitFlutterView(/*flutter_view_id=*/1, _, _, _)) + .Times(1); + EXPECT_CALL(*external_view_embedder, EndFrame(/*should_resubmit_frame=*/false, + /*raster_thread_merger=*/_)) + .Times(1); + + rasterizer->Setup(std::move(surface)); + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + std::vector> tasks; + tasks.push_back(std::make_unique( + 0, std::make_unique(nullptr, DlISize()), 1.5)); + tasks.push_back(std::make_unique( + 1, std::make_unique(nullptr, DlISize()), 2.0)); + auto layer_tree_item = std::make_unique( + std::move(tasks), CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + latch.Signal(); + }); + latch.Wait(); +} + +TEST(RasterizerTest, + drawWithGpuEnabledAndSurfaceAllowsDrawingWhenGpuDisabledDoesAcquireFrame) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)); + + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + auto is_gpu_disabled_sync_switch = + std::make_shared(false); + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + auto surface_frame = std::make_unique( + /*surface=*/ + nullptr, /*framebuffer_info=*/framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillOnce(Return(true)); + ON_CALL(delegate, GetIsGpuDisabledSyncSwitch()) + .WillByDefault(Return(is_gpu_disabled_sync_switch)); + EXPECT_CALL(delegate, GetIsGpuDisabledSyncSwitch()).Times(0); + EXPECT_CALL(*surface, AcquireFrame(SkISize())) + .WillOnce(Return(ByMove(std::move(surface_frame)))); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + + rasterizer->Setup(std::move(surface)); + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + latch.Signal(); + }); + latch.Wait(); +} + +TEST( + RasterizerTest, + drawWithGpuDisabledAndSurfaceAllowsDrawingWhenGpuDisabledDoesAcquireFrame) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)); + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + auto is_gpu_disabled_sync_switch = + std::make_shared(true); + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + auto surface_frame = std::make_unique( + /*surface=*/ + nullptr, /*framebuffer_info=*/framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillOnce(Return(true)); + ON_CALL(delegate, GetIsGpuDisabledSyncSwitch()) + .WillByDefault(Return(is_gpu_disabled_sync_switch)); + EXPECT_CALL(delegate, GetIsGpuDisabledSyncSwitch()).Times(0); + EXPECT_CALL(*surface, AcquireFrame(SkISize())) + .WillOnce(Return(ByMove(std::move(surface_frame)))); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + + rasterizer->Setup(std::move(surface)); + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + DrawStatus status = rasterizer->Draw(pipeline); + EXPECT_EQ(status, DrawStatus::kDone); + latch.Signal(); + }); + latch.Wait(); +} + +TEST( + RasterizerTest, + drawWithGpuEnabledAndSurfaceDisallowsDrawingWhenGpuDisabledDoesAcquireFrame) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)); + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + auto is_gpu_disabled_sync_switch = + std::make_shared(false); + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + auto surface_frame = std::make_unique( + /*surface=*/ + nullptr, /*framebuffer_info=*/framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillOnce(Return(false)); + EXPECT_CALL(delegate, GetIsGpuDisabledSyncSwitch()) + .WillOnce(Return(is_gpu_disabled_sync_switch)); + EXPECT_CALL(*surface, AcquireFrame(SkISize())) + .WillOnce(Return(ByMove(std::move(surface_frame)))); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + + rasterizer->Setup(std::move(surface)); + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + DrawStatus status = rasterizer->Draw(pipeline); + EXPECT_EQ(status, DrawStatus::kDone); + latch.Signal(); + }); + latch.Wait(); +} + +TEST( + RasterizerTest, + drawWithGpuDisabledAndSurfaceDisallowsDrawingWhenGpuDisabledDoesntAcquireFrame) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)).Times(0); + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + auto is_gpu_disabled_sync_switch = + std::make_shared(true); + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + auto surface_frame = std::make_unique( + /*surface=*/ + nullptr, /*framebuffer_info=*/framebuffer_info, + /*encode_callback=*/[](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame&) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillOnce(Return(false)); + EXPECT_CALL(delegate, GetIsGpuDisabledSyncSwitch()) + .WillOnce(Return(is_gpu_disabled_sync_switch)); + EXPECT_CALL(*surface, AcquireFrame(SkISize())).Times(0); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + + rasterizer->Setup(std::move(surface)); + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + DrawStatus status = rasterizer->Draw(pipeline); + EXPECT_EQ(status, DrawStatus::kGpuUnavailable); + latch.Signal(); + }); + latch.Wait(); +} + +TEST( + RasterizerTest, + FrameTimingRecorderShouldStartRecordingRasterTimeBeforeSurfaceAcquireFrame) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + EXPECT_CALL(delegate, OnFrameRasterized(_)) + .WillOnce([&](const FrameTiming& frame_timing) { + fml::TimePoint now = fml::TimePoint::Now(); + fml::TimePoint raster_start = + frame_timing.Get(FrameTiming::kRasterStart); + EXPECT_TRUE(now - raster_start < fml::TimeDelta::FromSecondsF(1)); + }); + + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + auto is_gpu_disabled_sync_switch = + std::make_shared(false); + ON_CALL(delegate, GetIsGpuDisabledSyncSwitch()) + .WillByDefault(Return(is_gpu_disabled_sync_switch)); + ON_CALL(*surface, AcquireFrame(SkISize())) + .WillByDefault(::testing::Invoke([] { return nullptr; })); + EXPECT_CALL(*surface, AcquireFrame(SkISize())); + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillOnce(Return(ByMove(std::make_unique(true)))); + rasterizer->Setup(std::move(surface)); + fml::AutoResetWaitableEvent latch; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder()); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + DrawStatus status = rasterizer->Draw(pipeline); + EXPECT_EQ(status, DrawStatus::kDone); + EXPECT_EQ(rasterizer->GetLastDrawStatus(kImplicitViewId), + DrawSurfaceStatus::kFailed); + latch.Signal(); + }); + latch.Wait(); +} + +TEST(RasterizerTest, + drawLayerTreeWithCorrectFrameTimingWhenPipelineIsMoreAvailable) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + ON_CALL(delegate, GetTaskRunners()).WillByDefault(ReturnRef(task_runners)); + + fml::AutoResetWaitableEvent latch; + std::unique_ptr rasterizer; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + rasterizer = std::make_unique(delegate); + latch.Signal(); + }); + latch.Wait(); + + auto surface = std::make_unique>(); + EXPECT_CALL(*surface, AllowsDrawingWhenGpuDisabled()) + .WillRepeatedly(Return(true)); + ON_CALL(*surface, AcquireFrame(SkISize())) + .WillByDefault(::testing::Invoke([] { + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + return std::make_unique( + /*surface=*/ + nullptr, framebuffer_info, + /*encode_callback=*/ + [](const SurfaceFrame&, DlCanvas*) { return true; }, + /*submit_callback=*/[](const SurfaceFrame& frame) { return true; }, + /*frame_size=*/SkISize::Make(800, 600)); + })); + ON_CALL(*surface, MakeRenderContextCurrent()) + .WillByDefault(::testing::Invoke( + [] { return std::make_unique(true); })); + + fml::CountDownLatch count_down_latch(2); + auto first_timestamp = fml::TimePoint::Now(); + auto second_timestamp = first_timestamp + fml::TimeDelta::FromMilliseconds(8); + std::vector timestamps = {first_timestamp, second_timestamp}; + int frame_rasterized_count = 0; + EXPECT_CALL(delegate, OnFrameRasterized(_)) + .Times(2) + .WillRepeatedly([&](const FrameTiming& frame_timing) { + EXPECT_EQ(timestamps[frame_rasterized_count], + frame_timing.Get(FrameTiming::kVsyncStart)); + EXPECT_EQ(timestamps[frame_rasterized_count], + frame_timing.Get(FrameTiming::kBuildStart)); + EXPECT_EQ(timestamps[frame_rasterized_count], + frame_timing.Get(FrameTiming::kBuildFinish)); + frame_rasterized_count++; + count_down_latch.CountDown(); + }); + + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + rasterizer->Setup(std::move(surface)); + auto pipeline = std::make_shared(/*depth=*/10); + for (int i = 0; i < 2; i++) { + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder(timestamps[i])); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + EXPECT_EQ(result.is_first_item, i == 0); + } + // Although we only call 'Rasterizer::Draw' once, it will be called twice + // finally because there are two items in the pipeline. + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + }); + count_down_latch.Wait(); + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + rasterizer.reset(); + latch.Signal(); + }); + latch.Wait(); +} + +TEST(RasterizerTest, TeardownFreesResourceCache) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + + auto rasterizer = std::make_unique(delegate); + auto surface = std::make_unique>(); + auto context = GrDirectContext::MakeMock(nullptr); + context->setResourceCacheLimit(0); + + EXPECT_CALL(*surface, MakeRenderContextCurrent()) + .WillRepeatedly([]() -> std::unique_ptr { + return std::make_unique(true); + }); + EXPECT_CALL(*surface, GetContext()).WillRepeatedly(Return(context.get())); + + rasterizer->Setup(std::move(surface)); + EXPECT_EQ(context->getResourceCacheLimit(), 0ul); + + rasterizer->SetResourceCacheMaxBytes(10000000, false); + EXPECT_EQ(context->getResourceCacheLimit(), 10000000ul); + EXPECT_EQ(context->getResourceCachePurgeableBytes(), 0ul); + + int count = 0; + size_t bytes = 0; + context->getResourceCacheUsage(&count, &bytes); + EXPECT_EQ(bytes, 0ul); + + auto image_info = + SkImageInfo::MakeN32Premul(500, 500, SkColorSpace::MakeSRGB()); + auto sk_surface = SkSurfaces::RenderTarget(context.get(), + skgpu::Budgeted::kYes, image_info); + EXPECT_TRUE(sk_surface); + + SkPaint paint; + sk_surface->getCanvas()->drawPaint(paint); + context->flushAndSubmit(GrSyncCpu::kYes); + + EXPECT_EQ(context->getResourceCachePurgeableBytes(), 0ul); + + sk_surface.reset(); + + context->getResourceCacheUsage(&count, &bytes); + EXPECT_GT(bytes, 0ul); + EXPECT_GT(context->getResourceCachePurgeableBytes(), 0ul); + + rasterizer->Teardown(); + EXPECT_EQ(context->getResourceCachePurgeableBytes(), 0ul); +} + +TEST(RasterizerTest, TeardownNoSurface) { + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + EXPECT_CALL(delegate, GetTaskRunners()) + .WillRepeatedly(ReturnRef(task_runners)); + + auto rasterizer = std::make_unique(delegate); + + EXPECT_TRUE(rasterizer); + rasterizer->Teardown(); +} + +TEST(RasterizerTest, presentationTimeSetWhenVsyncTargetInFuture) { + GTEST_SKIP() << "eglPresentationTime is disabled due to " + "https://github.com/flutter/flutter/issues/112503"; +#if false + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + ON_CALL(delegate, GetTaskRunners()).WillByDefault(ReturnRef(task_runners)); + + fml::AutoResetWaitableEvent latch; + std::unique_ptr rasterizer; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + rasterizer = std::make_unique(delegate); + latch.Signal(); + }); + latch.Wait(); + + const auto millis_16 = fml::TimeDelta::FromMilliseconds(16); + const auto first_timestamp = fml::TimePoint::Now() + millis_16; + auto second_timestamp = first_timestamp + millis_16; + std::vector timestamps = {first_timestamp, second_timestamp}; + + int frames_submitted = 0; + fml::CountDownLatch submit_latch(2); + auto surface = std::make_unique(); + ON_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillByDefault(Return(true)); + ON_CALL(*surface, AcquireFrame(SkISize())) + .WillByDefault(::testing::Invoke([&] { + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + return std::make_unique( + /*surface=*/nullptr, framebuffer_info, + /*submit_callback=*/ + [&](const SurfaceFrame& frame, DlCanvas*) { + const auto pres_time = *frame.submit_info().presentation_time; + const auto diff = pres_time - first_timestamp; + int num_frames_submitted = frames_submitted++; + EXPECT_EQ(diff.ToMilliseconds(), + num_frames_submitted * millis_16.ToMilliseconds()); + submit_latch.CountDown(); + return true; + }, + /*frame_size=*/SkISize::Make(800, 600)); + })); + + ON_CALL(*surface, MakeRenderContextCurrent()) + .WillByDefault(::testing::Invoke( + [] { return std::make_unique(true); })); + + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + rasterizer->Setup(std::move(surface)); + auto pipeline = std::make_shared(/*depth=*/10); + for (int i = 0; i < 2; i++) { + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder(timestamps[i])); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + EXPECT_EQ(result.is_first_item, i == 0); + } + // Although we only call 'Rasterizer::Draw' once, it will be called twice + // finally because there are two items in the pipeline. + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + }); + + submit_latch.Wait(); + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + rasterizer.reset(); + latch.Signal(); + }); + latch.Wait(); +#endif // false +} + +TEST(RasterizerTest, presentationTimeNotSetWhenVsyncTargetInPast) { + GTEST_SKIP() << "eglPresentationTime is disabled due to " + "https://github.com/flutter/flutter/issues/112503"; +#if false + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host("io.flutter.test." + test_name + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + + NiceMock delegate; + Settings settings; + ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); + ON_CALL(delegate, GetTaskRunners()).WillByDefault(ReturnRef(task_runners)); + + fml::AutoResetWaitableEvent latch; + std::unique_ptr rasterizer; + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + rasterizer = std::make_unique(delegate); + latch.Signal(); + }); + latch.Wait(); + + const auto millis_16 = fml::TimeDelta::FromMilliseconds(16); + const auto first_timestamp = fml::TimePoint::Now() - millis_16; + + fml::CountDownLatch submit_latch(1); + auto surface = std::make_unique(); + ON_CALL(*surface, AllowsDrawingWhenGpuDisabled()).WillByDefault(Return(true)); + ON_CALL(*surface, AcquireFrame(SkISize())) + .WillByDefault(::testing::Invoke([&] { + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + return std::make_unique( + /*surface=*/nullptr, framebuffer_info, + /*submit_callback=*/ + [&](const SurfaceFrame& frame, DlCanvas*) { + const std::optional pres_time = + frame.submit_info().presentation_time; + EXPECT_EQ(pres_time, std::nullopt); + submit_latch.CountDown(); + return true; + }, + /*frame_size=*/SkISize::Make(800, 600)); + })); + + ON_CALL(*surface, MakeRenderContextCurrent()) + .WillByDefault(::testing::Invoke( + [] { return std::make_unique(true); })); + + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + rasterizer->Setup(std::move(surface)); + auto pipeline = std::make_shared(/*depth=*/10); + auto layer_tree = std::make_unique( + /*root_layer=*/nullptr, /*frame_size=*/DlISize()); + auto layer_tree_item = std::make_unique( + SingleLayerTreeList(kImplicitViewId, std::move(layer_tree), + kDevicePixelRatio), + CreateFinishedBuildRecorder(first_timestamp)); + PipelineProduceResult result = + pipeline->Produce().Complete(std::move(layer_tree_item)); + EXPECT_TRUE(result.success); + EXPECT_EQ(result.is_first_item, true); + ON_CALL(delegate, ShouldDiscardLayerTree).WillByDefault(Return(false)); + rasterizer->Draw(pipeline); + }); + + submit_latch.Wait(); + thread_host.raster_thread->GetTaskRunner()->PostTask([&] { + rasterizer.reset(); + latch.Signal(); + }); + latch.Wait(); +#endif // false +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.cc b/flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.cc new file mode 100644 index 0000000000000000000000000000000000000000..8b13ee28bd5f45400a29512df86c333fd17a607e --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.cc @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/resource_cache_limit_calculator.h" + +namespace flutter { + +size_t ResourceCacheLimitCalculator::GetResourceCacheMaxBytes() { + size_t max_bytes = 0; + size_t max_bytes_threshold = max_bytes_threshold_ > 0 + ? max_bytes_threshold_ + : std::numeric_limits::max(); + std::vector> live_items; + for (const auto& item : items_) { + if (item) { + live_items.push_back(item); + max_bytes += item->GetResourceCacheLimit(); + } + } + items_ = std::move(live_items); + return std::min(max_bytes, max_bytes_threshold); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.h b/flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.h new file mode 100644 index 0000000000000000000000000000000000000000..27965475baa0a04a49a4b4c84a9366dc628b54ed --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.h @@ -0,0 +1,49 @@ +// 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_COMMON_RESOURCE_CACHE_LIMIT_CALCULATOR_H_ +#define FLUTTER_SHELL_COMMON_RESOURCE_CACHE_LIMIT_CALCULATOR_H_ + +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" + +namespace flutter { +class ResourceCacheLimitItem { + public: + // The expected GPU resource cache limit in bytes. This will be called on the + // platform thread. + virtual size_t GetResourceCacheLimit() = 0; + + protected: + virtual ~ResourceCacheLimitItem() = default; +}; + +class ResourceCacheLimitCalculator { + public: + explicit ResourceCacheLimitCalculator(size_t max_bytes_threshold) + : max_bytes_threshold_(max_bytes_threshold) {} + + ~ResourceCacheLimitCalculator() = default; + + // This will be called on the platform thread. + void AddResourceCacheLimitItem( + const fml::WeakPtr& item) { + items_.push_back(item); + } + + // The maximum GPU resource cache limit in bytes calculated by + // 'ResourceCacheLimitItem's. This will be called on the platform thread. + size_t GetResourceCacheMaxBytes(); + + private: + std::vector> items_; + size_t max_bytes_threshold_; + FML_DISALLOW_COPY_AND_ASSIGN(ResourceCacheLimitCalculator); +}; +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_RESOURCE_CACHE_LIMIT_CALCULATOR_H_ diff --git a/flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator_unittests.cc b/flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..dc928d4c508f6e2773ef1aee74c9e1603eb00d61 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator_unittests.cc @@ -0,0 +1,54 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/resource_cache_limit_calculator.h" + +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +class TestResourceCacheLimitItem : public ResourceCacheLimitItem { + public: + explicit TestResourceCacheLimitItem(size_t resource_cache_limit) + : resource_cache_limit_(resource_cache_limit), weak_factory_(this) {} + + size_t GetResourceCacheLimit() override { return resource_cache_limit_; } + + fml::WeakPtr GetWeakPtr() { + return weak_factory_.GetWeakPtr(); + } + + private: + size_t resource_cache_limit_; + fml::WeakPtrFactory weak_factory_; +}; + +TEST(ResourceCacheLimitCalculatorTest, GetResourceCacheMaxBytes) { + ResourceCacheLimitCalculator calculator(800U); + auto item1 = std::make_unique(100.0); + calculator.AddResourceCacheLimitItem(item1->GetWeakPtr()); + EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast(100U)); + + auto item2 = std::make_unique(200.0); + calculator.AddResourceCacheLimitItem(item2->GetWeakPtr()); + EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast(300U)); + + auto item3 = std::make_unique(300.0); + calculator.AddResourceCacheLimitItem(item3->GetWeakPtr()); + EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast(600U)); + + auto item4 = std::make_unique(400.0); + calculator.AddResourceCacheLimitItem(item4->GetWeakPtr()); + EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast(800U)); + + item3.reset(); + EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast(700U)); + + item2.reset(); + EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast(500U)); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/run_configuration.cc b/flutter/engine/src/flutter/shell/common/run_configuration.cc new file mode 100644 index 0000000000000000000000000000000000000000..6f22efbdc83fab6bbc4ddc1539dc6d8b2f6e4fcb --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/run_configuration.cc @@ -0,0 +1,122 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/run_configuration.h" + +#include +#include + +#include "flutter/assets/directory_asset_bundle.h" +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/fml/file.h" +#include "flutter/fml/unique_fd.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/runtime/isolate_configuration.h" + +namespace flutter { + +RunConfiguration RunConfiguration::InferFromSettings( + const Settings& settings, + const fml::RefPtr& io_worker, + IsolateLaunchType launch_type) { + auto asset_manager = std::make_shared(); + + if (fml::UniqueFD::traits_type::IsValid(settings.assets_dir)) { + asset_manager->PushBack(std::make_unique( + fml::Duplicate(settings.assets_dir), true)); + } + + asset_manager->PushBack(std::make_unique( + fml::OpenDirectory(settings.assets_path.c_str(), false, + fml::FilePermission::kRead), + true)); + + return {IsolateConfiguration::InferFromSettings(settings, asset_manager, + io_worker, launch_type), + asset_manager}; +} + +RunConfiguration::RunConfiguration( + std::unique_ptr configuration) + : RunConfiguration(std::move(configuration), + std::make_shared()) { +#if !SLIMPELLER + PersistentCache::SetAssetManager(asset_manager_); +#endif // !SLIMPELLER +} + +RunConfiguration::RunConfiguration( + std::unique_ptr configuration, + std::shared_ptr asset_manager) + : isolate_configuration_(std::move(configuration)), + asset_manager_(std::move(asset_manager)) { +#if !SLIMPELLER + PersistentCache::SetAssetManager(asset_manager_); +#endif // !SLIMPELLER +} + +RunConfiguration::RunConfiguration(RunConfiguration&&) = default; + +RunConfiguration::~RunConfiguration() = default; + +bool RunConfiguration::IsValid() const { + return asset_manager_ && isolate_configuration_; +} + +bool RunConfiguration::AddAssetResolver( + std::unique_ptr resolver) { + if (!resolver || !resolver->IsValid()) { + return false; + } + + asset_manager_->PushBack(std::move(resolver)); + return true; +} + +void RunConfiguration::SetEntrypoint(std::string entrypoint) { + entrypoint_ = std::move(entrypoint); +} + +void RunConfiguration::SetEntrypointAndLibrary(std::string entrypoint, + std::string library) { + SetEntrypoint(std::move(entrypoint)); + entrypoint_library_ = std::move(library); +} + +void RunConfiguration::SetEntrypointArgs( + std::vector entrypoint_args) { + entrypoint_args_ = std::move(entrypoint_args); +} + +std::shared_ptr RunConfiguration::GetAssetManager() const { + return asset_manager_; +} + +const std::string& RunConfiguration::GetEntrypoint() const { + return entrypoint_; +} + +const std::string& RunConfiguration::GetEntrypointLibrary() const { + return entrypoint_library_; +} + +const std::vector& RunConfiguration::GetEntrypointArgs() const { + return entrypoint_args_; +} + +void RunConfiguration::SetEngineId(int64_t engine_id) { + engine_id_ = engine_id; +} + +// Engine identifier to be passed to the platform dispatcher. +std::optional RunConfiguration::GetEngineId() const { + return engine_id_; +} + +std::unique_ptr +RunConfiguration::TakeIsolateConfiguration() { + return std::move(isolate_configuration_); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/run_configuration.h b/flutter/engine/src/flutter/shell/common/run_configuration.h new file mode 100644 index 0000000000000000000000000000000000000000..f2f3a2b406add96d81aa55dfb078d5d8eec3f84c --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/run_configuration.h @@ -0,0 +1,219 @@ +// 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_COMMON_RUN_CONFIGURATION_H_ +#define FLUTTER_SHELL_COMMON_RUN_CONFIGURATION_H_ + +#include +#include + +#include "flutter/assets/asset_manager.h" +#include "flutter/assets/asset_resolver.h" +#include "flutter/common/settings.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/unique_fd.h" +#include "flutter/runtime/isolate_configuration.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Specifies all the configuration required by the runtime library +/// to launch the root isolate. This object may be created on any +/// thread but must be given to the |Run| call of the |Engine| on +/// the UI thread. The configuration object is used to specify how +/// the root isolate finds its snapshots, assets, root library and +/// the "main" entrypoint. +/// +class RunConfiguration { + public: + //---------------------------------------------------------------------------- + /// @brief Attempts to infer a run configuration from the settings + /// object. This tries to create a run configuration with sensible + /// defaults for the given Dart VM runtime mode. In JIT mode, this + /// will attempt to look for the VM and isolate snapshots in the + /// assets directory (must be specified in settings). In AOT mode, + /// it will attempt to look for known snapshot symbols in the + /// currently loaded process. The entrypoint defaults to + /// the "main" method in the root library. + /// + /// @param[in] settings The settings object used to look for the various + /// snapshots and settings. This is usually initialized + /// from command line arguments. + /// @param[in] io_worker An optional IO worker. Resolving and reading the + /// various snapshots may be slow. Providing an IO + /// worker will ensure that realization of these + /// snapshots happens on a worker thread instead of the + /// calling thread. Note that the work done to realize + /// the snapshots may occur after this call returns. If + /// is the embedder's responsibility to make sure the + /// serial worker is kept alive for the lifetime of the + /// shell associated with the engine that this run + /// configuration is given to. + /// @param[in] launch_type Whether to launch the new isolate into an existing + /// group or a new one. + /// + /// @return A run configuration. Depending on the completeness of the + /// settings, This object may potentially be invalid. + /// + static RunConfiguration InferFromSettings( + const Settings& settings, + const fml::RefPtr& io_worker = nullptr, + IsolateLaunchType launch_type = IsolateLaunchType::kNewGroup); + + //---------------------------------------------------------------------------- + /// @brief Creates a run configuration with only an isolate + /// configuration. There is no asset manager and default + /// entrypoint and root library are used ("main" in root library). + /// + /// @param[in] configuration The configuration + /// + explicit RunConfiguration( + std::unique_ptr configuration); + + //---------------------------------------------------------------------------- + /// @brief Creates a run configuration with the specified isolate + /// configuration and asset manager. The default entrypoint and + /// root library are used ("main" in root library). + /// + /// @param[in] configuration The configuration + /// @param[in] asset_manager The asset manager + /// + RunConfiguration(std::unique_ptr configuration, + std::shared_ptr asset_manager); + + //---------------------------------------------------------------------------- + /// @brief Run configurations cannot be copied because it may not always + /// be possible to copy the underlying isolate snapshots. If + /// multiple run configurations share the same underlying + /// snapshots, creating a configuration from isolate snapshots + /// sharing the same underlying buffers is recommended. + /// + /// @param config The run configuration to move. + /// + RunConfiguration(RunConfiguration&& config); + + //---------------------------------------------------------------------------- + /// @brief There are no threading restrictions on the destruction of the + /// run configuration. + /// + ~RunConfiguration(); + + //---------------------------------------------------------------------------- + /// @brief A valid run configuration only guarantees that the engine + /// should be able to find the assets and the isolate snapshots + /// when it attempts to launch the root isolate. The validity of + /// the snapshot cannot be determined yet. That determination can + /// only be made when the configuration is used to run the root + /// isolate in the engine. However, the engine will always reject + /// an invalid run configuration. + /// + /// @attention A valid run configuration does not mean that the root isolate + /// will always be launched. It only indicates that the various + /// snapshots are isolate snapshots and asset managers are present + /// and accounted for. The validity of the snapshots will only be + /// checked when the engine attempts to launch the root isolate. + /// + /// @return Returns whether the snapshots and asset manager registrations + /// are valid. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Asset managers maintain a list of resolvers that are checked + /// in order when attempting to locate an asset. This method adds + /// a resolver to the end of the list. + /// + /// @param[in] resolver The asset resolver to add to the engine of the list + /// resolvers maintained by the asset manager. + /// + /// @return Returns whether the resolver was successfully registered. The + /// resolver must be valid for its registration to be successful. + /// + bool AddAssetResolver(std::unique_ptr resolver); + + //---------------------------------------------------------------------------- + /// @brief Updates the main application entrypoint. If this is not set, + /// the + /// "main" method is used as the entrypoint. + /// + /// @param[in] entrypoint The entrypoint to use. + void SetEntrypoint(std::string entrypoint); + + //---------------------------------------------------------------------------- + /// @brief Specifies the main Dart entrypoint and the library to find + /// that entrypoint in. By default, this is the "main" method in + /// the root library. The root library may be specified by + /// entering the empty string as the second argument. + /// + /// @see SetEntrypoint() + /// + /// @param[in] entrypoint The entrypoint + /// @param[in] library The library + /// + void SetEntrypointAndLibrary(std::string entrypoint, std::string library); + + //---------------------------------------------------------------------------- + /// @brief Updates the main application entrypoint arguments. + /// + /// @param[in] entrypoint_args The entrypoint arguments to use. + void SetEntrypointArgs(std::vector entrypoint_args); + + //---------------------------------------------------------------------------- + /// @return The asset manager referencing all previously registered asset + /// resolvers. + /// + std::shared_ptr GetAssetManager() const; + + //---------------------------------------------------------------------------- + /// @return The main Dart entrypoint to be used for the root isolate. + /// + const std::string& GetEntrypoint() const; + + //---------------------------------------------------------------------------- + /// @return The name of the library in which the main entrypoint resides. + /// If empty, the root library is used. + /// + const std::string& GetEntrypointLibrary() const; + + //---------------------------------------------------------------------------- + /// @return Arguments passed as a List to Dart's entrypoint + /// function. + /// + const std::vector& GetEntrypointArgs() const; + + //---------------------------------------------------------------------------- + /// @brief The engine uses this to take the isolate configuration from + /// the run configuration. The run configuration is no longer + /// valid after this call is made. The non-copyable nature of some + /// of the snapshots referenced in the isolate configuration is + /// why the run configuration as a whole is not copyable. + /// + /// @return The run configuration if one is present. + /// + std::unique_ptr TakeIsolateConfiguration(); + + //---------------------------------------------------------------------------- + /// @brief Sets the engine identifier to be passed to the platform + /// dispatcher. + void SetEngineId(int64_t engine_id); + + ///---------------------------------------------------------------------------- + /// @return Engine identifier to be passed to the platform dispatcher. + std::optional GetEngineId() const; + + private: + std::unique_ptr isolate_configuration_; + std::shared_ptr asset_manager_; + std::string entrypoint_ = "main"; + std::string entrypoint_library_ = ""; + std::vector entrypoint_args_; + std::optional engine_id_; + + FML_DISALLOW_COPY_AND_ASSIGN(RunConfiguration); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_RUN_CONFIGURATION_H_ diff --git a/flutter/engine/src/flutter/shell/common/serialization_callbacks.cc b/flutter/engine/src/flutter/shell/common/serialization_callbacks.cc new file mode 100644 index 0000000000000000000000000000000000000000..ce3e5356f00951efee02be2447a71a976b962d45 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/serialization_callbacks.cc @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/logging.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkImageInfo.h" +#include "third_party/skia/include/core/SkStream.h" +#include "third_party/skia/include/core/SkTypeface.h" + +namespace flutter { + +sk_sp SerializeTypefaceWithoutData(SkTypeface* typeface, void* ctx) { + return SkData::MakeEmpty(); +} + +sk_sp SerializeTypefaceWithData(SkTypeface* typeface, void* ctx) { + return typeface->serialize(SkTypeface::SerializeBehavior::kDoIncludeData); +} + +sk_sp DeserializeTypefaceWithoutData(const void* data, + size_t length, + void* ctx) { + return nullptr; +} + +struct ImageMetaData { + int32_t width; + int32_t height; + uint32_t color_type; + uint32_t alpha_type; + bool has_color_space; +} __attribute__((packed)); + +sk_sp SerializeImageWithoutData(SkImage* image, void* ctx) { + const auto& info = image->imageInfo(); + SkDynamicMemoryWStream stream; + + ImageMetaData metadata = {info.width(), info.height(), + static_cast(info.colorType()), + static_cast(info.alphaType()), + static_cast(info.colorSpace())}; + stream.write(&metadata, sizeof(ImageMetaData)); + + if (info.colorSpace()) { + auto color_space_data = info.colorSpace()->serialize(); + FML_CHECK(color_space_data); + SkMemoryStream color_space_stream(color_space_data); + stream.writeStream(&color_space_stream, color_space_data->size()); + } + + return stream.detachAsData(); +}; + +sk_sp DeserializeImageWithoutData(const void* data, + size_t length, + void* ctx) { + FML_CHECK(length >= sizeof(ImageMetaData)); + auto metadata = static_cast(data); + sk_sp color_space = nullptr; + if (metadata->has_color_space) { + color_space = SkColorSpace::Deserialize( + static_cast(data) + sizeof(ImageMetaData), + length - sizeof(ImageMetaData)); + } + + auto image_size = SkISize::Make(metadata->width, metadata->height); + auto info = SkImageInfo::Make( + image_size, static_cast(metadata->color_type), + static_cast(metadata->alpha_type), color_space); + sk_sp image_data = + SkData::MakeUninitialized(image_size.width() * image_size.height() * 4); + memset(image_data->writable_data(), 0x0f, image_data->size()); + sk_sp image = + SkImages::RasterFromData(info, image_data, image_size.width() * 4); + + return image; +}; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/serialization_callbacks.h b/flutter/engine/src/flutter/shell/common/serialization_callbacks.h new file mode 100644 index 0000000000000000000000000000000000000000..66d7a549d82c3957bf54611ac25646e5a662613e --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/serialization_callbacks.h @@ -0,0 +1,28 @@ +// 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_COMMON_SERIALIZATION_CALLBACKS_H_ +#define FLUTTER_SHELL_COMMON_SERIALIZATION_CALLBACKS_H_ + +#include "flutter/fml/logging.h" +#include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkTypeface.h" + +namespace flutter { + +sk_sp SerializeTypefaceWithoutData(SkTypeface* typeface, void* ctx); +sk_sp SerializeTypefaceWithData(SkTypeface* typeface, void* ctx); +sk_sp DeserializeTypefaceWithoutData(const void* data, + size_t length, + void* ctx); + +// Serializes only the metadata of the image and not the underlying pixel data. +sk_sp SerializeImageWithoutData(SkImage* image, void* ctx); +sk_sp DeserializeImageWithoutData(const void* data, + size_t length, + void* ctx); + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SERIALIZATION_CALLBACKS_H_ diff --git a/flutter/engine/src/flutter/shell/common/shell.cc b/flutter/engine/src/flutter/shell/common/shell.cc new file mode 100644 index 0000000000000000000000000000000000000000..f70991ca00612f9a23bfab1c26d8c0b56989b144 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell.cc @@ -0,0 +1,2297 @@ +// 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 "fml/task_runner.h" +#define RAPIDJSON_HAS_STDSTRING 1 +#include "flutter/shell/common/shell.h" + +#include +#include +#include +#include + +#include "flutter/assets/directory_asset_bundle.h" +#include "flutter/common/constants.h" +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/fml/base32.h" +#include "flutter/fml/file.h" +#include "flutter/fml/icu_util.h" +#include "flutter/fml/log_settings.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/paths.h" +#include "flutter/fml/trace_event.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/common/base64.h" +#include "flutter/shell/common/engine.h" +#include "flutter/shell/common/skia_event_tracer_impl.h" +#include "flutter/shell/common/switches.h" +#include "flutter/shell/common/vsync_waiter.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/writer.h" +#include "third_party/dart/runtime/include/dart_tools_api.h" +#include "third_party/skia/include/codec/SkBmpDecoder.h" +#include "third_party/skia/include/codec/SkCodec.h" +#include "third_party/skia/include/codec/SkGifDecoder.h" +#include "third_party/skia/include/codec/SkIcoDecoder.h" +#include "third_party/skia/include/codec/SkJpegDecoder.h" +#include "third_party/skia/include/codec/SkPngDecoder.h" +#include "third_party/skia/include/codec/SkWbmpDecoder.h" +#include "third_party/skia/include/codec/SkWebpDecoder.h" +#include "third_party/skia/include/core/SkGraphics.h" +#include "third_party/tonic/common/log.h" + +namespace flutter { + +constexpr char kSkiaChannel[] = "flutter/skia"; +constexpr char kSystemChannel[] = "flutter/system"; +constexpr char kTypeKey[] = "type"; +constexpr char kFontChange[] = "fontsChange"; + +namespace { + +std::unique_ptr CreateEngine( + Engine::Delegate& delegate, + const PointerDataDispatcherMaker& dispatcher_maker, + DartVM& vm, + const fml::RefPtr& isolate_snapshot, + const TaskRunners& task_runners, + const PlatformData& platform_data, + const Settings& settings, + std::unique_ptr animator, + const fml::WeakPtr& io_manager, + const fml::RefPtr& unref_queue, + const fml::TaskRunnerAffineWeakPtr& snapshot_delegate, + const std::shared_ptr& gpu_disabled_switch, + impeller::RuntimeStageBackend runtime_stage_backend) { + return std::make_unique(delegate, // + dispatcher_maker, // + vm, // + isolate_snapshot, // + task_runners, // + platform_data, // + settings, // + std::move(animator), // + io_manager, // + unref_queue, // + snapshot_delegate, // + gpu_disabled_switch, // + runtime_stage_backend); +} + +void RegisterCodecsWithSkia() { + // These are in the order they will be attempted to be decoded from. + // If we have data to back it up, we can order these by "frequency used in + // the wild" for a very small performance bump, but for now we mirror the + // order Skia had them in. + SkCodecs::Register(SkPngDecoder::Decoder()); + SkCodecs::Register(SkJpegDecoder::Decoder()); + SkCodecs::Register(SkWebpDecoder::Decoder()); + SkCodecs::Register(SkGifDecoder::Decoder()); + SkCodecs::Register(SkBmpDecoder::Decoder()); + SkCodecs::Register(SkWbmpDecoder::Decoder()); + SkCodecs::Register(SkIcoDecoder::Decoder()); +} + +// Though there can be multiple shells, some settings apply to all components in +// the process. These have to be set up before the shell or any of its +// sub-components can be initialized. In a perfect world, this would be empty. +// TODO(chinmaygarde): The unfortunate side effect of this call is that settings +// that cause shell initialization failures will still lead to some of their +// settings being applied. +void PerformInitializationTasks(Settings& settings) { + { + fml::LogSettings log_settings; + log_settings.min_log_level = + settings.verbose_logging ? fml::kLogInfo : fml::kLogError; + fml::SetLogSettings(log_settings); + } + + static std::once_flag gShellSettingsInitialization = {}; + std::call_once(gShellSettingsInitialization, [&settings] { + tonic::SetLogHandler( + [](const char* message) { FML_LOG(ERROR) << message; }); + + if (settings.trace_skia) { + InitSkiaEventTracer(settings.trace_skia, settings.trace_skia_allowlist); + } + + if (!settings.trace_allowlist.empty()) { + fml::tracing::TraceSetAllowlist(settings.trace_allowlist); + } + + if (!settings.skia_deterministic_rendering_on_cpu) { + SkGraphics::Init(); + } else { + FML_DLOG(INFO) << "Skia deterministic rendering is enabled."; + } + RegisterCodecsWithSkia(); + + if (settings.icu_initialization_required) { + if (!settings.icu_data_path.empty()) { + fml::icu::InitializeICU(settings.icu_data_path); + } else if (settings.icu_mapper) { + fml::icu::InitializeICUFromMapping(settings.icu_mapper()); + } else { + FML_DLOG(WARNING) << "Skipping ICU initialization in the shell."; + } + } + }); + +#if !SLIMPELLER + PersistentCache::SetCacheSkSL(settings.cache_sksl); +#endif // !SLIMPELLER +} + +} // namespace + +std::pair> +Shell::InferVmInitDataFromSettings(Settings& settings) { + // Always use the `vm_snapshot` and `isolate_snapshot` provided by the + // settings to launch the VM. If the VM is already running, the snapshot + // arguments are ignored. + auto vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings); + auto isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings); + auto vm = DartVMRef::Create(settings, vm_snapshot, isolate_snapshot); + + // If the settings did not specify an `isolate_snapshot`, fall back to the + // one the VM was launched with. + if (!isolate_snapshot) { + isolate_snapshot = vm->GetVMData()->GetIsolateSnapshot(); + } + return {std::move(vm), isolate_snapshot}; +} + +std::unique_ptr Shell::Create( + const PlatformData& platform_data, + const TaskRunners& task_runners, + Settings settings, + const Shell::CreateCallback& on_create_platform_view, + const Shell::CreateCallback& on_create_rasterizer, + bool is_gpu_disabled) { + // This must come first as it initializes tracing. + PerformInitializationTasks(settings); + + TRACE_EVENT0("flutter", "Shell::Create"); + + auto [vm, isolate_snapshot] = InferVmInitDataFromSettings(settings); + auto resource_cache_limit_calculator = + std::make_shared( + settings.resource_cache_max_bytes_threshold); + + return CreateWithSnapshot(platform_data, // + task_runners, // + /*parent_thread_merger=*/nullptr, // + /*parent_io_manager=*/nullptr, // + resource_cache_limit_calculator, // + settings, // + std::move(vm), // + std::move(isolate_snapshot), // + on_create_platform_view, // + on_create_rasterizer, // + CreateEngine, is_gpu_disabled); +} + +static impeller::RuntimeStageBackend DetermineRuntimeStageBackend( + const std::shared_ptr& impeller_context) { + if (!impeller_context) { + return impeller::RuntimeStageBackend::kSkSL; + } + return impeller_context->GetRuntimeStageBackend(); +} + +std::unique_ptr Shell::CreateShellOnPlatformThread( + DartVMRef vm, + fml::RefPtr parent_merger, + std::shared_ptr parent_io_manager, + const std::shared_ptr& + resource_cache_limit_calculator, + const TaskRunners& task_runners, + const PlatformData& platform_data, + const Settings& settings, + fml::RefPtr isolate_snapshot, + const Shell::CreateCallback& on_create_platform_view, + const Shell::CreateCallback& on_create_rasterizer, + const Shell::EngineCreateCallback& on_create_engine, + bool is_gpu_disabled) { + if (!task_runners.IsValid()) { + FML_LOG(ERROR) << "Task runners to run the shell were invalid."; + return nullptr; + } + + auto shell = std::unique_ptr( + new Shell(std::move(vm), task_runners, std::move(parent_merger), + resource_cache_limit_calculator, settings, is_gpu_disabled)); + + // Create the platform view on the platform thread (this thread). + auto platform_view = on_create_platform_view(*shell.get()); + if (!platform_view || !platform_view->GetWeakPtr()) { + return nullptr; + } + + // Create the rasterizer on the raster thread. + std::promise> rasterizer_promise; + auto rasterizer_future = rasterizer_promise.get_future(); + std::promise> + snapshot_delegate_promise; + auto snapshot_delegate_future = snapshot_delegate_promise.get_future(); + fml::TaskRunner::RunNowOrPostTask( + task_runners.GetRasterTaskRunner(), + [&rasterizer_promise, // + &snapshot_delegate_promise, + on_create_rasterizer, // + shell = shell.get(), // + impeller_context = platform_view->GetImpellerContext() // + ]() { + TRACE_EVENT0("flutter", "ShellSetupGPUSubsystem"); + std::unique_ptr rasterizer(on_create_rasterizer(*shell)); + rasterizer->SetImpellerContext(impeller_context); + snapshot_delegate_promise.set_value(rasterizer->GetSnapshotDelegate()); + rasterizer_promise.set_value(std::move(rasterizer)); + }); + + // Ask the platform view for the vsync waiter. This will be used by the engine + // to create the animator. + auto vsync_waiter = platform_view->CreateVSyncWaiter(); + if (!vsync_waiter) { + return nullptr; + } + + // Create the IO manager on the IO thread. The IO manager must be initialized + // first because it has state that the other subsystems depend on. It must + // first be booted and the necessary references obtained to initialize the + // other subsystems. + std::promise> io_manager_promise; + auto io_manager_future = io_manager_promise.get_future(); + std::promise> weak_io_manager_promise; + auto weak_io_manager_future = weak_io_manager_promise.get_future(); + std::promise> unref_queue_promise; + auto unref_queue_future = unref_queue_promise.get_future(); + auto io_task_runner = shell->GetTaskRunners().GetIOTaskRunner(); + + // The platform_view will be stored into shell's platform_view_ in + // shell->Setup(std::move(platform_view), ...) at the end. + PlatformView* platform_view_ptr = platform_view.get(); + fml::TaskRunner::RunNowOrPostTask( + io_task_runner, + [&io_manager_promise, // + &weak_io_manager_promise, // + &parent_io_manager, // + &unref_queue_promise, // + platform_view_ptr, // + io_task_runner, // + is_backgrounded_sync_switch = shell->GetIsGpuDisabledSyncSwitch() // + ]() { + TRACE_EVENT0("flutter", "ShellSetupIOSubsystem"); + std::shared_ptr io_manager; + if (parent_io_manager) { + io_manager = parent_io_manager; + } else { + io_manager = std::make_shared( + platform_view_ptr->CreateResourceContext(), // resource context + is_backgrounded_sync_switch, // sync switch + io_task_runner, // unref queue task runner + platform_view_ptr->GetImpellerContext() // impeller context + ); + } + weak_io_manager_promise.set_value(io_manager->GetWeakPtr()); + unref_queue_promise.set_value(io_manager->GetSkiaUnrefQueue()); + io_manager_promise.set_value(io_manager); + }); + + // Send dispatcher_maker to the engine constructor because shell won't have + // platform_view set until Shell::Setup is called later. + auto dispatcher_maker = platform_view->GetDispatcherMaker(); + + // Create the engine on the UI thread. + std::promise> engine_promise; + auto engine_future = engine_promise.get_future(); + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetUITaskRunner(), + fml::MakeCopyable([&engine_promise, // + shell = shell.get(), // + &dispatcher_maker, // + &platform_data, // + isolate_snapshot = std::move(isolate_snapshot), // + vsync_waiter = std::move(vsync_waiter), // + &weak_io_manager_future, // + &snapshot_delegate_future, // + &unref_queue_future, // + &on_create_engine, + runtime_stage_backend = DetermineRuntimeStageBackend( + platform_view->GetImpellerContext())]() mutable { + TRACE_EVENT0("flutter", "ShellSetupUISubsystem"); + const auto& task_runners = shell->GetTaskRunners(); + + // The animator is owned by the UI thread but it gets its vsync pulses + // from the platform. + auto animator = std::make_unique(*shell, task_runners, + std::move(vsync_waiter)); + + engine_promise.set_value(on_create_engine( + *shell, // + dispatcher_maker, // + *shell->GetDartVM(), // + std::move(isolate_snapshot), // + task_runners, // + platform_data, // + shell->GetSettings(), // + std::move(animator), // + weak_io_manager_future.get(), // + unref_queue_future.get(), // + snapshot_delegate_future.get(), // + shell->is_gpu_disabled_sync_switch_, // + runtime_stage_backend // + )); + })); + + if (!shell->Setup(std::move(platform_view), // + engine_future.get(), // + rasterizer_future.get(), // + io_manager_future.get()) // + ) { + return nullptr; + } + + return shell; +} + +std::unique_ptr Shell::CreateWithSnapshot( + const PlatformData& platform_data, + const TaskRunners& task_runners, + const fml::RefPtr& parent_thread_merger, + const std::shared_ptr& parent_io_manager, + const std::shared_ptr& + resource_cache_limit_calculator, + Settings settings, + DartVMRef vm, + fml::RefPtr isolate_snapshot, + const Shell::CreateCallback& on_create_platform_view, + const Shell::CreateCallback& on_create_rasterizer, + const Shell::EngineCreateCallback& on_create_engine, + bool is_gpu_disabled) { + // This must come first as it initializes tracing. + PerformInitializationTasks(settings); + + TRACE_EVENT0("flutter", "Shell::CreateWithSnapshot"); + + const bool callbacks_valid = + on_create_platform_view && on_create_rasterizer && on_create_engine; + if (!task_runners.IsValid() || !callbacks_valid) { + return nullptr; + } + + fml::AutoResetWaitableEvent latch; + std::unique_ptr shell; + auto platform_task_runner = task_runners.GetPlatformTaskRunner(); + fml::TaskRunner::RunNowOrPostTask( + platform_task_runner, + fml::MakeCopyable([&latch, // + &shell, // + parent_thread_merger, // + parent_io_manager, // + resource_cache_limit_calculator, // + task_runners = task_runners, // + platform_data = platform_data, // + settings = settings, // + vm = std::move(vm), // + isolate_snapshot = std::move(isolate_snapshot), // + on_create_platform_view = on_create_platform_view, // + on_create_rasterizer = on_create_rasterizer, // + on_create_engine = on_create_engine, + is_gpu_disabled]() mutable { + shell = CreateShellOnPlatformThread(std::move(vm), // + parent_thread_merger, // + parent_io_manager, // + resource_cache_limit_calculator, // + task_runners, // + platform_data, // + settings, // + std::move(isolate_snapshot), // + on_create_platform_view, // + on_create_rasterizer, // + on_create_engine, is_gpu_disabled); + latch.Signal(); + })); + latch.Wait(); + return shell; +} + +Shell::Shell(DartVMRef vm, + const TaskRunners& task_runners, + fml::RefPtr parent_merger, + const std::shared_ptr& + resource_cache_limit_calculator, + const Settings& settings, + bool is_gpu_disabled) + : task_runners_(task_runners), + parent_raster_thread_merger_(std::move(parent_merger)), + resource_cache_limit_calculator_(resource_cache_limit_calculator), + settings_(settings), + vm_(std::move(vm)), + is_gpu_disabled_sync_switch_(new fml::SyncSwitch(is_gpu_disabled)), + weak_factory_gpu_(nullptr), + weak_factory_(this) { + FML_CHECK(!settings.enable_software_rendering || !settings.enable_impeller) + << "Software rendering is incompatible with Impeller."; + if (!settings.enable_impeller && settings.warn_on_impeller_opt_out) { + FML_LOG(IMPORTANT) + << "[Action Required] The application opted out of Impeller by either " + "using the --no-enable-impeller flag or FLTEnableImpeller=false " + "plist flag. This option is going to go away in an upcoming Flutter " + "release. Remove the explicit opt-out. If you need to opt-out, " + "report a bug describing the issue."; + } + FML_CHECK(vm_) << "Must have access to VM to create a shell."; + FML_DCHECK(task_runners_.IsValid()); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + display_manager_ = std::make_unique(); + resource_cache_limit_calculator->AddResourceCacheLimitItem( + weak_factory_.GetWeakPtr()); + + // Generate a WeakPtrFactory for use with the raster thread. This does not + // need to wait on a latch because it can only ever be used from the raster + // thread from this class, so we have ordering guarantees. + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetRasterTaskRunner(), fml::MakeCopyable([this]() mutable { + this->weak_factory_gpu_ = + std::make_unique>(this); + })); + + // Install service protocol handlers. + + service_protocol_handlers_[ServiceProtocol::kScreenshotExtensionName] = { + task_runners_.GetRasterTaskRunner(), + std::bind(&Shell::OnServiceProtocolScreenshot, this, + std::placeholders::_1, std::placeholders::_2)}; + service_protocol_handlers_[ServiceProtocol::kScreenshotSkpExtensionName] = { + task_runners_.GetRasterTaskRunner(), + std::bind(&Shell::OnServiceProtocolScreenshotSKP, this, + std::placeholders::_1, std::placeholders::_2)}; + service_protocol_handlers_[ServiceProtocol::kRunInViewExtensionName] = { + task_runners_.GetUITaskRunner(), + std::bind(&Shell::OnServiceProtocolRunInView, this, std::placeholders::_1, + std::placeholders::_2)}; + service_protocol_handlers_ + [ServiceProtocol::kFlushUIThreadTasksExtensionName] = { + task_runners_.GetUITaskRunner(), + std::bind(&Shell::OnServiceProtocolFlushUIThreadTasks, this, + std::placeholders::_1, std::placeholders::_2)}; + service_protocol_handlers_ + [ServiceProtocol::kSetAssetBundlePathExtensionName] = { + task_runners_.GetUITaskRunner(), + std::bind(&Shell::OnServiceProtocolSetAssetBundlePath, this, + std::placeholders::_1, std::placeholders::_2)}; + service_protocol_handlers_ + [ServiceProtocol::kGetDisplayRefreshRateExtensionName] = { + task_runners_.GetUITaskRunner(), + std::bind(&Shell::OnServiceProtocolGetDisplayRefreshRate, this, + std::placeholders::_1, std::placeholders::_2)}; + service_protocol_handlers_[ServiceProtocol::kGetSkSLsExtensionName] = { + task_runners_.GetIOTaskRunner(), + std::bind(&Shell::OnServiceProtocolGetSkSLs, this, std::placeholders::_1, + std::placeholders::_2)}; + service_protocol_handlers_ + [ServiceProtocol::kEstimateRasterCacheMemoryExtensionName] = { + task_runners_.GetRasterTaskRunner(), + std::bind(&Shell::OnServiceProtocolEstimateRasterCacheMemory, this, + std::placeholders::_1, std::placeholders::_2)}; + service_protocol_handlers_[ServiceProtocol::kReloadAssetFonts] = { + task_runners_.GetPlatformTaskRunner(), + std::bind(&Shell::OnServiceProtocolReloadAssetFonts, this, + std::placeholders::_1, std::placeholders::_2)}; +} + +Shell::~Shell() { +#if !SLIMPELLER + PersistentCache::GetCacheForProcess()->RemoveWorkerTaskRunner( + task_runners_.GetIOTaskRunner()); +#endif // !SLIMPELLER + + vm_->GetServiceProtocol()->RemoveHandler(this); + + fml::AutoResetWaitableEvent platiso_latch, ui_latch, gpu_latch, + platform_latch, io_latch; + + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetPlatformTaskRunner(), + fml::MakeCopyable([this, &platiso_latch]() mutable { + engine_->ShutdownPlatformIsolates(); + platiso_latch.Signal(); + })); + platiso_latch.Wait(); + + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetUITaskRunner(), + fml::MakeCopyable([this, &ui_latch]() mutable { + engine_.reset(); + ui_latch.Signal(); + })); + ui_latch.Wait(); + + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetRasterTaskRunner(), + fml::MakeCopyable( + [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable { + rasterizer.reset(); + this->weak_factory_gpu_.reset(); + gpu_latch.Signal(); + })); + gpu_latch.Wait(); + + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetIOTaskRunner(), + fml::MakeCopyable([io_manager = std::move(io_manager_), + platform_view = platform_view_.get(), + &io_latch]() mutable { + io_manager.reset(); + if (platform_view) { + platform_view->ReleaseResourceContext(); + } + io_latch.Signal(); + })); + + io_latch.Wait(); + + // The platform view must go last because it may be holding onto platform side + // counterparts to resources owned by subsystems running on other threads. For + // example, the NSOpenGLContext on the Mac. + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetPlatformTaskRunner(), + fml::MakeCopyable([platform_view = std::move(platform_view_), + &platform_latch]() mutable { + platform_view.reset(); + platform_latch.Signal(); + })); + platform_latch.Wait(); +} + +std::unique_ptr Shell::Spawn( + RunConfiguration run_configuration, + const std::string& initial_route, + const CreateCallback& on_create_platform_view, + const CreateCallback& on_create_rasterizer) const { + FML_DCHECK(task_runners_.IsValid()); + // It's safe to store this value since it is set on the platform thread. + bool is_gpu_disabled = false; + GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers() + .SetIfFalse([&is_gpu_disabled] { is_gpu_disabled = false; }) + .SetIfTrue([&is_gpu_disabled] { is_gpu_disabled = true; })); + std::unique_ptr result = CreateWithSnapshot( + PlatformData{}, task_runners_, rasterizer_->GetRasterThreadMerger(), + io_manager_, resource_cache_limit_calculator_, GetSettings(), vm_, + vm_->GetVMData()->GetIsolateSnapshot(), on_create_platform_view, + on_create_rasterizer, + [engine = this->engine_.get(), initial_route]( + Engine::Delegate& delegate, + const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm, + const fml::RefPtr& isolate_snapshot, + const TaskRunners& task_runners, const PlatformData& platform_data, + const Settings& settings, std::unique_ptr animator, + const fml::WeakPtr& io_manager, + const fml::RefPtr& unref_queue, + fml::TaskRunnerAffineWeakPtr snapshot_delegate, + const std::shared_ptr& is_gpu_disabled_sync_switch, + impeller::RuntimeStageBackend runtime_stage_backend) { + return engine->Spawn( + /*delegate=*/delegate, + /*dispatcher_maker=*/dispatcher_maker, + /*settings=*/settings, + /*animator=*/std::move(animator), + /*initial_route=*/initial_route, + /*io_manager=*/io_manager, + /*snapshot_delegate=*/std::move(snapshot_delegate), + /*gpu_disabled_switch=*/is_gpu_disabled_sync_switch); + }, + is_gpu_disabled); + result->RunEngine(std::move(run_configuration)); + return result; +} + +void Shell::NotifyLowMemoryWarning() const { + auto trace_id = fml::tracing::TraceNonce(); + TRACE_EVENT_ASYNC_BEGIN0("flutter", "Shell::NotifyLowMemoryWarning", + trace_id); + // This does not require a current isolate but does require a running VM. + // Since a valid shell will not be returned to the embedder without a valid + // DartVMRef, we can be certain that this is a safe spot to assume a VM is + // running. + ::Dart_NotifyLowMemory(); + + task_runners_.GetRasterTaskRunner()->PostTask( + [rasterizer = rasterizer_->GetWeakPtr(), trace_id = trace_id]() { + if (rasterizer) { + rasterizer->NotifyLowMemoryWarning(); + } + TRACE_EVENT_ASYNC_END0("flutter", "Shell::NotifyLowMemoryWarning", + trace_id); + }); + // The IO Manager uses resource cache limits of 0, so it is not necessary + // to purge them. +} + +void Shell::FlushMicrotaskQueue() const { + if (engine_) { + engine_->FlushMicrotaskQueue(); + } +} + +void Shell::RunEngine(RunConfiguration run_configuration) { + RunEngine(std::move(run_configuration), nullptr); +} + +void Shell::RunEngine( + RunConfiguration run_configuration, + const std::function& result_callback) { + auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(), + result_callback](Engine::RunStatus run_result) { + if (!result_callback) { + return; + } + platform_runner->PostTask( + [result_callback, run_result]() { result_callback(run_result); }); + }; + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetUITaskRunner(), + fml::MakeCopyable( + [run_configuration = std::move(run_configuration), + weak_engine = weak_engine_, result]() mutable { + if (!weak_engine) { + FML_LOG(ERROR) + << "Could not launch engine with configuration - no engine."; + result(Engine::RunStatus::Failure); + return; + } + auto run_result = weak_engine->Run(std::move(run_configuration)); + if (run_result == flutter::Engine::RunStatus::Failure) { + FML_LOG(ERROR) << "Could not launch engine with configuration."; + } + + result(run_result); + })); +} + +std::optional Shell::GetUIIsolateLastError() const { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + if (!weak_engine_) { + return std::nullopt; + } + switch (weak_engine_->GetUIIsolateLastError()) { + case tonic::kCompilationErrorType: + return DartErrorCode::CompilationError; + case tonic::kApiErrorType: + return DartErrorCode::ApiError; + case tonic::kUnknownErrorType: + return DartErrorCode::UnknownError; + case tonic::kNoError: + return DartErrorCode::NoError; + } + return DartErrorCode::UnknownError; +} + +bool Shell::EngineHasLivePorts() const { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + if (!weak_engine_) { + return false; + } + + return weak_engine_->UIIsolateHasLivePorts(); +} + +bool Shell::EngineHasPendingMicrotasks() const { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + if (!weak_engine_) { + return false; + } + + return weak_engine_->UIIsolateHasPendingMicrotasks(); +} + +bool Shell::IsSetup() const { + return is_set_up_; +} + +bool Shell::Setup(std::unique_ptr platform_view, + std::unique_ptr engine, + std::unique_ptr rasterizer, + const std::shared_ptr& io_manager) { + if (is_set_up_) { + return false; + } + + if (!platform_view || !engine || !rasterizer || !io_manager) { + return false; + } + + platform_view_ = std::move(platform_view); + platform_message_handler_ = platform_view_->GetPlatformMessageHandler(); + route_messages_through_platform_thread_.store(true); + task_runners_.GetPlatformTaskRunner()->PostTask( + [self = weak_factory_.GetWeakPtr()] { + if (self) { + self->route_messages_through_platform_thread_.store(false); + } + }); + engine_ = std::move(engine); + rasterizer_ = std::move(rasterizer); + io_manager_ = io_manager; + + // Set the external view embedder for the rasterizer. + auto view_embedder = platform_view_->CreateExternalViewEmbedder(); + rasterizer_->SetExternalViewEmbedder(view_embedder); + rasterizer_->SetSnapshotSurfaceProducer( + platform_view_->CreateSnapshotSurfaceProducer()); + + // The weak ptr must be generated in the platform thread which owns the unique + // ptr. + weak_engine_ = engine_->GetWeakPtr(); + weak_rasterizer_ = rasterizer_->GetWeakPtr(); + weak_platform_view_ = platform_view_->GetWeakPtr(); + + // Add the implicit view with empty metrics. + engine_->AddView(kFlutterImplicitViewId, ViewportMetrics{}, [](bool added) { + FML_DCHECK(added) << "Failed to add the implicit view"; + }); + + // Setup the time-consuming default font manager right after engine created. + if (!settings_.prefetched_default_font_manager) { + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetUITaskRunner(), + [engine = weak_engine_] { + if (engine) { + engine->SetupDefaultFontManager(); + } + }); + } + + is_set_up_ = true; + +#if !SLIMPELLER + PersistentCache::GetCacheForProcess()->AddWorkerTaskRunner( + task_runners_.GetIOTaskRunner()); + + PersistentCache::GetCacheForProcess()->SetIsDumpingSkp( + settings_.dump_skp_on_shader_compilation); + + if (settings_.purge_persistent_cache) { + PersistentCache::GetCacheForProcess()->Purge(); + } +#endif // !SLIMPELLER + + return true; +} + +const Settings& Shell::GetSettings() const { + return settings_; +} + +const TaskRunners& Shell::GetTaskRunners() const { + return task_runners_; +} + +const fml::RefPtr Shell::GetParentRasterThreadMerger() + const { + return parent_raster_thread_merger_; +} + +fml::TaskRunnerAffineWeakPtr Shell::GetRasterizer() const { + FML_DCHECK(is_set_up_); + return weak_rasterizer_; +} + +fml::WeakPtr Shell::GetEngine() { + FML_DCHECK(is_set_up_); + return weak_engine_; +} + +fml::WeakPtr Shell::GetPlatformView() { + FML_DCHECK(is_set_up_); + return weak_platform_view_; +} + +fml::WeakPtr Shell::GetIOManager() { + FML_DCHECK(is_set_up_); + return io_manager_->GetWeakPtr(); +} + +DartVM* Shell::GetDartVM() { + return &vm_; +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewCreated(std::unique_ptr surface) { + TRACE_EVENT0("flutter", "Shell::OnPlatformViewCreated"); + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + // Prevent any request to change the thread configuration for raster and + // platform queues while the platform view is being created. + // + // This prevents false positives such as this method starts assuming that the + // raster and platform queues have a given thread configuration, but then the + // configuration is changed by a task, and the assumption is no longer true. + // + // This incorrect assumption can lead to deadlock. + // See `should_post_raster_task` for more. + rasterizer_->DisableThreadMergerIfNeeded(); + + // The normal flow executed by this method is that the platform thread is + // starting the sequence and waiting on the latch. Later the UI thread posts + // raster_task to the raster thread which signals the latch. If the raster and + // the platform threads are the same this results in a deadlock as the + // raster_task will never be posted to the platform/raster thread that is + // blocked on a latch. To avoid the described deadlock, if the raster and the + // platform threads are the same, should_post_raster_task will be false, and + // then instead of posting a task to the raster thread, the ui thread just + // signals the latch and the platform/raster thread follows with executing + // raster_task. + const bool should_post_raster_task = + !task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread(); + + auto raster_task = fml::MakeCopyable( + [&waiting_for_first_frame = waiting_for_first_frame_, // + rasterizer = rasterizer_->GetWeakPtr(), // + surface = std::move(surface) // + ]() mutable { + if (rasterizer) { + // Enables the thread merger which may be used by the external view + // embedder. + rasterizer->EnableThreadMergerIfNeeded(); + rasterizer->Setup(std::move(surface)); + } + + waiting_for_first_frame.store(true); + }); + + auto ui_task = [engine = engine_->GetWeakPtr()] { + if (engine) { + engine->ScheduleFrame(); + } + }; + + // Threading: Capture platform view by raw pointer and not the weak pointer. + // We are going to use the pointer on the IO thread which is not safe with a + // weak pointer. However, we are preventing the platform view from being + // collected by using a latch. + auto* platform_view = platform_view_.get(); + FML_DCHECK(platform_view); + fml::AutoResetWaitableEvent latch; + + auto io_task = [io_manager = io_manager_->GetWeakPtr(), platform_view, + ui_task_runner = task_runners_.GetUITaskRunner(), ui_task, + raster_task_runner = task_runners_.GetRasterTaskRunner(), + raster_task, should_post_raster_task, &latch] { + if (io_manager && !io_manager->GetResourceContext()) { + sk_sp resource_context = + platform_view->CreateResourceContext(); + io_manager->NotifyResourceContextAvailable(resource_context); + } + // Step 1: Post a task on the UI thread to tell the engine that it has + // an output surface. + fml::TaskRunner::RunNowOrPostTask(ui_task_runner, ui_task); + + // Step 2: Tell the raster thread that it should create a surface for + // its rasterizer. + if (should_post_raster_task) { + fml::TaskRunner::RunNowOrPostTask(raster_task_runner, raster_task); + } + latch.Signal(); + }; + + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetIOTaskRunner(), io_task); + + latch.Wait(); + if (!should_post_raster_task) { + // See comment on should_post_raster_task, in this case the raster_task + // wasn't executed, and we just run it here as the platform thread + // is the raster thread. + raster_task(); + } + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewDestroyed() { + TRACE_EVENT0("flutter", "Shell::OnPlatformViewDestroyed"); + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + // Prevent any request to change the thread configuration for raster and + // platform queues while the platform view is being destroyed. + // + // This prevents false positives such as this method starts assuming that the + // raster and platform queues have a given thread configuration, but then the + // configuration is changed by a task, and the assumption is no longer true. + // + // This incorrect assumption can lead to deadlock. + rasterizer_->DisableThreadMergerIfNeeded(); + + // Notify the Dart VM that the PlatformView has been destroyed and some + // cleanup activity can be done (e.g: garbage collect the Dart heap). + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetUITaskRunner(), + [engine = engine_->GetWeakPtr()]() { + if (engine) { + engine->NotifyDestroyed(); + } + }); + + // Note: + // This is a synchronous operation because certain platforms depend on + // setup/suspension of all activities that may be interacting with the GPU in + // a synchronous fashion. + // The UI thread does not need to be serialized here - there is sufficient + // guardrailing in the rasterizer to allow the UI thread to post work to it + // even after the surface has been torn down. + + fml::AutoResetWaitableEvent latch; + + auto io_task = [io_manager = io_manager_.get(), &latch]() { + // Execute any pending Skia object deletions while GPU access is still + // allowed. + io_manager->GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers().SetIfFalse( + [&] { io_manager->GetSkiaUnrefQueue()->Drain(); })); + // Step 4: All done. Signal the latch that the platform thread is waiting + // on. + latch.Signal(); + }; + + auto raster_task = [rasterizer = rasterizer_->GetWeakPtr(), + io_task_runner = task_runners_.GetIOTaskRunner(), + io_task]() { + if (rasterizer) { + // Enables the thread merger which is required prior tearing down the + // rasterizer. If the raster and platform threads are merged, tearing down + // the rasterizer unmerges the threads. + rasterizer->EnableThreadMergerIfNeeded(); + rasterizer->Teardown(); + } + // Step 2: Tell the IO thread to complete its remaining work. + fml::TaskRunner::RunNowOrPostTask(io_task_runner, io_task); + }; + + // Step 1: Post a task to the Raster thread (possibly this thread) to tell the + // rasterizer the output surface is going away. + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetRasterTaskRunner(), + raster_task); + latch.Wait(); + // On Android, the external view embedder may post a task to the platform + // thread, and wait until it completes if overlay surfaces must be released. + // However, the platform thread might be blocked when Dart is initializing. + // In this situation, calling TeardownExternalViewEmbedder is safe because no + // platform views have been created before Flutter renders the first frame. + // Overall, the longer term plan is to remove this implementation once + // https://github.com/flutter/flutter/issues/96679 is fixed. + rasterizer_->TeardownExternalViewEmbedder(); +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewScheduleFrame() { + TRACE_EVENT0("flutter", "Shell::OnPlatformViewScheduleFrame"); + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetUITaskRunner(), + [engine = engine_->GetWeakPtr()]() { + if (engine) { + engine->ScheduleFrame(); + } + }); +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewSetViewportMetrics(int64_t view_id, + const ViewportMetrics& metrics) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + if (metrics.device_pixel_ratio <= 0 || metrics.physical_width <= 0 || + metrics.physical_height <= 0) { + // Ignore invalid view-port metrics. + return; + } + + // This is the formula Android uses. + // https://android.googlesource.com/platform/frameworks/base/+/39ae5bac216757bc201490f4c7b8c0f63006c6cd/libs/hwui/renderthread/CacheManager.cpp#45 + resource_cache_limit_ = + metrics.physical_width * metrics.physical_height * 12 * 4; + size_t resource_cache_max_bytes = + resource_cache_limit_calculator_->GetResourceCacheMaxBytes(); + task_runners_.GetRasterTaskRunner()->PostTask( + [rasterizer = rasterizer_->GetWeakPtr(), resource_cache_max_bytes] { + if (rasterizer) { + rasterizer->SetResourceCacheMaxBytes(resource_cache_max_bytes, false); + } + }); + + fml::TaskRunner::RunNowAndFlushMessages( + task_runners_.GetUITaskRunner(), + [engine = engine_->GetWeakPtr(), view_id, metrics]() { + if (engine) { + engine->SetViewportMetrics(view_id, metrics); + } + }); + + { + std::scoped_lock lock(resize_mutex_); + expected_frame_sizes_[view_id] = + SkISize::Make(metrics.physical_width, metrics.physical_height); + device_pixel_ratio_ = metrics.device_pixel_ratio; + } +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewDispatchPlatformMessage( + std::unique_ptr message) { + FML_DCHECK(is_set_up_); +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + if (!task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()) { + std::scoped_lock lock(misbehaving_message_channels_mutex_); + auto inserted = misbehaving_message_channels_.insert(message->channel()); + if (inserted.second) { + FML_LOG(ERROR) + << "The '" << message->channel() + << "' channel sent a message from native to Flutter on a " + "non-platform thread. Platform channel messages must be sent on " + "the platform thread. Failure to do so may result in data loss or " + "crashes, and must be fixed in the plugin or application code " + "creating that channel.\n" + "See https://docs.flutter.dev/platform-integration/" + "platform-channels#channels-and-platform-threading for more " + "information."; + } + } +#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + + // The static leak checker gets confused by the use of fml::MakeCopyable. + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + fml::TaskRunner::RunNowAndFlushMessages( + task_runners_.GetUITaskRunner(), + fml::MakeCopyable([engine = engine_->GetWeakPtr(), + message = std::move(message)]() mutable { + if (engine) { + engine->DispatchPlatformMessage(std::move(message)); + } + })); +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewDispatchPointerDataPacket( + std::unique_ptr packet) { + TRACE_EVENT0_WITH_FLOW_IDS( + "flutter", "Shell::OnPlatformViewDispatchPointerDataPacket", + /*flow_id_count=*/1, /*flow_ids=*/&next_pointer_flow_id_); + TRACE_FLOW_BEGIN("flutter", "PointerEvent", next_pointer_flow_id_); + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + task_runners_.GetUITaskRunner()->PostTask( + fml::MakeCopyable([engine = weak_engine_, packet = std::move(packet), + flow_id = next_pointer_flow_id_]() mutable { + if (engine) { + engine->DispatchPointerDataPacket(std::move(packet), flow_id); + } + })); + next_pointer_flow_id_++; +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewDispatchSemanticsAction(int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + fml::TaskRunner::RunNowAndFlushMessages( + task_runners_.GetUITaskRunner(), + fml::MakeCopyable([engine = engine_->GetWeakPtr(), view_id, node_id, + action, args = std::move(args)]() mutable { + if (engine) { + engine->DispatchSemanticsAction(view_id, node_id, action, + std::move(args)); + } + })); +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewSetSemanticsEnabled(bool enabled) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + fml::TaskRunner::RunNowAndFlushMessages( + task_runners_.GetUITaskRunner(), + [engine = engine_->GetWeakPtr(), enabled] { + if (engine) { + engine->SetSemanticsEnabled(enabled); + } + }); +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewSetAccessibilityFeatures(int32_t flags) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + fml::TaskRunner::RunNowAndFlushMessages( + task_runners_.GetUITaskRunner(), [engine = engine_->GetWeakPtr(), flags] { + if (engine) { + engine->SetAccessibilityFeatures(flags); + } + }); +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewRegisterTexture( + std::shared_ptr texture) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + task_runners_.GetRasterTaskRunner()->PostTask( + [rasterizer = rasterizer_->GetWeakPtr(), texture] { + if (rasterizer) { + if (auto registry = rasterizer->GetTextureRegistry()) { + registry->RegisterTexture(texture); + } + } + }); +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewUnregisterTexture(int64_t texture_id) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + task_runners_.GetRasterTaskRunner()->PostTask( + [rasterizer = rasterizer_->GetWeakPtr(), texture_id]() { + if (rasterizer) { + if (auto registry = rasterizer->GetTextureRegistry()) { + registry->UnregisterTexture(texture_id); + } + } + }); +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + // Tell the rasterizer that one of its textures has a new frame available. + task_runners_.GetRasterTaskRunner()->PostTask( + [rasterizer = rasterizer_->GetWeakPtr(), texture_id]() { + if (!rasterizer) { + return; + } + auto registry = rasterizer->GetTextureRegistry(); + + if (!registry) { + return; + } + + auto texture = registry->GetTexture(texture_id); + + if (!texture) { + return; + } + + texture->MarkNewFrameAvailable(); + }); + + // Schedule a new frame without having to rebuild the layer tree. + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetUITaskRunner(), + [engine = engine_->GetWeakPtr()]() { + if (engine) { + engine->ScheduleFrame(false); + } + }); +} + +// |PlatformView::Delegate| +void Shell::OnPlatformViewSetNextFrameCallback(const fml::closure& closure) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + task_runners_.GetRasterTaskRunner()->PostTask( + [rasterizer = rasterizer_->GetWeakPtr(), closure = closure]() { + if (rasterizer) { + rasterizer->SetNextFrameCallback(closure); + } + }); +} + +// |PlatformView::Delegate| +const Settings& Shell::OnPlatformViewGetSettings() const { + return settings_; +} + +// |Animator::Delegate| +void Shell::OnAnimatorBeginFrame(fml::TimePoint frame_target_time, + uint64_t frame_number) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + // record the target time for use by rasterizer. + { + std::scoped_lock time_recorder_lock(time_recorder_mutex_); + latest_frame_target_time_.emplace(frame_target_time); + } + if (engine_) { + engine_->BeginFrame(frame_target_time, frame_number); + } +} + +// |Animator::Delegate| +void Shell::OnAnimatorNotifyIdle(fml::TimeDelta deadline) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + if (engine_) { + engine_->NotifyIdle(deadline); + } +} + +void Shell::OnAnimatorUpdateLatestFrameTargetTime( + fml::TimePoint frame_target_time) { + FML_DCHECK(is_set_up_); + + // record the target time for use by rasterizer. + { + std::scoped_lock time_recorder_lock(time_recorder_mutex_); + if (!latest_frame_target_time_) { + latest_frame_target_time_ = frame_target_time; + } else if (latest_frame_target_time_ < frame_target_time) { + latest_frame_target_time_ = frame_target_time; + } + } +} + +// |Animator::Delegate| +void Shell::OnAnimatorDraw(std::shared_ptr pipeline) { + FML_DCHECK(is_set_up_); + + task_runners_.GetRasterTaskRunner()->PostTask(fml::MakeCopyable( + [&waiting_for_first_frame = waiting_for_first_frame_, + &waiting_for_first_frame_condition = waiting_for_first_frame_condition_, + rasterizer = rasterizer_->GetWeakPtr(), + weak_pipeline = std::weak_ptr(pipeline)]() mutable { + if (rasterizer) { + std::shared_ptr pipeline = weak_pipeline.lock(); + if (pipeline) { + rasterizer->Draw(pipeline); + } + + if (waiting_for_first_frame.load()) { + waiting_for_first_frame.store(false); + waiting_for_first_frame_condition.notify_all(); + } + } + })); +} + +// |Animator::Delegate| +void Shell::OnAnimatorDrawLastLayerTrees( + std::unique_ptr frame_timings_recorder) { + FML_DCHECK(is_set_up_); + + auto task = fml::MakeCopyable( + [rasterizer = rasterizer_->GetWeakPtr(), + frame_timings_recorder = std::move(frame_timings_recorder)]() mutable { + if (rasterizer) { + rasterizer->DrawLastLayerTrees(std::move(frame_timings_recorder)); + } + }); + + task_runners_.GetRasterTaskRunner()->PostTask(task); +} + +// |Engine::Delegate| +void Shell::OnEngineUpdateSemantics(int64_t view_id, + SemanticsNodeUpdates update, + CustomAccessibilityActionUpdates actions) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + task_runners_.GetPlatformTaskRunner()->RunNowOrPostTask( + task_runners_.GetPlatformTaskRunner(), + [view = platform_view_->GetWeakPtr(), update = std::move(update), + actions = std::move(actions), view_id = view_id] { + if (view) { + view->UpdateSemantics(view_id, update, actions); + } + }); +} + +// |Engine::Delegate| +void Shell::OnEngineHandlePlatformMessage( + std::unique_ptr message) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + if (message->channel() == kSkiaChannel) { + HandleEngineSkiaMessage(std::move(message)); + return; + } + + if (platform_message_handler_) { + if (route_messages_through_platform_thread_ && + !platform_message_handler_ + ->DoesHandlePlatformMessageOnPlatformThread()) { +#if _WIN32 + // On Windows capturing a TaskRunner with a TaskRunner will cause an + // uncaught exception in process shutdown because of the deletion order of + // global variables. See also + // https://github.com/flutter/flutter/issues/111575. + // This won't be an issue until Windows supports background platform + // channels (https://github.com/flutter/flutter/issues/93945). Then this + // can potentially be addressed by capturing a weak_ptr to an object that + // retains the ui TaskRunner, instead of the TaskRunner directly. + FML_DCHECK(false); +#endif + // We route messages through the platform thread temporarily when the + // shell is being initialized to be backwards compatible with setting + // message handlers in the same event as starting the isolate, but after + // it is started. + auto ui_task_runner = task_runners_.GetUITaskRunner(); + task_runners_.GetPlatformTaskRunner()->PostTask(fml::MakeCopyable( + [weak_platform_message_handler = + std::weak_ptr(platform_message_handler_), + message = std::move(message), ui_task_runner]() mutable { + ui_task_runner->PostTask( + fml::MakeCopyable([weak_platform_message_handler, + message = std::move(message)]() mutable { + auto platform_message_handler = + weak_platform_message_handler.lock(); + if (platform_message_handler) { + platform_message_handler->HandlePlatformMessage( + std::move(message)); + } + })); + })); + } else { + platform_message_handler_->HandlePlatformMessage(std::move(message)); + } + } else { + task_runners_.GetPlatformTaskRunner()->PostTask( + fml::MakeCopyable([view = platform_view_->GetWeakPtr(), + message = std::move(message)]() mutable { + if (view) { + view->HandlePlatformMessage(std::move(message)); + } + })); + } +} + +void Shell::OnEngineChannelUpdate(std::string name, bool listening) { + FML_DCHECK(is_set_up_); + + task_runners_.GetPlatformTaskRunner()->PostTask( + [view = platform_view_->GetWeakPtr(), name = std::move(name), listening] { + if (view) { + view->SendChannelUpdate(name, listening); + } + }); +} + +void Shell::HandleEngineSkiaMessage(std::unique_ptr message) { + const auto& data = message->data(); + + rapidjson::Document document; + document.Parse(reinterpret_cast(data.GetMapping()), + data.GetSize()); + if (document.HasParseError() || !document.IsObject()) { + return; + } + auto root = document.GetObject(); + auto method = root.FindMember("method"); + if (method->value != "Skia.setResourceCacheMaxBytes") { + return; + } + auto args = root.FindMember("args"); + if (args == root.MemberEnd() || !args->value.IsInt()) { + return; + } + + task_runners_.GetRasterTaskRunner()->PostTask( + [rasterizer = rasterizer_->GetWeakPtr(), max_bytes = args->value.GetInt(), + response = message->response()] { + if (rasterizer) { + rasterizer->SetResourceCacheMaxBytes(static_cast(max_bytes), + true); + } + if (response) { + // The framework side expects this to be valid json encoded as a list. + // Return `[true]` to signal success. + std::vector data = {'[', 't', 'r', 'u', 'e', ']'}; + response->Complete( + std::make_unique(std::move(data))); + } + }); +} + +// |Engine::Delegate| +void Shell::OnPreEngineRestart() { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetPlatformTaskRunner(), + [view = platform_view_->GetWeakPtr(), &latch]() { + if (view) { + view->OnPreEngineRestart(); + } + latch.Signal(); + }); + // This is blocking as any embedded platform views has to be flushed before + // we re-run the Dart code. + latch.Wait(); +} + +// |Engine::Delegate| +void Shell::OnRootIsolateCreated() { + if (is_added_to_service_protocol_) { + return; + } + auto description = GetServiceProtocolDescription(); + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetPlatformTaskRunner(), + [self = weak_factory_.GetWeakPtr(), + description = std::move(description)]() { + if (self) { + self->vm_->GetServiceProtocol()->AddHandler(self.get(), description); + } + }); + is_added_to_service_protocol_ = true; +} + +// |Engine::Delegate| +void Shell::UpdateIsolateDescription(const std::string isolate_name, + int64_t isolate_port) { + Handler::Description description(isolate_port, isolate_name); + vm_->GetServiceProtocol()->SetHandlerDescription(this, description); +} + +void Shell::SetNeedsReportTimings(bool value) { + needs_report_timings_ = value; +} + +// |Engine::Delegate| +std::unique_ptr> Shell::ComputePlatformResolvedLocale( + const std::vector& supported_locale_data) { + return platform_view_->ComputePlatformResolvedLocales(supported_locale_data); +} + +void Shell::LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) { + task_runners_.GetUITaskRunner()->PostTask(fml::MakeCopyable( + [engine = engine_->GetWeakPtr(), loading_unit_id, + data = std::move(snapshot_data), + instructions = std::move(snapshot_instructions)]() mutable { + if (engine) { + engine->LoadDartDeferredLibrary(loading_unit_id, std::move(data), + std::move(instructions)); + } + })); +} + +void Shell::LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string error_message, + bool transient) { + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetUITaskRunner(), + [engine = weak_engine_, loading_unit_id, error_message, transient] { + if (engine) { + engine->LoadDartDeferredLibraryError(loading_unit_id, error_message, + transient); + } + }); +} + +void Shell::UpdateAssetResolverByType( + std::unique_ptr updated_asset_resolver, + AssetResolver::AssetResolverType type) { + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetUITaskRunner(), + fml::MakeCopyable( + [engine = weak_engine_, type, + asset_resolver = std::move(updated_asset_resolver)]() mutable { + if (engine) { + engine->GetAssetManager()->UpdateResolverByType( + std::move(asset_resolver), type); + } + })); +} + +// |Engine::Delegate| +void Shell::RequestDartDeferredLibrary(intptr_t loading_unit_id) { + task_runners_.GetPlatformTaskRunner()->PostTask( + [view = platform_view_->GetWeakPtr(), loading_unit_id] { + if (view) { + view->RequestDartDeferredLibrary(loading_unit_id); + } + }); +} + +// |Engine::Delegate| +double Shell::GetScaledFontSize(double unscaled_font_size, + int configuration_id) const { + return platform_view_->GetScaledFontSize(unscaled_font_size, + configuration_id); +} + +void Shell::RequestViewFocusChange(const ViewFocusChangeRequest& request) { + FML_DCHECK(is_set_up_); + + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetPlatformTaskRunner(), + [view = platform_view_->GetWeakPtr(), request] { + if (view) { + view->RequestViewFocusChange(request); + } + }); +} + +void Shell::ReportTimings() { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); + + auto timings = std::move(unreported_timings_); + unreported_timings_ = {}; + task_runners_.GetUITaskRunner()->PostTask([timings, engine = weak_engine_] { + if (engine) { + engine->ReportTimings(timings); + } + }); +} + +size_t Shell::UnreportedFramesCount() const { + // Check that this is running on the raster thread to avoid race conditions. + FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); + FML_DCHECK(unreported_timings_.size() % (FrameTiming::kStatisticsCount) == 0); + return unreported_timings_.size() / (FrameTiming::kStatisticsCount); +} + +void Shell::OnFrameRasterized(const FrameTiming& timing) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); + + // The C++ callback defined in settings.h and set by Flutter runner. This is + // independent of the timings report to the Dart side. + if (settings_.frame_rasterized_callback) { + settings_.frame_rasterized_callback(timing); + } + + if (!needs_report_timings_) { + return; + } + + size_t old_count = unreported_timings_.size(); + (void)old_count; + for (auto phase : FrameTiming::kPhases) { + unreported_timings_.push_back( + timing.Get(phase).ToEpochDelta().ToMicroseconds()); + } + unreported_timings_.push_back(timing.GetLayerCacheCount()); + unreported_timings_.push_back(timing.GetLayerCacheBytes()); + unreported_timings_.push_back(timing.GetPictureCacheCount()); + unreported_timings_.push_back(timing.GetPictureCacheBytes()); + unreported_timings_.push_back(timing.GetFrameNumber()); + FML_DCHECK(unreported_timings_.size() == + old_count + FrameTiming::kStatisticsCount); + + // In tests using iPhone 6S with profile mode, sending a batch of 1 frame or a + // batch of 100 frames have roughly the same cost of less than 0.1ms. Sending + // a batch of 500 frames costs about 0.2ms. The 1 second threshold usually + // kicks in before we reaching the following 100 frames threshold. The 100 + // threshold here is mainly for unit tests (so we don't have to write a + // 1-second unit test), and make sure that our vector won't grow too big with + // future 120fps, 240fps, or 1000fps displays. + // + // In the profile/debug mode, the timings are used by development tools which + // require a latency of no more than 100ms. Hence we lower that 1-second + // threshold to 100ms because performance overhead isn't that critical in + // those cases. + if (!first_frame_rasterized_ || UnreportedFramesCount() >= 100) { + first_frame_rasterized_ = true; + ReportTimings(); + } else if (!frame_timings_report_scheduled_) { +#if FLUTTER_RELEASE + constexpr int kBatchTimeInMilliseconds = 1000; +#else + constexpr int kBatchTimeInMilliseconds = 100; +#endif + + // Also make sure that frame times get reported with a max latency of 1 + // second. Otherwise, the timings of last few frames of an animation may + // never be reported until the next animation starts. + frame_timings_report_scheduled_ = true; + task_runners_.GetRasterTaskRunner()->PostDelayedTask( + [self = weak_factory_gpu_->GetWeakPtr()]() { + if (!self) { + return; + } + self->frame_timings_report_scheduled_ = false; + if (self->UnreportedFramesCount() > 0) { + self->ReportTimings(); + } + }, + fml::TimeDelta::FromMilliseconds(kBatchTimeInMilliseconds)); + } +} + +fml::Milliseconds Shell::GetFrameBudget() { + if (cached_display_refresh_rate_.has_value()) { + return cached_display_refresh_rate_.value(); + } + double display_refresh_rate = display_manager_->GetMainDisplayRefreshRate(); + if (display_refresh_rate > 0) { + cached_display_refresh_rate_ = + fml::RefreshRateToFrameBudget(display_refresh_rate); + } else { + cached_display_refresh_rate_ = fml::kDefaultFrameBudget; + } + return cached_display_refresh_rate_.value_or(fml::kDefaultFrameBudget); +} + +fml::TimePoint Shell::GetLatestFrameTargetTime() const { + std::scoped_lock time_recorder_lock(time_recorder_mutex_); + FML_CHECK(latest_frame_target_time_.has_value()) + << "GetLatestFrameTargetTime called before OnAnimatorBeginFrame"; + // Covered by FML_CHECK(). + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return latest_frame_target_time_.value(); +} + +// |Rasterizer::Delegate| +bool Shell::ShouldDiscardLayerTree(int64_t view_id, + const flutter::LayerTree& tree) { + std::scoped_lock lock(resize_mutex_); + auto expected_frame_size = ExpectedFrameSize(view_id); + return !expected_frame_size.isEmpty() && + ToSkISize(tree.frame_size()) != expected_frame_size; +} + +// |ServiceProtocol::Handler| +fml::RefPtr Shell::GetServiceProtocolHandlerTaskRunner( + std::string_view method) const { + FML_DCHECK(is_set_up_); + auto found = service_protocol_handlers_.find(method); + if (found != service_protocol_handlers_.end()) { + return found->second.first; + } + return task_runners_.GetUITaskRunner(); +} + +// |ServiceProtocol::Handler| +bool Shell::HandleServiceProtocolMessage( + std::string_view method, // one if the extension names specified above. + const ServiceProtocolMap& params, + rapidjson::Document* response) { + auto found = service_protocol_handlers_.find(method); + if (found != service_protocol_handlers_.end()) { + return found->second.second(params, response); + } + return false; +} + +// |ServiceProtocol::Handler| +ServiceProtocol::Handler::Description Shell::GetServiceProtocolDescription() + const { + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + if (!weak_engine_) { + return ServiceProtocol::Handler::Description(); + } + + return { + weak_engine_->GetUIIsolateMainPort(), + weak_engine_->GetUIIsolateName(), + }; +} + +static void ServiceProtocolParameterError(rapidjson::Document* response, + std::string error_details) { + auto& allocator = response->GetAllocator(); + response->SetObject(); + const int64_t kInvalidParams = -32602; + response->AddMember("code", kInvalidParams, allocator); + response->AddMember("message", "Invalid params", allocator); + { + rapidjson::Value details(rapidjson::kObjectType); + details.AddMember("details", std::move(error_details), allocator); + response->AddMember("data", details, allocator); + } +} + +static void ServiceProtocolFailureError(rapidjson::Document* response, + std::string message) { + auto& allocator = response->GetAllocator(); + response->SetObject(); + const int64_t kJsonServerError = -32000; + response->AddMember("code", kJsonServerError, allocator); + response->AddMember("message", std::move(message), allocator); +} + +// Service protocol handler +bool Shell::OnServiceProtocolScreenshot( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); + auto screenshot = rasterizer_->ScreenshotLastLayerTree( + Rasterizer::ScreenshotType::CompressedImage, true); + if (screenshot.data) { + response->SetObject(); + auto& allocator = response->GetAllocator(); + response->AddMember("type", "Screenshot", allocator); + rapidjson::Value image; + image.SetString(static_cast(screenshot.data->data()), + screenshot.data->size(), allocator); + response->AddMember("screenshot", image, allocator); + return true; + } + ServiceProtocolFailureError(response, "Could not capture image screenshot."); + return false; +} + +// Service protocol handler +bool Shell::OnServiceProtocolScreenshotSKP( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); + if (settings_.enable_impeller) { + ServiceProtocolFailureError( + response, "Cannot capture SKP screenshot with Impeller enabled."); + return false; + } + auto screenshot = rasterizer_->ScreenshotLastLayerTree( + Rasterizer::ScreenshotType::SkiaPicture, true); + if (screenshot.data) { + response->SetObject(); + auto& allocator = response->GetAllocator(); + response->AddMember("type", "ScreenshotSkp", allocator); + rapidjson::Value skp; + skp.SetString(static_cast(screenshot.data->data()), + screenshot.data->size(), allocator); + response->AddMember("skp", skp, allocator); + return true; + } + ServiceProtocolFailureError(response, "Could not capture SKP screenshot."); + return false; +} + +// Service protocol handler +bool Shell::OnServiceProtocolRunInView( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + if (params.count("mainScript") == 0) { + ServiceProtocolParameterError(response, + "'mainScript' parameter is missing."); + return false; + } + + if (params.count("assetDirectory") == 0) { + ServiceProtocolParameterError(response, + "'assetDirectory' parameter is missing."); + return false; + } + + std::string main_script_path = + fml::paths::FromURI(params.at("mainScript").data()); + std::string asset_directory_path = + fml::paths::FromURI(params.at("assetDirectory").data()); + + auto main_script_file_mapping = + std::make_unique(fml::OpenFile( + main_script_path.c_str(), false, fml::FilePermission::kRead)); + + auto isolate_configuration = IsolateConfiguration::CreateForKernel( + std::move(main_script_file_mapping)); + + RunConfiguration configuration(std::move(isolate_configuration)); + + configuration.SetEntrypointAndLibrary(engine_->GetLastEntrypoint(), + engine_->GetLastEntrypointLibrary()); + configuration.SetEntrypointArgs(engine_->GetLastEntrypointArgs()); + + configuration.AddAssetResolver(std::make_unique( + fml::OpenDirectory(asset_directory_path.c_str(), false, + fml::FilePermission::kRead), + false)); + + // Preserve any original asset resolvers to avoid syncing unchanged assets + // over the DevFS connection. + auto old_asset_manager = engine_->GetAssetManager(); + if (old_asset_manager != nullptr) { + for (auto& old_resolver : old_asset_manager->TakeResolvers()) { + if (old_resolver->IsValidAfterAssetManagerChange()) { + configuration.AddAssetResolver(std::move(old_resolver)); + } + } + } + + auto& allocator = response->GetAllocator(); + response->SetObject(); + if (engine_->Restart(std::move(configuration))) { + response->AddMember("type", "Success", allocator); + auto new_description = GetServiceProtocolDescription(); + rapidjson::Value view(rapidjson::kObjectType); + new_description.Write(this, view, allocator); + response->AddMember("view", view, allocator); + return true; + } else { + FML_DLOG(ERROR) << "Could not run configuration in engine."; + ServiceProtocolFailureError(response, + "Could not run configuration in engine."); + return false; + } + + FML_DCHECK(false); + return false; +} + +// Service protocol handler +bool Shell::OnServiceProtocolFlushUIThreadTasks( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + // This API should not be invoked by production code. + // It can potentially starve the service isolate if the main isolate pauses + // at a breakpoint or is in an infinite loop. + // + // It should be invoked from the VM Service and blocks it until UI thread + // tasks are processed. + response->SetObject(); + response->AddMember("type", "Success", response->GetAllocator()); + return true; +} + +bool Shell::OnServiceProtocolGetDisplayRefreshRate( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + response->SetObject(); + response->AddMember("type", "DisplayRefreshRate", response->GetAllocator()); + response->AddMember("fps", display_manager_->GetMainDisplayRefreshRate(), + response->GetAllocator()); + return true; +} + +double Shell::GetMainDisplayRefreshRate() { + return display_manager_->GetMainDisplayRefreshRate(); +} + +void Shell::RegisterImageDecoder(ImageGeneratorFactory factory, + int32_t priority) { + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + FML_DCHECK(is_set_up_); + + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetUITaskRunner(), + [engine = engine_->GetWeakPtr(), factory = std::move(factory), + priority]() { + if (engine) { + engine->GetImageGeneratorRegistry()->AddFactory(factory, priority); + } + }); +} + +bool Shell::OnServiceProtocolGetSkSLs( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + FML_DCHECK(task_runners_.GetIOTaskRunner()->RunsTasksOnCurrentThread()); + response->SetObject(); + response->AddMember("type", "GetSkSLs", response->GetAllocator()); + + rapidjson::Value shaders_json(rapidjson::kObjectType); +#if !SLIMPELLER + PersistentCache* persistent_cache = PersistentCache::GetCacheForProcess(); + std::vector sksls = persistent_cache->LoadSkSLs(); + for (const auto& sksl : sksls) { + size_t b64_size = Base64::EncodedSize(sksl.value->size()); + sk_sp b64_data = SkData::MakeUninitialized(b64_size + 1); + char* b64_char = static_cast(b64_data->writable_data()); + Base64::Encode(sksl.value->data(), sksl.value->size(), b64_char); + b64_char[b64_size] = 0; // make it null terminated for printing + rapidjson::Value shader_value(b64_char, response->GetAllocator()); + std::string_view key_view(reinterpret_cast(sksl.key->data()), + sksl.key->size()); + auto encode_result = fml::Base32Encode(key_view); + if (!encode_result.first) { + continue; + } + rapidjson::Value shader_key(encode_result.second, response->GetAllocator()); + shaders_json.AddMember(shader_key, shader_value, response->GetAllocator()); + } +#endif // !SLIMPELLER + response->AddMember("SkSLs", shaders_json, response->GetAllocator()); + return true; +} + +bool Shell::OnServiceProtocolEstimateRasterCacheMemory( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); + + uint64_t layer_cache_byte_size = 0u; + uint64_t picture_cache_byte_size = 0u; + +#if !SLIMPELLER + const auto& raster_cache = rasterizer_->compositor_context()->raster_cache(); + layer_cache_byte_size = raster_cache.EstimateLayerCacheByteSize(); + picture_cache_byte_size = raster_cache.EstimatePictureCacheByteSize(); +#endif // !SLIMPELLER + + response->SetObject(); + response->AddMember("type", "EstimateRasterCacheMemory", + response->GetAllocator()); + response->AddMember("layerBytes", layer_cache_byte_size, + response->GetAllocator()); + response->AddMember("pictureBytes", picture_cache_byte_size, + response->GetAllocator()); + return true; +} + +// Service protocol handler +bool Shell::OnServiceProtocolSetAssetBundlePath( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + if (params.count("assetDirectory") == 0) { + ServiceProtocolParameterError(response, + "'assetDirectory' parameter is missing."); + return false; + } + + auto& allocator = response->GetAllocator(); + response->SetObject(); + + auto asset_manager = std::make_shared(); + + if (!asset_manager->PushFront(std::make_unique( + fml::OpenDirectory(params.at("assetDirectory").data(), false, + fml::FilePermission::kRead), + false))) { + // The new asset directory path was invalid. + FML_DLOG(ERROR) << "Could not update asset directory."; + ServiceProtocolFailureError(response, "Could not update asset directory."); + return false; + } + + // Preserve any original asset resolvers to avoid syncing unchanged assets + // over the DevFS connection. + auto old_asset_manager = engine_->GetAssetManager(); + if (old_asset_manager != nullptr) { + for (auto& old_resolver : old_asset_manager->TakeResolvers()) { + if (old_resolver->IsValidAfterAssetManagerChange()) { + asset_manager->PushBack(std::move(old_resolver)); + } + } + } + + if (engine_->UpdateAssetManager(asset_manager)) { + response->AddMember("type", "Success", allocator); + auto new_description = GetServiceProtocolDescription(); + rapidjson::Value view(rapidjson::kObjectType); + new_description.Write(this, view, allocator); + response->AddMember("view", view, allocator); + return true; + } else { + FML_DLOG(ERROR) << "Could not update asset directory."; + ServiceProtocolFailureError(response, "Could not update asset directory."); + return false; + } + + FML_DCHECK(false); + return false; +} + +void Shell::SendFontChangeNotification() { + // After system fonts are reloaded, we send a system channel message + // to notify flutter framework. + rapidjson::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + rapidjson::Value message_value; + message_value.SetString(kFontChange, allocator); + document.AddMember(kTypeKey, message_value, allocator); + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + std::string message = buffer.GetString(); + std::unique_ptr fontsChangeMessage = + std::make_unique( + kSystemChannel, + fml::MallocMapping::Copy(message.c_str(), message.length()), nullptr); + OnPlatformViewDispatchPlatformMessage(std::move(fontsChangeMessage)); +} + +bool Shell::OnServiceProtocolReloadAssetFonts( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + if (!engine_) { + return false; + } + engine_->GetFontCollection().RegisterFonts(engine_->GetAssetManager()); + engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache(); + SendFontChangeNotification(); + + auto& allocator = response->GetAllocator(); + response->SetObject(); + response->AddMember("type", "Success", allocator); + + return true; +} + +void Shell::OnPlatformViewAddView(int64_t view_id, + const ViewportMetrics& viewport_metrics, + AddViewCallback callback) { + TRACE_EVENT0("flutter", "Shell::AddView"); + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + FML_DCHECK(view_id != kFlutterImplicitViewId) + << "Unexpected request to add the implicit view #" + << kFlutterImplicitViewId << ". This view should never be added."; + + task_runners_.GetUITaskRunner()->RunNowOrPostTask( + task_runners_.GetUITaskRunner(), [engine = engine_->GetWeakPtr(), // + viewport_metrics, // + view_id, // + callback = std::move(callback) // + ] { + if (engine) { + engine->AddView(view_id, viewport_metrics, callback); + } + }); +} + +void Shell::OnPlatformViewRemoveView(int64_t view_id, + RemoveViewCallback callback) { + TRACE_EVENT0("flutter", "Shell::RemoveView"); + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + FML_DCHECK(view_id != kFlutterImplicitViewId) + << "Unexpected request to remove the implicit view #" + << kFlutterImplicitViewId << ". This view should never be removed."; + + expected_frame_sizes_.erase(view_id); + task_runners_.GetUITaskRunner()->RunNowOrPostTask( + task_runners_.GetUITaskRunner(), + [&task_runners = task_runners_, // + engine = engine_->GetWeakPtr(), // + rasterizer = rasterizer_->GetWeakPtr(), // + view_id, // + callback = std::move(callback) // + ]() mutable { + bool removed = false; + if (engine) { + removed = engine->RemoveView(view_id); + } + task_runners.GetRasterTaskRunner()->PostTask( + [rasterizer, view_id, callback = std::move(callback), removed]() { + if (rasterizer) { + rasterizer->CollectView(view_id); + } + // Only call the callback after it is known for certain that the + // raster thread will not try to use resources associated with + // the view. + callback(removed); + }); + }); +} + +void Shell::OnPlatformViewSendViewFocusEvent(const ViewFocusEvent& event) { + TRACE_EVENT0("flutter", "Shell:: OnPlatformViewSendViewFocusEvent"); + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + task_runners_.GetUITaskRunner()->RunNowOrPostTask( + task_runners_.GetUITaskRunner(), + [engine = engine_->GetWeakPtr(), event = event] { + if (engine) { + engine->SendViewFocusEvent(event); + } + }); +} + +Rasterizer::Screenshot Shell::Screenshot( + Rasterizer::ScreenshotType screenshot_type, + bool base64_encode) { + if (settings_.enable_impeller) { + switch (screenshot_type) { + case Rasterizer::ScreenshotType::SkiaPicture: + FML_LOG(ERROR) + << "Impeller backend cannot produce ScreenshotType::SkiaPicture."; + return {}; + case Rasterizer::ScreenshotType::UncompressedImage: + case Rasterizer::ScreenshotType::CompressedImage: + case Rasterizer::ScreenshotType::SurfaceData: + break; + } + } + TRACE_EVENT0("flutter", "Shell::Screenshot"); + fml::AutoResetWaitableEvent latch; + Rasterizer::Screenshot screenshot; + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetRasterTaskRunner(), [&latch, // + rasterizer = GetRasterizer(), // + &screenshot, // + screenshot_type, // + base64_encode // + ]() { + if (rasterizer) { + screenshot = rasterizer->ScreenshotLastLayerTree(screenshot_type, + base64_encode); + } + latch.Signal(); + }); + latch.Wait(); + return screenshot; +} + +fml::Status Shell::WaitForFirstFrame(fml::TimeDelta timeout) { + FML_DCHECK(is_set_up_); + if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() || + task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) { + return fml::Status(fml::StatusCode::kFailedPrecondition, + "WaitForFirstFrame called from thread that can't wait " + "because it is responsible for generating the frame."); + } + + // Check for overflow. + auto now = std::chrono::steady_clock::now(); + auto max_duration = std::chrono::steady_clock::time_point::max() - now; + auto desired_duration = std::chrono::milliseconds(timeout.ToMilliseconds()); + auto duration = + now + (desired_duration > max_duration ? max_duration : desired_duration); + + std::unique_lock lock(waiting_for_first_frame_mutex_); + bool success = waiting_for_first_frame_condition_.wait_until( + lock, duration, [&waiting_for_first_frame = waiting_for_first_frame_] { + return !waiting_for_first_frame.load(); + }); + if (success) { + return fml::Status(); + } else { + return fml::Status(fml::StatusCode::kDeadlineExceeded, "timeout"); + } +} + +bool Shell::ReloadSystemFonts() { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + if (!engine_) { + return false; + } + engine_->SetupDefaultFontManager(); + engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache(); + // After system fonts are reloaded, we send a system channel message + // to notify flutter framework. + SendFontChangeNotification(); + return true; +} + +std::shared_ptr Shell::GetIsGpuDisabledSyncSwitch() + const { + return is_gpu_disabled_sync_switch_; +} + +void Shell::SetGpuAvailability(GpuAvailability availability) { + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + switch (availability) { + case GpuAvailability::kAvailable: + is_gpu_disabled_sync_switch_->SetSwitch(false); + return; + case GpuAvailability::kFlushAndMakeUnavailable: { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetIOTaskRunner(), + [io_manager = io_manager_.get(), &latch]() { + io_manager->GetSkiaUnrefQueue()->Drain(); + latch.Signal(); + }); + latch.Wait(); + } + // FALLTHROUGH + case GpuAvailability::kUnavailable: + is_gpu_disabled_sync_switch_->SetSwitch(true); + return; + default: + FML_DCHECK(false); + } +} + +void Shell::OnDisplayUpdates(std::vector> displays) { + FML_DCHECK(is_set_up_); + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + + std::vector display_data; + display_data.reserve(displays.size()); + for (const auto& display : displays) { + display_data.push_back(display->GetDisplayData()); + } + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetUITaskRunner(), + [engine = engine_->GetWeakPtr(), + display_data = std::move(display_data)]() { + if (engine) { + engine->SetDisplays(display_data); + } + }); + + display_manager_->HandleDisplayUpdates(std::move(displays)); +} + +fml::TimePoint Shell::GetCurrentTimePoint() { + return fml::TimePoint::Now(); +} + +const std::shared_ptr& +Shell::GetPlatformMessageHandler() const { + return platform_message_handler_; +} + +const std::weak_ptr Shell::GetVsyncWaiter() const { + if (!engine_) { + return {}; + } + return engine_->GetVsyncWaiter(); +} + +const std::shared_ptr +Shell::GetConcurrentWorkerTaskRunner() const { + FML_DCHECK(vm_); + if (!vm_) { + return nullptr; + } + return vm_->GetConcurrentWorkerTaskRunner(); +} + +SkISize Shell::ExpectedFrameSize(int64_t view_id) { + auto found = expected_frame_sizes_.find(view_id); + if (found == expected_frame_sizes_.end()) { + return SkISize::MakeEmpty(); + } + return found->second; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/shell.h b/flutter/engine/src/flutter/shell/common/shell.h new file mode 100644 index 0000000000000000000000000000000000000000..a5305e7abfdc953eca7902a7a1622ebd903cb95d --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell.h @@ -0,0 +1,815 @@ +// 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_COMMON_SHELL_H_ +#define FLUTTER_SHELL_COMMON_SHELL_H_ + +#include +#include +#include +#include + +#include "flutter/assets/directory_asset_bundle.h" +#include "flutter/common/graphics/texture.h" +#include "flutter/common/settings.h" +#include "flutter/common/task_runners.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/closure.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/ref_ptr.h" +#include "flutter/fml/memory/thread_checker.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/fml/status.h" +#include "flutter/fml/synchronization/sync_switch.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/thread.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/lib/ui/painting/image_generator_registry.h" +#include "flutter/lib/ui/semantics/custom_accessibility_action.h" +#include "flutter/lib/ui/semantics/semantics_node.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/runtime/dart_vm_lifecycle.h" +#include "flutter/runtime/platform_data.h" +#include "flutter/runtime/service_protocol.h" +#include "flutter/shell/common/animator.h" +#include "flutter/shell/common/display_manager.h" +#include "flutter/shell/common/engine.h" +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/common/rasterizer.h" +#include "flutter/shell/common/resource_cache_limit_calculator.h" +#include "flutter/shell/common/shell_io_manager.h" +#include "impeller/renderer/context.h" +#include "impeller/runtime_stage/runtime_stage.h" + +namespace flutter { + +/// Error exit codes for the Dart isolate. +enum class DartErrorCode { + // NOLINTBEGIN(readability-identifier-naming) + /// No error has occurred. + NoError = 0, + /// The Dart error code for an API error. + ApiError = 253, + /// The Dart error code for a compilation error. + CompilationError = 254, + /// The Dart error code for an unknown error. + UnknownError = 255 + // NOLINTEND(readability-identifier-naming) +}; + +/// Values for |Shell::SetGpuAvailability|. +enum class GpuAvailability { + /// Indicates that GPU operations should be permitted. + kAvailable = 0, + /// Indicates that the GPU is about to become unavailable, and to attempt to + /// flush any GPU related resources now. + kFlushAndMakeUnavailable = 1, + /// Indicates that the GPU is unavailable, and that no attempt should be made + /// to even flush GPU objects until it is available again. + kUnavailable = 2 +}; + +//------------------------------------------------------------------------------ +/// Perhaps the single most important class in the Flutter engine repository. +/// When embedders create a Flutter application, they are referring to the +/// creation of an instance of a shell. Creation and destruction of the shell is +/// synchronous and the embedder only holds a unique pointer to the shell. The +/// shell does not create the threads its primary components run on. Instead, it +/// is the embedder's responsibility to create threads and give the shell task +/// runners for those threads. Due to deterministic destruction of the shell, +/// the embedder can terminate all threads immediately after collecting the +/// shell. The shell must be created and destroyed on the same thread, but, +/// different shells (i.e. a separate instances of a Flutter application) may be +/// run on different threads simultaneously. The task runners themselves do not +/// have to be unique. If all task runner references given to the shell during +/// shell creation point to the same task runner, the Flutter application is +/// effectively single threaded. +/// +/// The shell is the central nervous system of the Flutter application. None of +/// the shell components are thread safe and must be created, accessed and +/// destroyed on the same thread. To interact with one another, the various +/// components delegate to the shell for communication. Instead of using back +/// pointers to the shell, a delegation pattern is used by all components that +/// want to communicate with one another. Because of this, the shell implements +/// the delegate interface for all these components. +/// +/// All shell methods accessed by the embedder may only be called on the +/// platform task runner. In case the embedder wants to directly access a shell +/// subcomponent, it is the embedder's responsibility to acquire a weak pointer +/// to that component and post a task to the task runner used by the component +/// to access its methods. The shell must also be destroyed on the platform +/// task runner. +/// +/// There is no explicit API to bootstrap and shutdown the Dart VM. The first +/// instance of the shell in the process bootstraps the Dart VM and the +/// destruction of the last shell instance destroys the same. Since different +/// shells may be created and destroyed on different threads. VM bootstrap may +/// happen on one thread but its collection on another. This behavior is thread +/// safe. +/// +class Shell final : public PlatformView::Delegate, + public Animator::Delegate, + public Engine::Delegate, + public Rasterizer::Delegate, + public ServiceProtocol::Handler, + public ResourceCacheLimitItem { + public: + template + using CreateCallback = std::function(Shell&)>; + typedef std::function( + Engine::Delegate& delegate, + const PointerDataDispatcherMaker& dispatcher_maker, + DartVM& vm, + fml::RefPtr isolate_snapshot, + TaskRunners task_runners, + const PlatformData& platform_data, + Settings settings, + std::unique_ptr animator, + fml::WeakPtr io_manager, + fml::RefPtr unref_queue, + fml::TaskRunnerAffineWeakPtr snapshot_delegate, + const std::shared_ptr& gpu_disabled_switch, + impeller::RuntimeStageBackend runtime_stage_type)> + EngineCreateCallback; + + //---------------------------------------------------------------------------- + /// @brief Creates a shell instance using the provided settings. The + /// callbacks to create the various shell subcomponents will be + /// called on the appropriate threads before this method returns. + /// If this is the first instance of a shell in the process, this + /// call also bootstraps the Dart VM. + /// @note The root isolate which will run this Shell's Dart code takes + /// its instructions from the passed in settings. This allows + /// embedders to host multiple Shells with different Dart code. + /// + /// @param[in] task_runners The task runners + /// @param[in] settings The settings + /// @param[in] on_create_platform_view The callback that must return a + /// platform view. This will be called on + /// the platform task runner before this + /// method returns. + /// @param[in] on_create_rasterizer That callback that must provide a + /// valid rasterizer. This will be called + /// on the render task runner before this + /// method returns. + /// @param[in] is_gpu_disabled The default value for the switch that + /// turns off the GPU. + /// + /// @return A full initialized shell if the settings and callbacks are + /// valid. The root isolate has been created but not yet launched. + /// It may be launched by obtaining the engine weak pointer and + /// posting a task onto the UI task runner with a valid run + /// configuration to run the isolate. The embedder must always + /// check the validity of the shell (using the IsSetup call) + /// immediately after getting a pointer to it. + /// + static std::unique_ptr Create( + const PlatformData& platform_data, + const TaskRunners& task_runners, + Settings settings, + const CreateCallback& on_create_platform_view, + const CreateCallback& on_create_rasterizer, + bool is_gpu_disabled = false); + + //---------------------------------------------------------------------------- + /// @brief Destroys the shell. This is a synchronous operation and + /// synchronous barrier blocks are introduced on the various + /// threads to ensure shutdown of all shell sub-components before + /// this method returns. + /// + ~Shell(); + + //---------------------------------------------------------------------------- + /// @brief Creates one Shell from another Shell where the created Shell + /// takes the opportunity to share any internal components it can. + /// This results is a Shell that has a smaller startup time cost + /// and a smaller memory footprint than an Shell created with the + /// Create function. + /// + /// The new Shell is returned in a running state so RunEngine + /// shouldn't be called again on the Shell. Once running, the + /// second Shell is mostly independent from the original Shell + /// and the original Shell doesn't need to keep running for the + /// spawned Shell to keep functioning. + /// @param[in] run_configuration A RunConfiguration used to run the Isolate + /// associated with this new Shell. It doesn't have to be the same + /// configuration as the current Shell but it needs to be in the + /// same snapshot or AOT. + /// + /// @see http://flutter.dev/go/multiple-engines + std::unique_ptr Spawn( + RunConfiguration run_configuration, + const std::string& initial_route, + const CreateCallback& on_create_platform_view, + const CreateCallback& on_create_rasterizer) const; + + //---------------------------------------------------------------------------- + /// @brief Starts an isolate for the given RunConfiguration. + /// + void RunEngine(RunConfiguration run_configuration); + + //---------------------------------------------------------------------------- + /// @brief Starts an isolate for the given RunConfiguration. The + /// result_callback will be called with the status of the + /// operation. + /// + void RunEngine(RunConfiguration run_configuration, + const std::function& result_callback); + + //------------------------------------------------------------------------------ + /// @return The settings used to launch this shell. + /// + const Settings& GetSettings() const override; + + //------------------------------------------------------------------------------ + /// @brief If callers wish to interact directly with any shell + /// subcomponents, they must (on the platform thread) obtain a + /// task runner that the component is designed to run on and a + /// weak pointer to that component. They may then post a task to + /// that task runner, do the validity check on that task runner + /// before performing any operation on that component. This + /// accessor allows callers to access the task runners for this + /// shell. + /// + /// @return The task runners current in use by the shell. + /// + const TaskRunners& GetTaskRunners() const override; + + //------------------------------------------------------------------------------ + /// @brief Getting the raster thread merger from parent shell, it can be + /// a null RefPtr when it's a root Shell or the + /// embedder_->SupportsDynamicThreadMerging() returns false. + /// + /// @return The raster thread merger used by the parent shell. + /// + const fml::RefPtr GetParentRasterThreadMerger() + const override; + + //---------------------------------------------------------------------------- + /// @brief Rasterizers may only be accessed on the raster task runner. + /// + /// @return A weak pointer to the rasterizer. + /// + fml::TaskRunnerAffineWeakPtr GetRasterizer() const; + + //------------------------------------------------------------------------------ + /// @brief Engines may only be accessed on the UI thread. This method is + /// deprecated, and implementers should instead use other API + /// available on the Shell or the PlatformView. + /// + /// @return A weak pointer to the engine. + /// + fml::WeakPtr GetEngine(); + + //---------------------------------------------------------------------------- + /// @brief Platform views may only be accessed on the platform task + /// runner. + /// + /// @return A weak pointer to the platform view. + /// + fml::WeakPtr GetPlatformView(); + + //---------------------------------------------------------------------------- + /// @brief The IO Manager may only be accessed on the IO task runner. + /// + /// @return A weak pointer to the IO manager. + /// + fml::WeakPtr GetIOManager(); + + // Embedders should call this under low memory conditions to free up + // internal caches used. + // + // This method posts a task to the raster threads to signal the Rasterizer to + // free resources. + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to notify that there is a low memory + /// warning. The shell will attempt to purge caches. Current, only + /// the rasterizer cache is purged. + void NotifyLowMemoryWarning() const; + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to flush the microtask queue. Required + /// when running with merged platform and UI threads, in which + /// case the embedder is responsible for flushing the microtask + /// queue. + void FlushMicrotaskQueue() const; + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to check if all shell subcomponents are + /// initialized. It is the embedder's responsibility to make this + /// call before accessing any other shell method. A shell that is + /// not set up must be discarded and another one created with + /// updated settings. + /// + /// @return Returns if the shell has been set up. Once set up, this does + /// not change for the life-cycle of the shell. + /// + bool IsSetup() const; + + //---------------------------------------------------------------------------- + /// @brief Captures a screenshot and optionally Base64 encodes the data + /// of the last layer tree rendered by the rasterizer in this + /// shell. + /// + /// @param[in] type The type of screenshot to capture. + /// @param[in] base64_encode If the screenshot data should be base64 + /// encoded. + /// + /// @return The screenshot result. + /// + Rasterizer::Screenshot Screenshot(Rasterizer::ScreenshotType type, + bool base64_encode); + + //---------------------------------------------------------------------------- + /// @brief Pauses the calling thread until the first frame is presented. + /// + /// @param[in] timeout The duration to wait before timing out. If this + /// duration would cause an overflow when added to + /// std::chrono::steady_clock::now(), this method will + /// wait indefinitely for the first frame. + /// + /// @return 'kOk' when the first frame has been presented before the + /// timeout successfully, 'kFailedPrecondition' if called from the + /// GPU or UI thread, 'kDeadlineExceeded' if there is a timeout. + /// + fml::Status WaitForFirstFrame(fml::TimeDelta timeout); + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to reload the system fonts in + /// FontCollection. + /// It also clears the cached font families and send system + /// channel message to framework to rebuild affected widgets. + /// + /// @return Returns if shell reloads system fonts successfully. + /// + bool ReloadSystemFonts(); + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to get the last error from the Dart UI + /// Isolate, if one exists. + /// + /// @return Returns the last error code from the UI Isolate. + /// + std::optional GetUIIsolateLastError() const; + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to check if the Engine is running and has + /// any live ports remaining. For example, the Flutter tester uses + /// this method to check whether it should continue to wait for + /// a running test or not. + /// + /// @return Returns if the shell has an engine and the engine has any live + /// Dart ports. + /// + bool EngineHasLivePorts() const; + + //---------------------------------------------------------------------------- + /// @brief Used by embedders to check if the Engine is running and has + /// any microtasks that have been queued but have not yet run. + /// The Flutter tester uses this as a signal that a test is still + /// running. + /// + /// @return Returns if the shell has an engine and the engine has pending + /// microtasks. + /// + bool EngineHasPendingMicrotasks() const; + + //---------------------------------------------------------------------------- + /// @brief Accessor for the disable GPU SyncSwitch. + // |Rasterizer::Delegate| + std::shared_ptr GetIsGpuDisabledSyncSwitch() + const override; + + //---------------------------------------------------------------------------- + /// @brief Marks the GPU as available or unavailable. + void SetGpuAvailability(GpuAvailability availability); + + //---------------------------------------------------------------------------- + /// @brief Get a pointer to the Dart VM used by this running shell + /// instance. + /// + /// @return The Dart VM pointer. + /// + DartVM* GetDartVM(); + + //---------------------------------------------------------------------------- + /// @brief Notifies the display manager of the updates. + /// + void OnDisplayUpdates(std::vector> displays); + + //---------------------------------------------------------------------------- + /// @brief Queries the `DisplayManager` for the main display refresh rate. + /// + double GetMainDisplayRefreshRate(); + + //---------------------------------------------------------------------------- + /// @brief Install a new factory that can match against and decode image + /// data. + /// @param[in] factory Callback that produces `ImageGenerator`s for + /// compatible input data. + /// @param[in] priority The priority used to determine the order in which + /// factories are tried. Higher values mean higher + /// priority. The built-in Skia decoders are installed + /// at priority 0, and so a priority > 0 takes precedent + /// over the builtin decoders. When multiple decoders + /// are added with the same priority, those which are + /// added earlier take precedent. + /// @see `CreateCompatibleGenerator` + void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority); + + // |Engine::Delegate| + const std::shared_ptr& GetPlatformMessageHandler() + const override; + + const std::weak_ptr GetVsyncWaiter() const; + + const std::shared_ptr + GetConcurrentWorkerTaskRunner() const; + + // Infer the VM ref and the isolate snapshot based on the settings. + // + // If the VM is already running, the settings are ignored, but the returned + // isolate snapshot always prioritize what is specified by the settings, and + // falls back to the one VM was launched with. + // + // This function is what Shell::Create uses to infer snapshot settings. + // + // TODO(dkwingsmt): Extracting this method is part of a bigger change. If the + // entire change is not eventually landed, we should merge this method back + // to Create. https://github.com/flutter/flutter/issues/136826 + static std::pair> + InferVmInitDataFromSettings(Settings& settings); + + private: + using ServiceProtocolHandler = + std::function; + + /// A collection of message channels (by name) that have sent at least one + /// message from a non-platform thread. Used to prevent printing the error + /// log more than once per channel, as a badly behaving plugin may send + /// multiple messages per second indefinitely. + std::mutex misbehaving_message_channels_mutex_; + std::set misbehaving_message_channels_; + const TaskRunners task_runners_; + const fml::RefPtr parent_raster_thread_merger_; + std::shared_ptr + resource_cache_limit_calculator_; + size_t resource_cache_limit_; + const Settings settings_; + DartVMRef vm_; + mutable std::mutex time_recorder_mutex_; + std::optional latest_frame_target_time_; + std::unique_ptr platform_view_; // on platform task runner + std::unique_ptr engine_; // on UI task runner + std::unique_ptr rasterizer_; // on raster task runner + std::shared_ptr io_manager_; // on IO task runner + std::shared_ptr is_gpu_disabled_sync_switch_; + std::shared_ptr platform_message_handler_; + std::atomic route_messages_through_platform_thread_ = false; + + fml::WeakPtr weak_engine_; // to be shared across threads + fml::TaskRunnerAffineWeakPtr + weak_rasterizer_; // to be shared across threads + fml::WeakPtr + weak_platform_view_; // to be shared across threads + + std::unordered_map, + ServiceProtocolHandler> // task-runner/function + // pair + > + service_protocol_handlers_; + bool is_set_up_ = false; + bool is_added_to_service_protocol_ = false; + uint64_t next_pointer_flow_id_ = 0; + + bool first_frame_rasterized_ = false; + std::atomic waiting_for_first_frame_ = true; + std::mutex waiting_for_first_frame_mutex_; + std::condition_variable waiting_for_first_frame_condition_; + + // Written in the UI thread and read from the raster thread. Hence make it + // atomic. + std::atomic needs_report_timings_{false}; + + // Whether there's a task scheduled to report the timings to Dart through + // ui.PlatformDispatcher.onReportTimings. + bool frame_timings_report_scheduled_ = false; + + // Vector of FrameTiming::kCount * n timestamps for n frames whose timings + // have not been reported yet. Vector of ints instead of FrameTiming is + // stored here for easier conversions to Dart objects. + std::vector unreported_timings_; + + /// Manages the displays. This class is thread safe, can be accessed from + /// any of the threads. + std::unique_ptr display_manager_; + + // protects expected_frame_size_ which is set on platform thread and read on + // raster thread + std::mutex resize_mutex_; + + // used to discard wrong size layer tree produced during interactive + // resizing + std::unordered_map expected_frame_sizes_; + + // Used to communicate the right frame bounds via service protocol. + double device_pixel_ratio_ = 0.0; + + // Cached refresh rate used by the performance overlay. + std::optional cached_display_refresh_rate_; + + // How many frames have been timed since last report. + size_t UnreportedFramesCount() const; + + Shell(DartVMRef vm, + const TaskRunners& task_runners, + fml::RefPtr parent_merger, + const std::shared_ptr& + resource_cache_limit_calculator, + const Settings& settings, + bool is_gpu_disabled); + + static std::unique_ptr CreateShellOnPlatformThread( + DartVMRef vm, + fml::RefPtr parent_merger, + std::shared_ptr parent_io_manager, + const std::shared_ptr& + resource_cache_limit_calculator, + const TaskRunners& task_runners, + const PlatformData& platform_data, + const Settings& settings, + fml::RefPtr isolate_snapshot, + const Shell::CreateCallback& on_create_platform_view, + const Shell::CreateCallback& on_create_rasterizer, + const EngineCreateCallback& on_create_engine, + bool is_gpu_disabled); + + static std::unique_ptr CreateWithSnapshot( + const PlatformData& platform_data, + const TaskRunners& task_runners, + const fml::RefPtr& parent_thread_merger, + const std::shared_ptr& parent_io_manager, + const std::shared_ptr& + resource_cache_limit_calculator, + Settings settings, + DartVMRef vm, + fml::RefPtr isolate_snapshot, + const CreateCallback& on_create_platform_view, + const CreateCallback& on_create_rasterizer, + const EngineCreateCallback& on_create_engine, + bool is_gpu_disabled); + + bool Setup(std::unique_ptr platform_view, + std::unique_ptr engine, + std::unique_ptr rasterizer, + const std::shared_ptr& io_manager); + + void ReportTimings(); + + // |PlatformView::Delegate| + void OnPlatformViewCreated(std::unique_ptr surface) override; + + // |PlatformView::Delegate| + void OnPlatformViewDestroyed() override; + + // |PlatformView::Delegate| + void OnPlatformViewScheduleFrame() override; + + // |PlatformView::Delegate| + void OnPlatformViewAddView(int64_t view_id, + const ViewportMetrics& viewport_metrics, + AddViewCallback callback) override; + + // |PlatformView::Delegate| + void OnPlatformViewRemoveView(int64_t view_id, + RemoveViewCallback callback) override; + + // |PlatformView::Delegate| + void OnPlatformViewSendViewFocusEvent(const ViewFocusEvent& event) override; + + // |PlatformView::Delegate| + void OnPlatformViewSetViewportMetrics( + int64_t view_id, + const ViewportMetrics& metrics) override; + + // |PlatformView::Delegate| + void OnPlatformViewDispatchPlatformMessage( + std::unique_ptr message) override; + + // |PlatformView::Delegate| + void OnPlatformViewDispatchPointerDataPacket( + std::unique_ptr packet) override; + + // |PlatformView::Delegate| + void OnPlatformViewDispatchSemanticsAction(int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args) override; + + // |PlatformView::Delegate| + void OnPlatformViewSetSemanticsEnabled(bool enabled) override; + + // |shell:PlatformView::Delegate| + void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override; + + // |PlatformView::Delegate| + void OnPlatformViewRegisterTexture( + std::shared_ptr texture) override; + + // |PlatformView::Delegate| + void OnPlatformViewUnregisterTexture(int64_t texture_id) override; + + // |PlatformView::Delegate| + void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override; + + // |PlatformView::Delegate| + void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override; + + // |PlatformView::Delegate| + const Settings& OnPlatformViewGetSettings() const override; + + // |PlatformView::Delegate| + void LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) override; + + void LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string error_message, + bool transient) override; + + // |PlatformView::Delegate| + void UpdateAssetResolverByType( + std::unique_ptr updated_asset_resolver, + AssetResolver::AssetResolverType type) override; + + // |Animator::Delegate| + void OnAnimatorBeginFrame(fml::TimePoint frame_target_time, + uint64_t frame_number) override; + + // |Animator::Delegate| + void OnAnimatorNotifyIdle(fml::TimeDelta deadline) override; + + // |Animator::Delegate| + void OnAnimatorUpdateLatestFrameTargetTime( + fml::TimePoint frame_target_time) override; + + // |Animator::Delegate| + void OnAnimatorDraw(std::shared_ptr pipeline) override; + + // |Animator::Delegate| + void OnAnimatorDrawLastLayerTrees( + std::unique_ptr frame_timings_recorder) override; + + // |Engine::Delegate| + void OnEngineUpdateSemantics( + int64_t view_id, + SemanticsNodeUpdates update, + CustomAccessibilityActionUpdates actions) override; + + // |Engine::Delegate| + void OnEngineHandlePlatformMessage( + std::unique_ptr message) override; + + void HandleEngineSkiaMessage(std::unique_ptr message); + + // |Engine::Delegate| + void OnPreEngineRestart() override; + + // |Engine::Delegate| + void OnRootIsolateCreated() override; + + // |Engine::Delegate| + void UpdateIsolateDescription(const std::string isolate_name, + int64_t isolate_port) override; + + // |Engine::Delegate| + void SetNeedsReportTimings(bool value) override; + + // |Engine::Delegate| + std::unique_ptr> ComputePlatformResolvedLocale( + const std::vector& supported_locale_data) override; + + // |Engine::Delegate| + void RequestDartDeferredLibrary(intptr_t loading_unit_id) override; + + // |Engine::Delegate| + fml::TimePoint GetCurrentTimePoint() override; + + // |Engine::Delegate| + void OnEngineChannelUpdate(std::string name, bool listening) override; + + // |Engine::Delegate| + double GetScaledFontSize(double unscaled_font_size, + int configuration_id) const override; + + // |Engine::Delegate| + void RequestViewFocusChange(const ViewFocusChangeRequest& request) override; + + // |Rasterizer::Delegate| + void OnFrameRasterized(const FrameTiming&) override; + + // |Rasterizer::Delegate| + fml::Milliseconds GetFrameBudget() override; + + // |Rasterizer::Delegate| + fml::TimePoint GetLatestFrameTargetTime() const override; + + // |Rasterizer::Delegate| + bool ShouldDiscardLayerTree(int64_t view_id, + const flutter::LayerTree& tree) override; + + // |ServiceProtocol::Handler| + fml::RefPtr GetServiceProtocolHandlerTaskRunner( + std::string_view method) const override; + + // |ServiceProtocol::Handler| + bool HandleServiceProtocolMessage( + std::string_view method, // one if the extension names specified above. + const ServiceProtocolMap& params, + rapidjson::Document* response) override; + + // |ServiceProtocol::Handler| + ServiceProtocol::Handler::Description GetServiceProtocolDescription() + const override; + + // Service protocol handler + bool OnServiceProtocolScreenshot( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + // Service protocol handler + bool OnServiceProtocolScreenshotSKP( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + // Service protocol handler + bool OnServiceProtocolRunInView( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + // Service protocol handler + bool OnServiceProtocolFlushUIThreadTasks( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + // Service protocol handler + bool OnServiceProtocolSetAssetBundlePath( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + // Service protocol handler + bool OnServiceProtocolGetDisplayRefreshRate( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + // Service protocol handler + // + // The returned SkSLs are base64 encoded. Decode before storing them to + // files. + bool OnServiceProtocolGetSkSLs( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + // Service protocol handler + bool OnServiceProtocolEstimateRasterCacheMemory( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + // Service protocol handler + // + // Forces the FontCollection to reload the font manifest. Used to support + // hot reload for fonts. + bool OnServiceProtocolReloadAssetFonts( + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + // Send a system font change notification. + void SendFontChangeNotification(); + + // |ResourceCacheLimitItem| + size_t GetResourceCacheLimit() override { return resource_cache_limit_; }; + + // Creates an asset bundle from the original settings asset path or + // directory. + std::unique_ptr RestoreOriginalAssetResolver(); + + SkISize ExpectedFrameSize(int64_t view_id); + + // For accessing the Shell via the raster thread, necessary for various + // rasterizer callbacks. + std::unique_ptr> weak_factory_gpu_; + + fml::WeakPtrFactory weak_factory_; + friend class testing::ShellTest; + + FML_DISALLOW_COPY_AND_ASSIGN(Shell); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SHELL_H_ diff --git a/flutter/engine/src/flutter/shell/common/shell_benchmarks.cc b/flutter/engine/src/flutter/shell/common/shell_benchmarks.cc new file mode 100644 index 0000000000000000000000000000000000000000..a1bba720fe940bdb4428f543028c1bffd4056bfd --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_benchmarks.cc @@ -0,0 +1,123 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/shell.h" + +#include "flutter/benchmarking/benchmarking.h" +#include "flutter/fml/logging.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/testing/elf_loader.h" +#include "flutter/testing/testing.h" + +namespace flutter { + +static void StartupAndShutdownShell(benchmark::State& state, + bool measure_startup, + bool measure_shutdown) { + auto assets_dir = fml::OpenDirectory(testing::GetFixturesPath(), false, + fml::FilePermission::kRead); + std::unique_ptr shell; + std::unique_ptr thread_host; + testing::ELFAOTSymbols aot_symbols; + + { + benchmarking::ScopedPauseTiming pause(state, !measure_startup); + Settings settings = {}; + settings.task_observer_add = [](intptr_t, const fml::closure&) {}; + settings.task_observer_remove = [](intptr_t) {}; + + if (DartVM::IsRunningPrecompiledCode()) { + aot_symbols = testing::LoadELFSymbolFromFixturesIfNeccessary( + testing::kDefaultAOTAppELFFileName); + FML_CHECK( + testing::PrepareSettingsForAOTWithSymbols(settings, aot_symbols)) + << "Could not set up settings with AOT symbols."; + } else { + settings.application_kernels = [&]() { + std::vector> kernel_mappings; + kernel_mappings.emplace_back( + fml::FileMapping::CreateReadOnly(assets_dir, "kernel_blob.bin")); + return kernel_mappings; + }; + } + + thread_host = std::make_unique(ThreadHost::ThreadHostConfig( + "io.flutter.bench.", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + + TaskRunners task_runners("test", + thread_host->platform_thread->GetTaskRunner(), + thread_host->raster_thread->GetTaskRunner(), + thread_host->ui_thread->GetTaskRunner(), + thread_host->io_thread->GetTaskRunner()); + + shell = Shell::Create( + flutter::PlatformData(), task_runners, settings, + [](Shell& shell) { + return std::make_unique(shell, shell.GetTaskRunners()); + }, + [](Shell& shell) { return std::make_unique(shell); }); + } + + FML_CHECK(shell); + + { + // The ui thread could be busy processing tasks after shell created, e.g., + // default font manager setup. The measurement of shell shutdown should be + // considered after those ui tasks have been done. + // + // However, if we're measuring the complete time from startup to shutdown, + // this time should still be included. + benchmarking::ScopedPauseTiming pause( + state, !measure_shutdown || !measure_startup); + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask(thread_host->ui_thread->GetTaskRunner(), + [&latch]() { latch.Signal(); }); + latch.Wait(); + } + + { + benchmarking::ScopedPauseTiming pause(state, !measure_shutdown); + // Shutdown must occur synchronously on the platform thread. + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + thread_host->platform_thread->GetTaskRunner(), + [&shell, &latch]() mutable { + shell.reset(); + latch.Signal(); + }); + latch.Wait(); + thread_host.reset(); + } + + FML_CHECK(!shell); +} + +static void BM_ShellInitialization(benchmark::State& state) { + while (state.KeepRunning()) { + StartupAndShutdownShell(state, true, false); + } +} + +BENCHMARK(BM_ShellInitialization); + +static void BM_ShellShutdown(benchmark::State& state) { + while (state.KeepRunning()) { + StartupAndShutdownShell(state, false, true); + } +} + +BENCHMARK(BM_ShellShutdown); + +static void BM_ShellInitializationAndShutdown(benchmark::State& state) { + while (state.KeepRunning()) { + StartupAndShutdownShell(state, true, true); + } +} + +BENCHMARK(BM_ShellInitializationAndShutdown); + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/shell_fuchsia_unittests.cc b/flutter/engine/src/flutter/shell/common/shell_fuchsia_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..da6bd0f641432f18d83b0b7ab280ca7504ae1637 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_fuchsia_unittests.cc @@ -0,0 +1,267 @@ +// 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. + +// A fuchsia-specific shell test. +// +// This test is only supposed to be ran on Fuchsia OS, as it exercises +// Fuchsia-specific functionality for which no equivalent exists elsewhere. + +#define FML_USED_ON_EMBEDDER + +#include +#include + +#include + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/common/shell_test.h" + +namespace flutter { +namespace testing { + +using fuchsia::intl::TimeZoneId; +using fuchsia::settings::Intl_Set_Result; +using fuchsia::settings::IntlSettings; + +class FuchsiaShellTest : public ShellTest { + protected: + FuchsiaShellTest() + : ctx_(sys::ComponentContext::CreateAndServeOutgoingDirectory()), + intl_() { + ctx_->svc()->Connect(intl_.NewRequest()); + } + + ~FuchsiaShellTest() { + // Restore the time zone that matches that of the test harness. This is + // the default. + // TODO(https://fxbug.dev/110019): This crashes right now. + + // const std::string local_timezone = GetLocalTimezone(); + // SetTimezone(local_timezone); + // AssertTimezone(local_timezone, GetSettings()); + } + + // Gets the international settings from this Fuchsia realm. + IntlSettings GetSettings() { + IntlSettings settings; + zx_status_t status = intl_->Watch(&settings); + EXPECT_EQ(status, ZX_OK); + return settings; + } + + // Sets the timezone of this Fuchsia realm to `timezone_name`. + void SetTimezone(const std::string& timezone_name) { + fuchsia::settings::IntlSettings settings; + settings.set_time_zone_id(TimeZoneId{.id = timezone_name}); + Intl_Set_Result result; + zx_status_t status = intl_->Set(std::move(settings), &result); + ASSERT_EQ(status, ZX_OK); + } + + std::string GetLocalTimezone() { + const time_t timestamp = time(nullptr); + const struct tm* local_time = localtime(×tamp); + EXPECT_NE(local_time, nullptr) + << "Could not get local time: errno=" << errno << ": " + << strerror(errno); + return std::string(local_time->tm_zone); + } + + std::string GetLocalTime() { + const time_t timestamp = time(nullptr); + const struct tm* local_time = localtime(×tamp); + EXPECT_NE(local_time, nullptr) + << "Could not get local time: errno=" << errno << ": " + << strerror(errno); + char buffer[sizeof("2020-08-26 14")]; + const size_t written = + strftime(buffer, sizeof(buffer), "%Y-%m-%d %H", local_time); + EXPECT_LT(0UL, written); + return std::string(buffer); + } + + // Checks that the timezone name in the `settings` matches what is `expected`. + void AssertTimezone(const std::string& expected, + const IntlSettings& settings) { + ASSERT_EQ(expected, settings.time_zone_id().id); + } + + std::unique_ptr ctx_; + fuchsia::settings::IntlSyncPtr intl_; + + fuchsia::settings::IntlSettings save_settings_; +}; + +// These functions are used by tests that are currently disabled. +#if false +static bool ValidateShell(Shell* shell) { + if (!shell) { + return false; + } + + if (!shell->IsSetup()) { + return false; + } + + ShellTest::PlatformViewNotifyCreated(shell); + + { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), [shell, &latch]() { + shell->GetPlatformView()->NotifyDestroyed(); + latch.Signal(); + }); + latch.Wait(); + } + + return true; +} + +// Runs the function `f` in lock-step with a Dart isolate until the function +// returns `true`, or until a certain fixed number of retries is exhausted. +// Events `tick` and `tock` are used to synchronize the lock-stepping. The +// event 'tick' is a signal to the dart isolate to advance a single iteration +// step. 'tock' is used by the dart isolate to signal that it has completed +// its step. +static void RunCoroutineWithRetry(int retries, + fml::AutoResetWaitableEvent* tick, + fml::AutoResetWaitableEvent* tock, + std::function f) { + for (; retries > 0; retries--) { + // Do a single coroutine step. + tick->Signal(); + tock->Wait(); + if (f()) { + break; + } + FML_LOG(INFO) << "Retries left: " << retries; + sleep(1); + } +} +#endif // false + +// Verifies that changing the Fuchsia settings timezone through the FIDL +// settings interface results in a change of the reported local time in the +// isolate. +// +// The test is as follows: +// +// - Set an initial timezone, then get a timestamp from the isolate rounded down +// to the nearest hour. The assumption is as long as this test doesn't run +// very near the whole hour, which should be very unlikely, the nearest hour +// will vary depending on the time zone. +// - Set a different timezone. Get a timestamp from the isolate again and +// confirm that this time around the timestamps are different. +// - Set the initial timezone again, and get the timestamp. This time, the +// timestamp rounded down to whole hour should match the timestamp we got +// in the initial step. +TEST_F(FuchsiaShellTest, LocaltimesVaryOnTimezoneChanges) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() + << "This test fails after the CF V2 migration. https://fxbug.dev/110019 "; +#else + + // See fixtures/shell_test.dart, the callback NotifyLocalTime is declared + // there. + fml::AutoResetWaitableEvent latch; + std::string dart_isolate_time_str; + AddNativeCallback("NotifyLocalTime", CREATE_NATIVE_ENTRY([&](auto args) { + dart_isolate_time_str = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + latch.Signal(); + })); + + // As long as this is set, the isolate will keep rerunning its only task. + bool continue_fixture = true; + fml::AutoResetWaitableEvent fixture_latch; + AddNativeCallback("WaitFixture", CREATE_NATIVE_ENTRY([&](auto args) { + // Wait for the test fixture to advance. + fixture_latch.Wait(); + tonic::DartConverter::SetReturnValue( + args, continue_fixture); + })); + + auto settings = CreateSettingsForFixture(); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("timezonesChange"); + + std::unique_ptr shell = CreateShell(settings); + ASSERT_NE(shell.get(), nullptr); + ASSERT_TRUE(ValidateShell(shell.get())); + RunEngine(shell.get(), std::move(configuration)); + latch.Wait(); // After this point, the fixture is at waitFixture(). + + // Start with the local timezone, ensure that the isolate and the test + // fixture are the same. + SetTimezone(GetLocalTimezone()); + AssertTimezone(GetLocalTimezone(), GetSettings()); + std::string expected = GetLocalTime(); + std::string actual = "undefined"; + RunCoroutineWithRetry(10, &fixture_latch, &latch, [&]() { + actual = dart_isolate_time_str; + FML_LOG(INFO) << "reference: " << expected << ", actual: " << actual; + return expected == actual; + }); + ASSERT_EQ(expected, actual) + << "The Dart isolate was expected to show the same time as the test " + << "fixture eventually, but that didn't happen after multiple retries."; + + // Set a new timezone, which is hopefully different from the local one. + SetTimezone("America/New_York"); + AssertTimezone("America/New_York", GetSettings()); + RunCoroutineWithRetry(10, &fixture_latch, &latch, [&]() { + actual = dart_isolate_time_str; + FML_LOG(INFO) << "reference: " << expected << ", actual: " << actual; + return expected != actual; + }); + ASSERT_NE(expected, actual) + << "The Dart isolate was expected to show a time different from the test " + << "fixture eventually, but that didn't happen after multiple retries."; + + // Set a new isolate timezone, and check that the reported time is eventually + // different from what it used to be prior to the change. + SetTimezone("Europe/Amsterdam"); + AssertTimezone("Europe/Amsterdam", GetSettings()); + RunCoroutineWithRetry(10, &fixture_latch, &latch, [&]() { + actual = dart_isolate_time_str; + FML_LOG(INFO) << "reference: " << expected << ", actual: " << actual; + return expected != actual; + }); + ASSERT_NE(expected, actual) + << "The Dart isolate was expected to show a time different from the " + << "prior timezone eventually, but that didn't happen after multiple " + << "retries."; + + // Let's try to bring the timezone back to the old one. + expected = actual; + SetTimezone("America/New_York"); + AssertTimezone("America/New_York", GetSettings()); + RunCoroutineWithRetry(10, &fixture_latch, &latch, [&]() { + actual = dart_isolate_time_str; + FML_LOG(INFO) << "reference: " << expected << ", actual: " << actual; + return expected != actual; + }); + ASSERT_NE(expected, actual) + << "The Dart isolate was expected to show a time different from the " + << "prior timezone eventually, but that didn't happen after multiple " + << "retries."; + + // Tell the isolate to exit its loop. + ASSERT_FALSE(fixture_latch.IsSignaledForTest()); + continue_fixture = false; + fixture_latch.Signal(); + DestroyShell(std::move(shell)); +#endif // OS_FUCHSIA +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/shell_io_manager.cc b/flutter/engine/src/flutter/shell/common/shell_io_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..4c842996dc8b3ed7d412d4cceef1d3fbbede8437 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_io_manager.cc @@ -0,0 +1,127 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/shell_io_manager.h" + +#include + +#include "flutter/fml/message_loop.h" +#include "flutter/shell/common/context_options.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLInterface.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLTypes.h" + +namespace flutter { + +sk_sp ShellIOManager::CreateCompatibleResourceLoadingContext( + GrBackendApi backend, + const sk_sp& gl_interface) { +#if SK_GL + if (backend != GrBackendApi::kOpenGL) { + return nullptr; + } + + const auto options = MakeDefaultContextOptions(ContextType::kResource); + + if (auto context = GrDirectContexts::MakeGL(gl_interface, options)) { + // Do not cache textures created by the image decoder. These textures + // should be deleted when they are no longer referenced by an SkImage. + context->setResourceCacheLimit(0); + return context; + } +#endif // SK_GL + + return nullptr; +} + +ShellIOManager::ShellIOManager( + sk_sp resource_context, + std::shared_ptr is_gpu_disabled_sync_switch, + fml::RefPtr unref_queue_task_runner, + std::shared_ptr impeller_context, + fml::TimeDelta unref_queue_drain_delay) + : resource_context_(std::move(resource_context)), + resource_context_weak_factory_( + resource_context_ + ? std::make_unique>( + resource_context_.get()) + : nullptr), + unref_queue_(fml::MakeRefCounted( + std::move(unref_queue_task_runner), + unref_queue_drain_delay, + resource_context_, + /*drain_immediate=*/!!impeller_context)), + is_gpu_disabled_sync_switch_(std::move(is_gpu_disabled_sync_switch)), + impeller_context_(std::move(impeller_context)), + weak_factory_(this) { + if (!resource_context_) { +#ifndef OS_FUCHSIA + FML_DLOG(WARNING) << "The IO manager was initialized without a resource " + "context. Async texture uploads will be disabled. " + "Expect performance degradation."; +#endif // OS_FUCHSIA + } +} + +ShellIOManager::~ShellIOManager() { + // Last chance to drain the IO queue as the platform side reference to the + // underlying OpenGL context may be going away. + is_gpu_disabled_sync_switch_->Execute( + fml::SyncSwitch::Handlers().SetIfFalse([&] { unref_queue_->Drain(); })); +} + +void ShellIOManager::NotifyResourceContextAvailable( + sk_sp resource_context) { + // The resource context needs to survive as long as we have Dart objects + // referencing. We shouldn't ever need to replace it if we have one - unless + // we've somehow shut down the Dart VM and started a new one fresh. + if (!resource_context_) { + UpdateResourceContext(std::move(resource_context)); + } +} + +void ShellIOManager::UpdateResourceContext( + sk_sp resource_context) { + resource_context_ = std::move(resource_context); + resource_context_weak_factory_ = + resource_context_ + ? std::make_unique>( + resource_context_.get()) + : nullptr; + unref_queue_->UpdateResourceContext(resource_context_); +} + +fml::WeakPtr ShellIOManager::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +} + +// |IOManager| +fml::WeakPtr ShellIOManager::GetResourceContext() const { + return resource_context_weak_factory_ + ? resource_context_weak_factory_->GetWeakPtr() + : fml::WeakPtr(); +} + +// |IOManager| +fml::RefPtr ShellIOManager::GetSkiaUnrefQueue() const { + return unref_queue_; +} + +// |IOManager| +fml::WeakPtr ShellIOManager::GetWeakIOManager() const { + return weak_factory_.GetWeakPtr(); +} + +// |IOManager| +std::shared_ptr +ShellIOManager::GetIsGpuDisabledSyncSwitch() { + return is_gpu_disabled_sync_switch_; +} + +// |IOManager| +std::shared_ptr ShellIOManager::GetImpellerContext() const { + return impeller_context_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/shell_io_manager.h b/flutter/engine/src/flutter/shell/common/shell_io_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..9096c1b17b6b5aef271fa3c44ce92a300bd8e6d4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_io_manager.h @@ -0,0 +1,84 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_SHELL_IO_MANAGER_H_ +#define FLUTTER_SHELL_COMMON_SHELL_IO_MANAGER_H_ + +#include + +#include "flutter/flow/skia_gpu_object.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/lib/ui/io_manager.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/GrTypes.h" + +struct GrGLInterface; + +namespace flutter { + +class ShellIOManager final : public IOManager { + public: + // Convenience methods for platforms to create a GrDirectContext used to + // supply to the IOManager. The platforms may create the context themselves if + // they so desire. + static sk_sp CreateCompatibleResourceLoadingContext( + GrBackendApi backend, + const sk_sp& gl_interface); + + ShellIOManager( + sk_sp resource_context, + std::shared_ptr is_gpu_disabled_sync_switch, + fml::RefPtr unref_queue_task_runner, + std::shared_ptr impeller_context, + fml::TimeDelta unref_queue_drain_delay = + fml::TimeDelta::FromMilliseconds(8)); + + ~ShellIOManager() override; + + // This method should be called when a resource_context first becomes + // available. It is safe to call multiple times, and will only update + // the held resource context if it has not already been set. + void NotifyResourceContextAvailable(sk_sp resource_context); + + // This method should be called if you want to force the IOManager to + // update its resource context reference. It should not be called + // if there are any Dart objects that have a reference to the old + // resource context, but may be called if the Dart VM is restarted. + void UpdateResourceContext(sk_sp resource_context); + + fml::WeakPtr GetWeakPtr(); + + // |IOManager| + fml::WeakPtr GetWeakIOManager() const override; + + // |IOManager| + fml::WeakPtr GetResourceContext() const override; + + // |IOManager| + fml::RefPtr GetSkiaUnrefQueue() const override; + + // |IOManager| + std::shared_ptr GetIsGpuDisabledSyncSwitch() override; + + // |IOManager| + std::shared_ptr GetImpellerContext() const override; + + private: + // Resource context management. + sk_sp resource_context_; + std::unique_ptr> + resource_context_weak_factory_; + // Unref queue management. + fml::RefPtr unref_queue_; + std::shared_ptr is_gpu_disabled_sync_switch_; + std::shared_ptr impeller_context_; + fml::WeakPtrFactory weak_factory_; + + FML_DISALLOW_COPY_AND_ASSIGN(ShellIOManager); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SHELL_IO_MANAGER_H_ diff --git a/flutter/engine/src/flutter/shell/common/shell_io_manager_unittests.cc b/flutter/engine/src/flutter/shell/common/shell_io_manager_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..e262fd7d7840e9c2c67fb87784dc79f5b20519a3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_io_manager_unittests.cc @@ -0,0 +1,106 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/shell_io_manager.h" + +#include "flutter/common/task_runners.h" +#include "flutter/fml/mapping.h" +#include "flutter/lib/ui/painting/multi_frame_codec.h" +#include "flutter/testing/dart_isolate_runner.h" +#include "flutter/testing/fixture_test.h" +#include "flutter/testing/post_task_sync.h" +#include "flutter/testing/test_gl_surface.h" // nogncheck +#include "flutter/testing/testing.h" + +namespace flutter { +namespace testing { + +class ShellIOManagerTest : public FixtureTest {}; + +// Regression test for https://github.com/flutter/engine/pull/32106. +TEST_F(ShellIOManagerTest, + ItDoesNotCrashThatSkiaUnrefQueueDrainAfterIOManagerReset) { + auto settings = CreateSettingsForFixture(); + auto vm_ref = DartVMRef::Create(settings); + auto vm_data = vm_ref.GetVMData(); + auto gif_mapping = flutter::testing::OpenFixtureAsSkData("hello_loop_2.gif"); + ASSERT_TRUE(gif_mapping); + + ImageGeneratorRegistry registry; + std::shared_ptr gif_generator = + registry.CreateCompatibleGenerator(gif_mapping); + ASSERT_TRUE(gif_generator); + + TaskRunners runners(GetCurrentTestName(), // label + CreateNewThread("platform"), // platform + CreateNewThread("raster"), // raster + CreateNewThread("ui"), // ui + CreateNewThread("io") // io + ); + + std::unique_ptr gl_surface; + std::unique_ptr io_manager; + fml::RefPtr codec; + + // Setup the IO manager. + PostTaskSync(runners.GetIOTaskRunner(), [&]() { + gl_surface = std::make_unique(SkISize::Make(1, 1)); + io_manager = std::make_unique( + gl_surface->CreateGrContext(), std::make_shared(), + runners.GetIOTaskRunner(), nullptr, + fml::TimeDelta::FromMilliseconds(0)); + }); + + auto isolate = RunDartCodeInIsolate(vm_ref, settings, runners, "emptyMain", + {}, GetDefaultKernelFilePath(), + io_manager->GetWeakIOManager()); + + PostTaskSync(runners.GetUITaskRunner(), [&]() { + fml::AutoResetWaitableEvent isolate_latch; + + EXPECT_TRUE(isolate->RunInIsolateScope([&]() -> bool { + Dart_Handle library = Dart_RootLibrary(); + if (Dart_IsError(library)) { + isolate_latch.Signal(); + return false; + } + Dart_Handle closure = + Dart_GetField(library, Dart_NewStringFromCString("frameCallback")); + if (Dart_IsError(closure) || !Dart_IsClosure(closure)) { + isolate_latch.Signal(); + return false; + } + + codec = fml::MakeRefCounted(std::move(gif_generator)); + codec->getNextFrame(closure); + isolate_latch.Signal(); + return true; + })); + isolate_latch.Wait(); + }); + + // Destroy the IO manager + PostTaskSync(runners.GetIOTaskRunner(), [&]() { + // 'SkiaUnrefQueue.Drain' will be called after 'io_manager.reset()' in this + // test, If the resource context has been destroyed at that time, it will + // crash. + // + // 'Drain()' currently checks whether the weak pointer is still valid or not + // before trying to call anything on it. + // + // However, calling 'unref' on the 'SkImage_Lazy' ends up freeing a + // 'GrBackendTexture'. That object seems to assume that something else is + // keeping the context alive. This seems like it might be a bad assumption + // on Skia's part, but in Skia's defense we're doing something pretty weird + // here by keeping GPU resident objects alive without keeping the + // 'GrDirectContext' alive ourselves. + // + // See https://github.com/flutter/flutter/issues/87895 + io_manager.reset(); + gl_surface.reset(); + }); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/shell_test.cc b/flutter/engine/src/flutter/shell/common/shell_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..7dc7f80369cf7c2db7856821d896ac71ecfc6173 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test.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. + +#define FML_USED_ON_EMBEDDER + +#include "flutter/shell/common/shell_test.h" + +#include "flutter/flow/frame_timings.h" +#include "flutter/flow/layers/layer_tree.h" +#include "flutter/flow/layers/transform_layer.h" +#include "flutter/fml/build_config.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/mapping.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/common/shell_test_platform_view.h" +#include "flutter/shell/common/vsync_waiter_fallback.h" +#include "flutter/testing/testing.h" + +namespace flutter { +namespace testing { + +constexpr int64_t kImplicitViewId = 0; + +FrameContent ViewContent::NoViews() { + return std::map(); +} + +FrameContent ViewContent::DummyView(double width, double height) { + FrameContent result; + result[kImplicitViewId] = ViewContent{ + .viewport_metrics = {1.0, width, height, 22, 0}, + .builder = {}, + }; + return result; +} + +FrameContent ViewContent::DummyView(flutter::ViewportMetrics viewport_metrics) { + FrameContent result; + result[kImplicitViewId] = ViewContent{ + .viewport_metrics = std::move(viewport_metrics), + .builder = {}, + }; + return result; +} + +FrameContent ViewContent::ImplicitView(double width, + double height, + LayerTreeBuilder builder) { + FrameContent result; + result[kImplicitViewId] = ViewContent{ + .viewport_metrics = {1.0, width, height, 22, 0}, + .builder = std::move(builder), + }; + return result; +} + +ShellTest::ShellTest() + : thread_host_("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kIo | + ThreadHost::Type::kUi | ThreadHost::Type::kRaster) {} + +void ShellTest::SendPlatformMessage(Shell* shell, + std::unique_ptr message) { + shell->OnPlatformViewDispatchPlatformMessage(std::move(message)); +} + +void ShellTest::SendSemanticsAction(Shell* shell, + int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args) { + shell->OnPlatformViewDispatchSemanticsAction(view_id, node_id, action, + std::move(args)); +} + +void ShellTest::SendEnginePlatformMessage( + Shell* shell, + std::unique_ptr message) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), + fml::MakeCopyable( + [shell, &latch, message = std::move(message)]() mutable { + if (auto engine = shell->weak_engine_) { + engine->HandlePlatformMessage(std::move(message)); + } + latch.Signal(); + })); + latch.Wait(); +} + +void ShellTest::PlatformViewNotifyCreated(Shell* shell) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), [shell, &latch]() { + shell->GetPlatformView()->NotifyCreated(); + latch.Signal(); + }); + latch.Wait(); +} + +void ShellTest::PlatformViewNotifyDestroyed(Shell* shell) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), [shell, &latch]() { + shell->GetPlatformView()->NotifyDestroyed(); + latch.Signal(); + }); + latch.Wait(); +} + +void ShellTest::RunEngine(Shell* shell, RunConfiguration configuration) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [shell, &latch, &configuration]() { + shell->RunEngine(std::move(configuration), + [&latch](Engine::RunStatus run_status) { + ASSERT_EQ(run_status, Engine::RunStatus::Success); + latch.Signal(); + }); + }); + latch.Wait(); +} + +void ShellTest::RestartEngine(Shell* shell, RunConfiguration configuration) { + std::promise restarted; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetUITaskRunner(), + [shell, &restarted, &configuration]() { + restarted.set_value(shell->engine_->Restart(std::move(configuration))); + }); + ASSERT_TRUE(restarted.get_future().get()); +} + +void ShellTest::VSyncFlush(Shell* shell, bool* will_draw_new_frame) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [shell, will_draw_new_frame, &latch] { + // The following UI task ensures that all previous UI tasks are flushed. + fml::AutoResetWaitableEvent ui_latch; + shell->GetTaskRunners().GetUITaskRunner()->PostTask( + [&ui_latch, will_draw_new_frame]() { + if (will_draw_new_frame != nullptr) { + *will_draw_new_frame = true; + } + ui_latch.Signal(); + }); + + ShellTestPlatformView* test_platform_view = + static_cast(shell->GetPlatformView().get()); + do { + test_platform_view->SimulateVSync(); + } while (ui_latch.WaitWithTimeout(fml::TimeDelta::FromMilliseconds(1))); + + latch.Signal(); + }); + latch.Wait(); +} + +void ShellTest::SetViewportMetrics(Shell* shell, double width, double height) { + flutter::ViewportMetrics viewport_metrics = { + 1, // device pixel ratio + width, // physical width + height, // physical height + 0, // padding top + 0, // padding right + 0, // padding bottom + 0, // padding left + 0, // view inset top + 0, // view inset right + 0, // view inset bottom + 0, // view inset left + 0, // gesture inset top + 0, // gesture inset right + 0, // gesture inset bottom + 0, // gesture inset left + 22, // physical touch slop + std::vector(), // display features bounds + std::vector(), // display features type + std::vector(), // display features state + 0 // Display ID + }; + // Set viewport to nonempty, and call Animator::BeginFrame to make the layer + // tree pipeline nonempty. Without either of this, the layer tree below + // won't be rasterized. + fml::AutoResetWaitableEvent latch; + shell->GetTaskRunners().GetUITaskRunner()->PostTask( + [&latch, engine = shell->weak_engine_, viewport_metrics]() { + if (engine) { + engine->SetViewportMetrics(kImplicitViewId, viewport_metrics); + const auto frame_begin_time = fml::TimePoint::Now(); + const auto frame_end_time = + frame_begin_time + fml::TimeDelta::FromSecondsF(1.0 / 60.0); + std::unique_ptr recorder = + std::make_unique(); + recorder->RecordVsync(frame_begin_time, frame_end_time); + engine->animator_->BeginFrame(std::move(recorder)); + engine->animator_->EndFrame(); + } + latch.Signal(); + }); + latch.Wait(); +} + +void ShellTest::NotifyIdle(Shell* shell, fml::TimeDelta deadline) { + fml::AutoResetWaitableEvent latch; + shell->GetTaskRunners().GetUITaskRunner()->PostTask( + [&latch, engine = shell->weak_engine_, deadline]() { + if (engine) { + engine->NotifyIdle(deadline); + } + latch.Signal(); + }); + latch.Wait(); +} + +void ShellTest::PumpOneFrame(Shell* shell) { + PumpOneFrame(shell, ViewContent::DummyView()); +} + +void ShellTest::PumpOneFrame(Shell* shell, FrameContent frame_content) { + // Set viewport to nonempty, and call Animator::BeginFrame to make the layer + // tree pipeline nonempty. Without either of this, the layer tree below + // won't be rasterized. + fml::AutoResetWaitableEvent latch; + fml::WeakPtr runtime_delegate = shell->weak_engine_; + shell->GetTaskRunners().GetUITaskRunner()->PostTask( + [&latch, engine = shell->weak_engine_, &frame_content, + runtime_delegate]() { + for (auto& [view_id, view_content] : frame_content) { + engine->SetViewportMetrics(view_id, view_content.viewport_metrics); + } + const auto frame_begin_time = fml::TimePoint::Now(); + const auto frame_end_time = + frame_begin_time + fml::TimeDelta::FromSecondsF(1.0 / 60.0); + std::unique_ptr recorder = + std::make_unique(); + recorder->RecordVsync(frame_begin_time, frame_end_time); + engine->animator_->BeginFrame(std::move(recorder)); + + // The BeginFrame phase and the EndFrame phase must be performed in a + // single task, otherwise a normal vsync might be inserted in between, + // causing flaky assertion errors. + + for (auto& [view_id, view_content] : frame_content) { + auto root_layer = std::make_shared(DlMatrix()); + auto layer_tree = std::make_unique( + root_layer, + DlISize(view_content.viewport_metrics.physical_width, + view_content.viewport_metrics.physical_height)); + float device_pixel_ratio = static_cast( + view_content.viewport_metrics.device_pixel_ratio); + if (view_content.builder) { + view_content.builder(root_layer); + } + runtime_delegate->Render(view_id, std::move(layer_tree), + device_pixel_ratio); + } + engine->animator_->EndFrame(); + latch.Signal(); + }); + latch.Wait(); +} + +void ShellTest::DispatchFakePointerData(Shell* shell, double x) { + auto packet = std::make_unique(1); + packet->SetPointerData(0, PointerData{ + .change = PointerData::Change::kHover, + .physical_x = x, + }); + DispatchPointerData(shell, std::move(packet)); +} + +void ShellTest::DispatchPointerData(Shell* shell, + std::unique_ptr packet) { + fml::AutoResetWaitableEvent latch; + shell->GetTaskRunners().GetPlatformTaskRunner()->PostTask( + [&latch, shell, &packet]() { + // Goes through PlatformView to ensure packet is corrected converted. + shell->GetPlatformView()->DispatchPointerDataPacket(std::move(packet)); + latch.Signal(); + }); + latch.Wait(); +} + +int ShellTest::UnreportedTimingsCount(Shell* shell) { + return shell->unreported_timings_.size(); +} + +void ShellTest::SetNeedsReportTimings(Shell* shell, bool value) { + shell->SetNeedsReportTimings(value); +} + +bool ShellTest::GetNeedsReportTimings(Shell* shell) { + return shell->needs_report_timings_; +} + +void ShellTest::StorePersistentCache(PersistentCache* cache, + const SkData& key, + const SkData& value) { + cache->store(key, value); +} + +void ShellTest::OnServiceProtocol( + Shell* shell, + ServiceProtocolEnum some_protocol, + const fml::RefPtr& task_runner, + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response) { + std::promise finished; + fml::TaskRunner::RunNowOrPostTask( + task_runner, [shell, some_protocol, params, response, &finished]() { + switch (some_protocol) { + case ServiceProtocolEnum::kGetSkSLs: + shell->OnServiceProtocolGetSkSLs(params, response); + break; + case ServiceProtocolEnum::kEstimateRasterCacheMemory: + shell->OnServiceProtocolEstimateRasterCacheMemory(params, response); + break; + case ServiceProtocolEnum::kSetAssetBundlePath: + shell->OnServiceProtocolSetAssetBundlePath(params, response); + break; + case ServiceProtocolEnum::kRunInView: + shell->OnServiceProtocolRunInView(params, response); + break; + } + finished.set_value(true); + }); + finished.get_future().wait(); +} + +std::shared_ptr ShellTest::GetFontCollection( + Shell* shell) { + return shell->weak_engine_->GetFontCollection().GetFontCollection(); +} + +Settings ShellTest::CreateSettingsForFixture() { + Settings settings; + settings.leak_vm = false; + settings.task_observer_add = [](intptr_t key, const fml::closure& handler) { + fml::MessageLoop::GetCurrent().AddTaskObserver(key, handler); + }; + settings.task_observer_remove = [](intptr_t key) { + fml::MessageLoop::GetCurrent().RemoveTaskObserver(key); + }; + settings.isolate_create_callback = [this]() { + native_resolver_->SetNativeResolverForIsolate(); + }; +#if OS_FUCHSIA + settings.verbose_logging = true; +#endif + SetSnapshotsAndAssets(settings); + return settings; +} + +TaskRunners ShellTest::GetTaskRunnersForFixture() { + return { + "test", + thread_host_.platform_thread->GetTaskRunner(), // platform + thread_host_.raster_thread->GetTaskRunner(), // raster + thread_host_.ui_thread->GetTaskRunner(), // ui + thread_host_.io_thread->GetTaskRunner() // io + }; +} + +fml::TimePoint ShellTest::GetLatestFrameTargetTime(Shell* shell) const { + return shell->GetLatestFrameTargetTime(); +} + +std::unique_ptr ShellTest::CreateShell( + const Settings& settings, + std::optional task_runners) { + return CreateShell({ + .settings = settings, + .task_runners = std::move(task_runners), + }); +} + +std::unique_ptr ShellTest::CreateShell(const Config& config) { + TaskRunners task_runners = config.task_runners.has_value() + ? config.task_runners.value() + : GetTaskRunnersForFixture(); + Shell::CreateCallback platform_view_create_callback = + config.platform_view_create_callback; + if (!platform_view_create_callback) { + platform_view_create_callback = ShellTestPlatformViewBuilder({}); + } + + Shell::CreateCallback rasterizer_create_callback = + [](Shell& shell) { return std::make_unique(shell); }; + + return Shell::Create(flutter::PlatformData(), // + task_runners, // + config.settings, // + platform_view_create_callback, // + rasterizer_create_callback, // + config.is_gpu_disabled // + ); +} + +void ShellTest::DestroyShell(std::unique_ptr shell) { + DestroyShell(std::move(shell), GetTaskRunnersForFixture()); +} + +void ShellTest::DestroyShell(std::unique_ptr shell, + const TaskRunners& task_runners) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask(task_runners.GetPlatformTaskRunner(), + [&shell, &latch]() mutable { + shell.reset(); + latch.Signal(); + }); + latch.Wait(); +} + +void ShellTest::TurnOffGPU(Shell* shell, bool value) { + shell->is_gpu_disabled_sync_switch_->SetSwitch(value); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/shell_test.h b/flutter/engine/src/flutter/shell/common/shell_test.h new file mode 100644 index 0000000000000000000000000000000000000000..0fd729f5a677be4dbdd4aca97ff6e00f9f4cc013 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test.h @@ -0,0 +1,175 @@ +// 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_COMMON_SHELL_TEST_H_ +#define FLUTTER_SHELL_COMMON_SHELL_TEST_H_ + +#include "flutter/shell/common/shell.h" + +#include + +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/common/settings.h" +#include "flutter/flow/layers/container_layer.h" +#include "flutter/fml/build_config.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/shell/common/run_configuration.h" +#include "flutter/shell/common/shell_test_external_view_embedder.h" +#include "flutter/shell/common/shell_test_platform_view.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/shell/common/vsync_waiters_test.h" +#include "flutter/testing/elf_loader.h" +#include "flutter/testing/fixture_test.h" +#include "flutter/testing/test_dart_native_resolver.h" + +namespace flutter { +namespace testing { + +// The signature of ViewContent::builder. +using LayerTreeBuilder = + std::function root)>; +struct ViewContent; +// Defines the content to be rendered to all views of a frame in PumpOneFrame. +using FrameContent = std::map; +// Defines the content to be rendered to a view in PumpOneFrame. +struct ViewContent { + flutter::ViewportMetrics viewport_metrics; + // Given the root layer, this callback builds the layer tree to be rasterized + // in PumpOneFrame. + LayerTreeBuilder builder; + + // Build a frame with no views. This is useful when PumpOneFrame is used just + // to schedule the frame while the frame content is defined by other means. + static FrameContent NoViews(); + + // Build a frame with a single implicit view with the specific size and no + // content. + static FrameContent DummyView(double width = 1, double height = 1); + + // Build a frame with a single implicit view with the specific viewport + // metrics and no content. + static FrameContent DummyView(flutter::ViewportMetrics viewport_metrics); + + // Build a frame with a single implicit view with the specific size and + // content. + static FrameContent ImplicitView(double width, + double height, + LayerTreeBuilder builder); +}; + +class ShellTest : public FixtureTest { + public: + struct Config { + // Required. + const Settings& settings; + // Defaults to GetTaskRunnersForFixture(). + std::optional task_runners = {}; + bool is_gpu_disabled = false; + // Defaults to calling ShellTestPlatformView::Create with the provided + // arguments. + Shell::CreateCallback platform_view_create_callback; + std::optional engine_id; + }; + + ShellTest(); + + Settings CreateSettingsForFixture() override; + std::unique_ptr CreateShell( + const Settings& settings, + std::optional task_runners = {}); + std::unique_ptr CreateShell(const Config& config); + void DestroyShell(std::unique_ptr shell); + void DestroyShell(std::unique_ptr shell, + const TaskRunners& task_runners); + TaskRunners GetTaskRunnersForFixture(); + + fml::TimePoint GetLatestFrameTargetTime(Shell* shell) const; + + void SendPlatformMessage(Shell* shell, + std::unique_ptr message); + + void SendSemanticsAction(Shell* shell, + int64_t view_id, + int32_t node_id, + SemanticsAction action, + fml::MallocMapping args); + + void SendEnginePlatformMessage(Shell* shell, + std::unique_ptr message); + + static void PlatformViewNotifyCreated( + Shell* shell); // This creates the surface + static void PlatformViewNotifyDestroyed( + Shell* shell); // This destroys the surface + static void RunEngine(Shell* shell, RunConfiguration configuration); + static void RestartEngine(Shell* shell, RunConfiguration configuration); + + /// Issue as many VSYNC as needed to flush the UI tasks so far, and reset + /// the content of `will_draw_new_frame` to true if it's not nullptr. + static void VSyncFlush(Shell* shell, bool* will_draw_new_frame = nullptr); + + static void SetViewportMetrics(Shell* shell, double width, double height); + static void NotifyIdle(Shell* shell, fml::TimeDelta deadline); + + static void PumpOneFrame(Shell* shell); + static void PumpOneFrame(Shell* shell, FrameContent frame_content); + // Dispatch a PointerHoverEvent with the specified `x` as the pointer + // position. + static void DispatchFakePointerData(Shell* shell, double x); + static void DispatchPointerData(Shell* shell, + std::unique_ptr packet); + // Declare |UnreportedTimingsCount|, |GetNeedsReportTimings| and + // |SetNeedsReportTimings| inside |ShellTest| mainly for easier friend class + // declarations as shell unit tests and Shell are in different name spaces. + + static bool GetNeedsReportTimings(Shell* shell); + static void SetNeedsReportTimings(Shell* shell, bool value); + + // Declare |StorePersistentCache| inside |ShellTest| so |PersistentCache| can + // friend |ShellTest| and allow us to call private |PersistentCache::store| in + // unit tests. + static void StorePersistentCache(PersistentCache* cache, + const SkData& key, + const SkData& value); + + static bool IsAnimatorRunning(Shell* shell); + + enum ServiceProtocolEnum { + kGetSkSLs, + kEstimateRasterCacheMemory, + kSetAssetBundlePath, + kRunInView, + }; + + // Helper method to test private method Shell::OnServiceProtocolGetSkSLs. + // (ShellTest is a friend class of Shell.) We'll also make sure that it is + // running on the correct task_runner. + static void OnServiceProtocol( + Shell* shell, + ServiceProtocolEnum some_protocol, + const fml::RefPtr& task_runner, + const ServiceProtocol::Handler::ServiceProtocolMap& params, + rapidjson::Document* response); + + std::shared_ptr GetFontCollection(Shell* shell); + + // Do not assert |UnreportedTimingsCount| to be positive in any tests. + // Otherwise those tests will be flaky as the clearing of unreported timings + // is unpredictive. + static int UnreportedTimingsCount(Shell* shell); + + static void TurnOffGPU(Shell* shell, bool value); + + private: + ThreadHost thread_host_; + + FML_DISALLOW_COPY_AND_ASSIGN(ShellTest); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SHELL_TEST_H_ diff --git a/flutter/engine/src/flutter/shell/common/shell_test_external_view_embedder.cc b/flutter/engine/src/flutter/shell/common/shell_test_external_view_embedder.cc new file mode 100644 index 0000000000000000000000000000000000000000..7e0d3b4c410a0ce0698a2a16897f657b10ae920f --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_external_view_embedder.cc @@ -0,0 +1,129 @@ +// 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 "shell_test_external_view_embedder.h" + +namespace flutter { + +ShellTestExternalViewEmbedder::ShellTestExternalViewEmbedder( + const EndFrameCallBack& end_frame_call_back, + PostPrerollResult post_preroll_result, + bool support_thread_merging) + : end_frame_call_back_(end_frame_call_back), + post_preroll_result_(post_preroll_result), + support_thread_merging_(support_thread_merging), + submitted_frame_count_(0) {} + +void ShellTestExternalViewEmbedder::UpdatePostPrerollResult( + PostPrerollResult post_preroll_result) { + post_preroll_result_ = post_preroll_result; +} + +int ShellTestExternalViewEmbedder::GetSubmittedFrameCount() { + return submitted_frame_count_; +} + +SkISize ShellTestExternalViewEmbedder::GetLastSubmittedFrameSize() { + return last_submitted_frame_size_; +} + +std::vector ShellTestExternalViewEmbedder::GetVisitedPlatformViews() { + return visited_platform_views_; +} + +MutatorsStack ShellTestExternalViewEmbedder::GetStack(int64_t view_id) { + return mutators_stacks_[view_id]; +} + +// |ExternalViewEmbedder| +void ShellTestExternalViewEmbedder::CancelFrame() {} + +// |ExternalViewEmbedder| +void ShellTestExternalViewEmbedder::BeginFrame( + GrDirectContext* context, + const fml::RefPtr& raster_thread_merger) {} + +// |ExternalViewEmbedder| +void ShellTestExternalViewEmbedder::PrepareFlutterView( + SkISize frame_size, + double device_pixel_ratio) { + visited_platform_views_.clear(); + mutators_stacks_.clear(); + current_composition_params_.clear(); +} + +// |ExternalViewEmbedder| +void ShellTestExternalViewEmbedder::PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) { + SkRect view_bounds = SkRect::Make(frame_size_); + auto view = std::make_unique(view_bounds); + slices_.insert_or_assign(view_id, std::move(view)); +} + +// |ExternalViewEmbedder| +PostPrerollResult ShellTestExternalViewEmbedder::PostPrerollAction( + const fml::RefPtr& raster_thread_merger) { + FML_DCHECK(raster_thread_merger); + return post_preroll_result_; +} + +// |ExternalViewEmbedder| +void ShellTestExternalViewEmbedder::PushVisitedPlatformView(int64_t view_id) { + visited_platform_views_.push_back(view_id); +} + +// |ExternalViewEmbedder| +void ShellTestExternalViewEmbedder::PushFilterToVisitedPlatformViews( + const std::shared_ptr& filter, + const SkRect& filter_rect) { + for (int64_t id : visited_platform_views_) { + EmbeddedViewParams params = current_composition_params_[id]; + params.PushImageFilter(filter, filter_rect); + current_composition_params_[id] = params; + mutators_stacks_[id] = params.mutatorsStack(); + } +} + +DlCanvas* ShellTestExternalViewEmbedder::CompositeEmbeddedView( + int64_t view_id) { + return slices_[view_id]->canvas(); +} + +// |ExternalViewEmbedder| +void ShellTestExternalViewEmbedder::SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) { + if (!frame) { + return; + } + frame->Submit(); + if (frame->SkiaSurface()) { + last_submitted_frame_size_ = SkISize::Make(frame->SkiaSurface()->width(), + frame->SkiaSurface()->height()); + } else { + last_submitted_frame_size_ = SkISize::MakeEmpty(); + } + submitted_frame_count_++; +} + +// |ExternalViewEmbedder| +void ShellTestExternalViewEmbedder::EndFrame( + bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + end_frame_call_back_(should_resubmit_frame, raster_thread_merger); +} + +// |ExternalViewEmbedder| +DlCanvas* ShellTestExternalViewEmbedder::GetRootCanvas() { + return nullptr; +} + +bool ShellTestExternalViewEmbedder::SupportsDynamicThreadMerging() { + return support_thread_merging_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/shell_test_external_view_embedder.h b/flutter/engine/src/flutter/shell/common/shell_test_external_view_embedder.h new file mode 100644 index 0000000000000000000000000000000000000000..ef63189c925936c756eda372702e2dd3ecda157d --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_external_view_embedder.h @@ -0,0 +1,114 @@ +// 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_COMMON_SHELL_TEST_EXTERNAL_VIEW_EMBEDDER_H_ +#define FLUTTER_SHELL_COMMON_SHELL_TEST_EXTERNAL_VIEW_EMBEDDER_H_ + +#include "flutter/flow/embedded_views.h" +#include "flutter/fml/raster_thread_merger.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief The external view embedder used by |ShellTestPlatformViewGL| +/// +class ShellTestExternalViewEmbedder final : public ExternalViewEmbedder { + public: + using EndFrameCallBack = + std::function)>; + + ShellTestExternalViewEmbedder(const EndFrameCallBack& end_frame_call_back, + PostPrerollResult post_preroll_result, + bool support_thread_merging); + + ~ShellTestExternalViewEmbedder() = default; + + // Updates the post preroll result so the |PostPrerollAction| after always + // returns the new `post_preroll_result`. + void UpdatePostPrerollResult(PostPrerollResult post_preroll_result); + + // Gets the number of times the SubmitFlutterView method has been called in + // the external view embedder. + int GetSubmittedFrameCount(); + + // Returns the size of last submitted frame surface. + SkISize GetLastSubmittedFrameSize(); + + // Returns the mutators stack for the given platform view. + MutatorsStack GetStack(int64_t); + + // Returns the list of visited platform views. + std::vector GetVisitedPlatformViews(); + + private: + // |ExternalViewEmbedder| + void CancelFrame() override; + + // |ExternalViewEmbedder| + void BeginFrame(GrDirectContext* context, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + void PrepareFlutterView(SkISize frame_size, + double device_pixel_ratio) override; + + // |ExternalViewEmbedder| + void PrerollCompositeEmbeddedView( + int64_t view_id, + std::unique_ptr params) override; + + // |ExternalViewEmbedder| + PostPrerollResult PostPrerollAction( + const fml::RefPtr& raster_thread_merger) + override; + + // |ExternalViewEmbedder| + DlCanvas* CompositeEmbeddedView(int64_t view_id) override; + + // |ExternalViewEmbedder| + void PushVisitedPlatformView(int64_t view_id) override; + + // |ExternalViewEmbedder| + void PushFilterToVisitedPlatformViews( + const std::shared_ptr& filter, + const SkRect& filter_rect) override; + + // |ExternalViewEmbedder| + void SubmitFlutterView( + int64_t flutter_view_id, + GrDirectContext* context, + const std::shared_ptr& aiks_context, + std::unique_ptr frame) override; + + // |ExternalViewEmbedder| + void EndFrame(bool should_resubmit_frame, + const fml::RefPtr& + raster_thread_merger) override; + + // |ExternalViewEmbedder| + DlCanvas* GetRootCanvas() override; + + // |ExternalViewEmbedder| + bool SupportsDynamicThreadMerging() override; + + const EndFrameCallBack end_frame_call_back_; + + PostPrerollResult post_preroll_result_; + + bool support_thread_merging_; + SkISize frame_size_; + std::map> slices_; + std::map mutators_stacks_; + std::map current_composition_params_; + std::vector visited_platform_views_; + std::atomic submitted_frame_count_; + std::atomic last_submitted_frame_size_; + + FML_DISALLOW_COPY_AND_ASSIGN(ShellTestExternalViewEmbedder); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SHELL_TEST_EXTERNAL_VIEW_EMBEDDER_H_ diff --git a/flutter/engine/src/flutter/shell/common/shell_test_platform_view.cc b/flutter/engine/src/flutter/shell/common/shell_test_platform_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..6f6a69aed956780b1ddc8247862b3c6d00dc0d41 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_platform_view.cc @@ -0,0 +1,109 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/shell_test_platform_view.h" + +#include + +#include "flutter/shell/common/vsync_waiter_fallback.h" + +namespace flutter::testing { + +std::unique_ptr ShellTestPlatformView::Create( + BackendType backend, + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& is_gpu_disabled_sync_switch) { + // TODO(gw280): https://github.com/flutter/flutter/issues/50298 + // Make this fully runtime configurable + switch (backend) { + case BackendType::kGLBackend: + return CreateGL(delegate, task_runners, vsync_clock, create_vsync_waiter, + shell_test_external_view_embedder, + is_gpu_disabled_sync_switch); + case BackendType::kMetalBackend: + return CreateMetal(delegate, task_runners, vsync_clock, + create_vsync_waiter, shell_test_external_view_embedder, + is_gpu_disabled_sync_switch); + case BackendType::kVulkanBackend: + return CreateVulkan( + delegate, task_runners, vsync_clock, create_vsync_waiter, + shell_test_external_view_embedder, is_gpu_disabled_sync_switch); + } +} + +#ifndef SHELL_ENABLE_GL +std::unique_ptr ShellTestPlatformView::CreateGL( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& is_gpu_disabled_sync_switch) { + FML_LOG(FATAL) << "OpenGL backend not enabled in this build"; + return nullptr; +} +#endif // SHELL_ENABLE_GL +#ifndef SHELL_ENABLE_METAL +std::unique_ptr ShellTestPlatformView::CreateMetal( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& is_gpu_disabled_sync_switch) { + FML_LOG(FATAL) << "Metal backend not enabled in this build"; + return nullptr; +} +#endif // SHELL_ENABLE_METAL +#ifndef SHELL_ENABLE_VULKAN +std::unique_ptr ShellTestPlatformView::CreateVulkan( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& is_gpu_disabled_sync_switch) { + FML_LOG(FATAL) << "Vulkan backend not enabled in this build"; + return nullptr; +} +#endif // SHELL_ENABLE_VULKAN + +ShellTestPlatformViewBuilder::ShellTestPlatformViewBuilder(Config config) + : config_(std::move(config)) {} + +std::unique_ptr ShellTestPlatformViewBuilder::operator()( + Shell& shell) { + const TaskRunners& task_runners = shell.GetTaskRunners(); + const auto vsync_clock = std::make_shared(); + CreateVsyncWaiter create_vsync_waiter = [&task_runners, vsync_clock, + simulate_vsync = + config_.simulate_vsync]() { + if (simulate_vsync) { + return static_cast>( + std::make_unique(task_runners, vsync_clock)); + } else { + return static_cast>( + std::make_unique(task_runners, true)); + } + }; + return ShellTestPlatformView::Create( + config_.rendering_backend, // + shell, // + task_runners, // + vsync_clock, // + create_vsync_waiter, // + config_.shell_test_external_view_embedder, // + shell.GetIsGpuDisabledSyncSwitch() // + ); +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/common/shell_test_platform_view.h b/flutter/engine/src/flutter/shell/common/shell_test_platform_view.h new file mode 100644 index 0000000000000000000000000000000000000000..de179fdbb2e84c060ba5172b38e94496a6cd7042 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_platform_view.h @@ -0,0 +1,109 @@ +// 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_COMMON_SHELL_TEST_PLATFORM_VIEW_H_ +#define FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_H_ + +#include + +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/common/shell_test_external_view_embedder.h" +#include "flutter/shell/common/vsync_waiters_test.h" + +namespace flutter::testing { + +class ShellTestPlatformView : public PlatformView { + public: + enum class BackendType { + kGLBackend, + kVulkanBackend, + kMetalBackend, + }; + + static BackendType DefaultBackendType() { +#if defined(SHELL_ENABLE_GL) + return BackendType::kGLBackend; +#elif defined(SHELL_ENABLE_METAL) + return BackendType::kMetalBackend; +#elif defined(SHELL_ENABLE_VULKAN) + return BackendType::kVulkanBackend; +#else + FML_LOG(FATAL) << "No backend is enabled in this build."; + std::terminate(); +#endif + } + + static std::unique_ptr Create( + BackendType backend, + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& + is_gpu_disabled_sync_switch); + + virtual void SimulateVSync() = 0; + + protected: + ShellTestPlatformView(PlatformView::Delegate& delegate, + const TaskRunners& task_runners) + : PlatformView(delegate, task_runners) {} + + static std::unique_ptr CreateGL( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& + is_gpu_disabled_sync_switch); + static std::unique_ptr CreateMetal( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& + is_gpu_disabled_sync_switch); + static std::unique_ptr CreateVulkan( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& + is_gpu_disabled_sync_switch); + + FML_DISALLOW_COPY_AND_ASSIGN(ShellTestPlatformView); +}; + +// Create a ShellTestPlatformView from configuration struct. +class ShellTestPlatformViewBuilder { + public: + struct Config { + bool simulate_vsync = false; + std::shared_ptr + shell_test_external_view_embedder = nullptr; + ShellTestPlatformView::BackendType rendering_backend = + ShellTestPlatformView::DefaultBackendType(); + }; + + explicit ShellTestPlatformViewBuilder(Config config); + ~ShellTestPlatformViewBuilder() = default; + + // Override operator () to make this class assignable to std::function. + std::unique_ptr operator()(Shell& shell); + + private: + Config config_; +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_H_ diff --git a/flutter/engine/src/flutter/shell/common/shell_test_platform_view_gl.cc b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_gl.cc new file mode 100644 index 0000000000000000000000000000000000000000..fbb629e464da40d737071893af2881b47be99f29 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_gl.cc @@ -0,0 +1,130 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/shell_test_platform_view_gl.h" + +#include + +#include + +#include "flutter/shell/gpu/gpu_surface_gl_skia.h" +#include "impeller/entity/gles/entity_shaders_gles.h" + +namespace flutter { +namespace testing { + +static std::vector> ShaderLibraryMappings() { + return { + std::make_shared( + impeller_entity_shaders_gles_data, + impeller_entity_shaders_gles_length), + }; +} + +std::unique_ptr ShellTestPlatformView::CreateGL( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& is_gpu_disabled_sync_switch) { + return std::make_unique( + delegate, task_runners, vsync_clock, create_vsync_waiter, + shell_test_external_view_embedder); +} + +ShellTestPlatformViewGL::ShellTestPlatformViewGL( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + std::shared_ptr vsync_clock, + CreateVsyncWaiter create_vsync_waiter, + std::shared_ptr + shell_test_external_view_embedder) + : ShellTestPlatformView(delegate, task_runners), + gl_surface_(SkISize::Make(800, 600)), + create_vsync_waiter_(std::move(create_vsync_waiter)), + vsync_clock_(std::move(vsync_clock)), + shell_test_external_view_embedder_( + std::move(shell_test_external_view_embedder)) { + if (GetSettings().enable_impeller) { + auto resolver = [](const char* name) -> void* { + return reinterpret_cast(::eglGetProcAddress(name)); + }; + // ANGLE needs this to initialize version strings checked by + // impeller::ProcTableGLES. + gl_surface_.MakeCurrent(); + auto gl = std::make_unique(resolver); + if (!gl->IsValid()) { + FML_LOG(ERROR) << "Proc table when a shell unittests invalid."; + return; + } + impeller_context_ = impeller::ContextGLES::Create( + impeller::Flags{}, std::move(gl), ShaderLibraryMappings(), true); + } +} + +ShellTestPlatformViewGL::~ShellTestPlatformViewGL() = default; + +std::unique_ptr ShellTestPlatformViewGL::CreateVSyncWaiter() { + return create_vsync_waiter_(); +} + +// |ShellTestPlatformView| +void ShellTestPlatformViewGL::SimulateVSync() { + vsync_clock_->SimulateVSync(); +} + +// |PlatformView| +std::unique_ptr ShellTestPlatformViewGL::CreateRenderingSurface() { + return std::make_unique(this, true); +} + +// |PlatformView| +std::shared_ptr +ShellTestPlatformViewGL::CreateExternalViewEmbedder() { + return shell_test_external_view_embedder_; +} + +// |PlatformView| +PointerDataDispatcherMaker ShellTestPlatformViewGL::GetDispatcherMaker() { + return [](DefaultPointerDataDispatcher::Delegate& delegate) { + return std::make_unique(delegate); + }; +} + +// |GPUSurfaceGLDelegate| +std::unique_ptr +ShellTestPlatformViewGL::GLContextMakeCurrent() { + return std::make_unique(gl_surface_.MakeCurrent()); +} + +// |GPUSurfaceGLDelegate| +bool ShellTestPlatformViewGL::GLContextClearCurrent() { + return gl_surface_.ClearCurrent(); +} + +// |GPUSurfaceGLDelegate| +bool ShellTestPlatformViewGL::GLContextPresent( + const GLPresentInfo& present_info) { + return gl_surface_.Present(); +} + +// |GPUSurfaceGLDelegate| +GLFBOInfo ShellTestPlatformViewGL::GLContextFBO(GLFrameInfo frame_info) const { + return GLFBOInfo{ + .fbo_id = gl_surface_.GetFramebuffer(frame_info.width, frame_info.height), + }; +} + +// |GPUSurfaceGLDelegate| +GPUSurfaceGLDelegate::GLProcResolver +ShellTestPlatformViewGL::GetGLProcResolver() const { + return [surface = &gl_surface_](const char* name) -> void* { + return surface->GetProcAddress(name); + }; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/shell_test_platform_view_gl.h b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_gl.h new file mode 100644 index 0000000000000000000000000000000000000000..12aa92d7f96740bd87700b4c63e920282a14229d --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_gl.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_COMMON_SHELL_TEST_PLATFORM_VIEW_GL_H_ +#define FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_GL_H_ + +#include "flutter/shell/common/shell_test_external_view_embedder.h" +#include "flutter/shell/common/shell_test_platform_view.h" +#include "flutter/shell/gpu/gpu_surface_gl_delegate.h" +#include "flutter/testing/test_gl_surface.h" +#include "impeller/renderer/backend/gles/context_gles.h" + +namespace flutter { +namespace testing { + +class ShellTestPlatformViewGL : public ShellTestPlatformView, + public GPUSurfaceGLDelegate { + public: + ShellTestPlatformViewGL(PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + std::shared_ptr vsync_clock, + CreateVsyncWaiter create_vsync_waiter, + std::shared_ptr + shell_test_external_view_embedder); + + // |ShellTestPlatformView| + virtual ~ShellTestPlatformViewGL() override; + + // |ShellTestPlatformView| + virtual void SimulateVSync() override; + + // |PlatformView| + std::shared_ptr GetImpellerContext() const { + return impeller_context_; + } + + private: + std::shared_ptr impeller_context_; + + TestGLSurface gl_surface_; + + CreateVsyncWaiter create_vsync_waiter_; + + std::shared_ptr vsync_clock_; + + std::shared_ptr + shell_test_external_view_embedder_; + + // |PlatformView| + std::unique_ptr CreateRenderingSurface() override; + + // |PlatformView| + std::shared_ptr CreateExternalViewEmbedder() override; + + // |PlatformView| + std::unique_ptr CreateVSyncWaiter() override; + + // |PlatformView| + PointerDataDispatcherMaker GetDispatcherMaker() override; + + // |GPUSurfaceGLDelegate| + std::unique_ptr GLContextMakeCurrent() override; + + // |GPUSurfaceGLDelegate| + bool GLContextClearCurrent() override; + + // |GPUSurfaceGLDelegate| + bool GLContextPresent(const GLPresentInfo& present_info) override; + + // |GPUSurfaceGLDelegate| + GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const override; + + // |GPUSurfaceGLDelegate| + GLProcResolver GetGLProcResolver() const override; + + FML_DISALLOW_COPY_AND_ASSIGN(ShellTestPlatformViewGL); +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_GL_H_ diff --git a/flutter/engine/src/flutter/shell/common/shell_test_platform_view_metal.h b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_metal.h new file mode 100644 index 0000000000000000000000000000000000000000..7f3204ddceccf13bf5dc9eb005e2b2547fe5bf42 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_metal.h @@ -0,0 +1,79 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_METAL_H_ +#define FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_METAL_H_ + +#include "flutter/shell/common/shell_test_platform_view.h" + +#import + +#include "flutter/fml/macros.h" +#include "flutter/shell/gpu/gpu_surface_metal_delegate.h" +#include "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h" +#include "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h" + +namespace flutter::testing { + +class ShellTestPlatformViewMetal final : public ShellTestPlatformView, + public GPUSurfaceMetalDelegate { + public: + ShellTestPlatformViewMetal(PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + std::shared_ptr vsync_clock, + CreateVsyncWaiter create_vsync_waiter, + std::shared_ptr + shell_test_external_view_embedder, + const std::shared_ptr& + is_gpu_disabled_sync_switch); + + // |ShellTestPlatformView| + virtual ~ShellTestPlatformViewMetal() override; + + private: + FlutterDarwinContextMetalSkia* skia_context_; + FlutterDarwinContextMetalImpeller* impeller_context_; + id offscreen_texture_; + const CreateVsyncWaiter create_vsync_waiter_; + const std::shared_ptr vsync_clock_; + const std::shared_ptr + shell_test_external_view_embedder_; + + // |ShellTestPlatformView| + virtual void SimulateVSync() override; + + // |PlatformView| + std::unique_ptr CreateVSyncWaiter() override; + + // |PlatformView| + std::shared_ptr CreateExternalViewEmbedder() override; + + // |PlatformView| + PointerDataDispatcherMaker GetDispatcherMaker() override; + + // |PlatformView| + std::unique_ptr CreateRenderingSurface() override; + + // |PlatformView| + std::shared_ptr GetImpellerContext() const override; + + // |GPUSurfaceMetalDelegate| + GPUCAMetalLayerHandle GetCAMetalLayer( + const SkISize& frame_info) const override; + + // |GPUSurfaceMetalDelegate| + bool PresentDrawable(GrMTLHandle drawable) const override; + + // |GPUSurfaceMetalDelegate| + GPUMTLTextureInfo GetMTLTexture(const SkISize& frame_info) const override; + + // |GPUSurfaceMetalDelegate| + bool PresentTexture(GPUMTLTextureInfo texture) const override; + + FML_DISALLOW_COPY_AND_ASSIGN(ShellTestPlatformViewMetal); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_METAL_H_ diff --git a/flutter/engine/src/flutter/shell/common/shell_test_platform_view_metal.mm b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_metal.mm new file mode 100644 index 0000000000000000000000000000000000000000..8383cf0625693167080ae1e5fe271e081d081170 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_metal.mm @@ -0,0 +1,127 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/shell_test_platform_view_metal.h" + +#include + +#include "flutter/shell/gpu/gpu_surface_metal_impeller.h" +#include "flutter/shell/gpu/gpu_surface_metal_skia.h" + +FLUTTER_ASSERT_ARC + +namespace flutter::testing { + +std::unique_ptr ShellTestPlatformView::CreateMetal( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& shell_test_external_view_embedder, + const std::shared_ptr& is_gpu_disabled_sync_switch) { + return std::make_unique( + delegate, task_runners, vsync_clock, create_vsync_waiter, shell_test_external_view_embedder, + is_gpu_disabled_sync_switch); +} + +ShellTestPlatformViewMetal::ShellTestPlatformViewMetal( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + std::shared_ptr vsync_clock, + CreateVsyncWaiter create_vsync_waiter, + std::shared_ptr shell_test_external_view_embedder, + const std::shared_ptr& is_gpu_disabled_sync_switch) + : ShellTestPlatformView(delegate, task_runners), + GPUSurfaceMetalDelegate(MTLRenderTargetType::kMTLTexture), + create_vsync_waiter_(std::move(create_vsync_waiter)), + vsync_clock_(std::move(vsync_clock)), + shell_test_external_view_embedder_(std::move(shell_test_external_view_embedder)) { + id device = nil; + if (GetSettings().enable_impeller) { + impeller_context_ = + [[FlutterDarwinContextMetalImpeller alloc] init:impeller::Flags {} + gpuDisabledSyncSwitch:is_gpu_disabled_sync_switch]; + FML_CHECK(impeller_context_.context); + device = impeller_context_.context->GetMTLDevice(); + } else { + skia_context_ = [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]; + FML_CHECK(skia_context_.mainContext); + device = skia_context_.device; + } + auto descriptor = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:800 + height:600 + mipmapped:NO]; + descriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + offscreen_texture_ = [device newTextureWithDescriptor:descriptor]; +} + +ShellTestPlatformViewMetal::~ShellTestPlatformViewMetal() = default; + +std::unique_ptr ShellTestPlatformViewMetal::CreateVSyncWaiter() { + return create_vsync_waiter_(); +} + +// |ShellTestPlatformView| +void ShellTestPlatformViewMetal::SimulateVSync() { + vsync_clock_->SimulateVSync(); +} + +// |PlatformView| +std::shared_ptr ShellTestPlatformViewMetal::CreateExternalViewEmbedder() { + return shell_test_external_view_embedder_; +} + +// |PlatformView| +PointerDataDispatcherMaker ShellTestPlatformViewMetal::GetDispatcherMaker() { + return [](DefaultPointerDataDispatcher::Delegate& delegate) { + return std::make_unique(delegate); + }; +} + +// |PlatformView| +std::unique_ptr ShellTestPlatformViewMetal::CreateRenderingSurface() { + if (GetSettings().enable_impeller) { + auto context = impeller_context_.context; + return std::make_unique( + this, std::make_shared(context, nullptr)); + } + return std::make_unique(this, skia_context_.mainContext); +} + +// |PlatformView| +std::shared_ptr ShellTestPlatformViewMetal::GetImpellerContext() const { + return impeller_context_.context; +} + +// |GPUSurfaceMetalDelegate| +GPUCAMetalLayerHandle ShellTestPlatformViewMetal::GetCAMetalLayer(const SkISize& frame_info) const { + FML_CHECK(false) << "A Metal Delegate configured with MTLRenderTargetType::kMTLTexture was asked " + "to acquire a layer."; + return nullptr; +} + +// |GPUSurfaceMetalDelegate| +bool ShellTestPlatformViewMetal::PresentDrawable(GrMTLHandle drawable) const { + FML_CHECK(false) << "A Metal Delegate configured with MTLRenderTargetType::kMTLTexture was asked " + "to present a layer drawable."; + return true; +} + +// |GPUSurfaceMetalDelegate| +GPUMTLTextureInfo ShellTestPlatformViewMetal::GetMTLTexture(const SkISize& frame_info) const { + return { + .texture_id = 0, + .texture = (__bridge GPUMTLTextureHandle)offscreen_texture_, + }; +} + +// |GPUSurfaceMetalDelegate| +bool ShellTestPlatformViewMetal::PresentTexture(GPUMTLTextureInfo texture) const { + // The texture resides offscreen. There is nothing to render to. + return true; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/common/shell_test_platform_view_vulkan.cc b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_vulkan.cc new file mode 100644 index 0000000000000000000000000000000000000000..27129ed907c3581f50eed2c8fdb8d6f616843c3d --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_vulkan.cc @@ -0,0 +1,247 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/shell_test_platform_view_vulkan.h" + +#include + +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/flutter_vma/flutter_skia_vma.h" +#include "flutter/shell/common/context_options.h" +#include "flutter/vulkan/vulkan_skia_proc_table.h" +#include "flutter/vulkan/vulkan_utilities.h" + +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkDirectContext.h" +#include "third_party/skia/include/gpu/vk/VulkanExtensions.h" + +#if OS_FUCHSIA +#define VULKAN_SO_PATH "libvulkan.so" +#else +#include "flutter/vulkan/swiftshader_path.h" +#endif + +namespace flutter::testing { + +std::unique_ptr ShellTestPlatformView::CreateVulkan( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + const std::shared_ptr& vsync_clock, + const CreateVsyncWaiter& create_vsync_waiter, + const std::shared_ptr& + shell_test_external_view_embedder, + const std::shared_ptr& is_gpu_disabled_sync_switch) { + return std::make_unique( + delegate, task_runners, vsync_clock, create_vsync_waiter, + shell_test_external_view_embedder); +} + +ShellTestPlatformViewVulkan::ShellTestPlatformViewVulkan( + PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + std::shared_ptr vsync_clock, + CreateVsyncWaiter create_vsync_waiter, + std::shared_ptr + shell_test_external_view_embedder) + : ShellTestPlatformView(delegate, task_runners), + create_vsync_waiter_(std::move(create_vsync_waiter)), + vsync_clock_(std::move(vsync_clock)), + proc_table_(fml::MakeRefCounted(VULKAN_SO_PATH)), + shell_test_external_view_embedder_( + std::move(shell_test_external_view_embedder)) {} + +ShellTestPlatformViewVulkan::~ShellTestPlatformViewVulkan() = default; + +std::unique_ptr ShellTestPlatformViewVulkan::CreateVSyncWaiter() { + return create_vsync_waiter_(); +} + +void ShellTestPlatformViewVulkan::SimulateVSync() { + vsync_clock_->SimulateVSync(); +} + +// |PlatformView| +std::unique_ptr ShellTestPlatformViewVulkan::CreateRenderingSurface() { + return std::make_unique(proc_table_, + shell_test_external_view_embedder_); +} + +// |PlatformView| +std::shared_ptr +ShellTestPlatformViewVulkan::CreateExternalViewEmbedder() { + return shell_test_external_view_embedder_; +} + +// |PlatformView| +PointerDataDispatcherMaker ShellTestPlatformViewVulkan::GetDispatcherMaker() { + return [](DefaultPointerDataDispatcher::Delegate& delegate) { + return std::make_unique(delegate); + }; +} + +// TODO(gw280): This code was forked from vulkan_window.cc specifically for +// shell_test. +// We need to merge this functionality back into //vulkan. +// https://github.com/flutter/flutter/issues/51132 +ShellTestPlatformViewVulkan::OffScreenSurface::OffScreenSurface( + fml::RefPtr vk, + std::shared_ptr + shell_test_external_view_embedder) + : vk_(std::move(vk)), + shell_test_external_view_embedder_( + std::move(shell_test_external_view_embedder)) { + if (!vk_ || !vk_->HasAcquiredMandatoryProcAddresses()) { + FML_DLOG(ERROR) << "Proc table has not acquired mandatory proc addresses."; + return; + } + + // Create the application instance. + std::vector extensions = { + VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME, + }; + + application_ = std::make_unique( + *vk_, "FlutterTest", std::move(extensions), VK_MAKE_VERSION(1, 0, 0), + VK_MAKE_VERSION(1, 1, 0), true); + + if (!application_->IsValid() || !vk_->AreInstanceProcsSetup()) { + // Make certain the application instance was created and it set up the + // instance proc table entries. + FML_DLOG(ERROR) << "Instance proc addresses have not been set up."; + return; + } + + // Create the device. + + logical_device_ = application_->AcquireFirstCompatibleLogicalDevice(); + + if (logical_device_ == nullptr || !logical_device_->IsValid() || + !vk_->AreDeviceProcsSetup()) { + // Make certain the device was created and it set up the device proc table + // entries. + FML_DLOG(ERROR) << "Device proc addresses have not been set up."; + return; + } + + memory_allocator_ = FlutterSkiaVulkanMemoryAllocator::Make( + application_->GetAPIVersion(), application_->GetInstance(), + logical_device_->GetPhysicalDeviceHandle(), logical_device_->GetHandle(), + vk_, true); + + // Create the Skia GrContext. + if (!CreateSkiaGrContext()) { + FML_DLOG(ERROR) << "Could not create Skia context."; + return; + } + + valid_ = true; +} + +bool ShellTestPlatformViewVulkan::OffScreenSurface::CreateSkiaGrContext() { + skgpu::VulkanBackendContext backend_context; + skgpu::VulkanExtensions no_extensions; + // For now, Skia crashes if fDeviceFeatures is set but fVkExtensions is not. + backend_context.fVkExtensions = &no_extensions; + VkPhysicalDeviceFeatures features; + // It may be tempting to put features into backend_context here + // and pass just backend_context into the below function, however the pointers + // for features are const, so we won't be able to update them. + + if (!this->CreateSkiaBackendContext(&backend_context, &features)) { + FML_DLOG(ERROR) << "Could not create Skia backend context."; + return false; + } + + const auto options = + MakeDefaultContextOptions(ContextType::kRender, GrBackendApi::kVulkan); + + sk_sp context = + GrDirectContexts::MakeVulkan(backend_context, options); + + if (context == nullptr) { + FML_DLOG(ERROR) << "Failed to create GrDirectContext"; + return false; + } + + context->setResourceCacheLimit(vulkan::kGrCacheMaxByteSize); + + context_ = context; + + return true; +} + +bool ShellTestPlatformViewVulkan::OffScreenSurface::CreateSkiaBackendContext( + skgpu::VulkanBackendContext* context, + VkPhysicalDeviceFeatures* features) { + FML_CHECK(context); + FML_CHECK(features); + auto getProc = CreateSkiaGetProc(vk_); + + if (getProc == nullptr) { + FML_DLOG(ERROR) << "GetProcAddress is null"; + return false; + } + + if (!logical_device_->GetPhysicalDeviceFeatures(features)) { + FML_DLOG(ERROR) << "Failed to get Physical Device features"; + return false; + } + + context->fInstance = application_->GetInstance(); + context->fPhysicalDevice = logical_device_->GetPhysicalDeviceHandle(); + context->fDevice = logical_device_->GetHandle(); + context->fQueue = logical_device_->GetQueueHandle(); + context->fGraphicsQueueIndex = logical_device_->GetGraphicsQueueIndex(); + context->fMaxAPIVersion = application_->GetAPIVersion(); + context->fDeviceFeatures = features; + context->fGetProc = std::move(getProc); + context->fMemoryAllocator = memory_allocator_; + + return true; +} + +ShellTestPlatformViewVulkan::OffScreenSurface::~OffScreenSurface() {} + +bool ShellTestPlatformViewVulkan::OffScreenSurface::IsValid() { + return valid_; +} + +std::unique_ptr +ShellTestPlatformViewVulkan::OffScreenSurface::AcquireFrame( + const SkISize& size) { + auto image_info = SkImageInfo::Make(size, SkColorType::kRGBA_8888_SkColorType, + SkAlphaType::kOpaque_SkAlphaType); + auto surface = SkSurfaces::RenderTarget(context_.get(), skgpu::Budgeted::kNo, + image_info, 0, nullptr); + + SurfaceFrame::EncodeCallback encode_callback = [](const SurfaceFrame&, + DlCanvas* canvas) -> bool { + canvas->Flush(); + return true; + }; + SurfaceFrame::SubmitCallback submit_callback = + [](const SurfaceFrame&) -> bool { return true; }; + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + return std::make_unique(std::move(surface), framebuffer_info, + std::move(encode_callback), + std::move(submit_callback), + /*frame_size=*/SkISize::Make(800, 600)); +} + +GrDirectContext* ShellTestPlatformViewVulkan::OffScreenSurface::GetContext() { + return context_.get(); +} + +SkMatrix ShellTestPlatformViewVulkan::OffScreenSurface::GetRootTransformation() + const { + SkMatrix matrix; + matrix.reset(); + return matrix; +} + +} // namespace flutter::testing diff --git a/flutter/engine/src/flutter/shell/common/shell_test_platform_view_vulkan.h b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_vulkan.h new file mode 100644 index 0000000000000000000000000000000000000000..5ab27fe975407cbfc18b9839ea9c5916c1711795 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_test_platform_view_vulkan.h @@ -0,0 +1,97 @@ +// 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_COMMON_SHELL_TEST_PLATFORM_VIEW_VULKAN_H_ +#define FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_VULKAN_H_ + +#include "flutter/shell/common/shell_test_external_view_embedder.h" +#include "flutter/shell/common/shell_test_platform_view.h" +#include "flutter/shell/gpu/gpu_surface_vulkan_delegate.h" +#include "flutter/vulkan/vulkan_application.h" +#include "flutter/vulkan/vulkan_device.h" +#include "flutter/vulkan/vulkan_skia_proc_table.h" +#include "third_party/skia/include/gpu/vk/VulkanBackendContext.h" +#include "third_party/skia/include/gpu/vk/VulkanMemoryAllocator.h" +#include "third_party/skia/include/gpu/vk/VulkanTypes.h" + +namespace flutter::testing { + +class ShellTestPlatformViewVulkan : public ShellTestPlatformView { + public: + ShellTestPlatformViewVulkan(PlatformView::Delegate& delegate, + const TaskRunners& task_runners, + std::shared_ptr vsync_clock, + CreateVsyncWaiter create_vsync_waiter, + std::shared_ptr + shell_test_external_view_embedder); + + ~ShellTestPlatformViewVulkan() override; + + void SimulateVSync() override; + + private: + class OffScreenSurface : public flutter::Surface { + public: + OffScreenSurface(fml::RefPtr vk, + std::shared_ptr + shell_test_external_view_embedder); + + ~OffScreenSurface() override; + + // |Surface| + bool IsValid() override; + + // |Surface| + std::unique_ptr AcquireFrame(const SkISize& size) override; + + // |Surface| + SkMatrix GetRootTransformation() const override; + + // |Surface| + GrDirectContext* GetContext() override; + + private: + bool valid_ = false; + fml::RefPtr vk_; + std::shared_ptr + shell_test_external_view_embedder_; + std::unique_ptr application_; + std::unique_ptr logical_device_; + sk_sp memory_allocator_; + sk_sp context_; + + bool CreateSkiaGrContext(); + bool CreateSkiaBackendContext(skgpu::VulkanBackendContext*, + VkPhysicalDeviceFeatures*); + + FML_DISALLOW_COPY_AND_ASSIGN(OffScreenSurface); + }; + + CreateVsyncWaiter create_vsync_waiter_; + + std::shared_ptr vsync_clock_; + + fml::RefPtr proc_table_; + + std::shared_ptr + shell_test_external_view_embedder_; + + // |PlatformView| + std::unique_ptr CreateRenderingSurface() override; + + // |PlatformView| + std::shared_ptr CreateExternalViewEmbedder() override; + + // |PlatformView| + std::unique_ptr CreateVSyncWaiter() override; + + // |PlatformView| + PointerDataDispatcherMaker GetDispatcherMaker() override; + + FML_DISALLOW_COPY_AND_ASSIGN(ShellTestPlatformViewVulkan); +}; + +} // namespace flutter::testing + +#endif // FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_VULKAN_H_ diff --git a/flutter/engine/src/flutter/shell/common/shell_unittests.cc b/flutter/engine/src/flutter/shell/common/shell_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..2bbf216bd0ceb98683044da677b6920996593b53 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/shell_unittests.cc @@ -0,0 +1,5078 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include +#include +#include +#include +#include +#include +#include + +#if SHELL_ENABLE_GL +#include +#endif // SHELL_ENABLE_GL + +#include "assets/asset_resolver.h" +#include "assets/directory_asset_bundle.h" +#include "common/graphics/persistent_cache.h" +#include "flutter/display_list/effects/dl_image_filter.h" +#include "flutter/flow/layers/backdrop_filter_layer.h" +#include "flutter/flow/layers/clip_rect_layer.h" +#include "flutter/flow/layers/display_list_layer.h" +#include "flutter/flow/layers/layer_raster_cache_item.h" +#include "flutter/flow/layers/platform_view_layer.h" +#include "flutter/flow/layers/transform_layer.h" +#include "flutter/fml/backtrace.h" +#include "flutter/fml/command_line.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/common/rasterizer.h" +#include "flutter/shell/common/shell_test.h" +#include "flutter/shell/common/shell_test_external_view_embedder.h" +#include "flutter/shell/common/shell_test_platform_view.h" +#include "flutter/shell/common/switches.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/shell/common/vsync_waiter_fallback.h" +#include "flutter/shell/common/vsync_waiters_test.h" +#include "flutter/shell/version/version.h" +#include "flutter/testing/testing.h" +#include "fml/mapping.h" +#include "gmock/gmock.h" +#include "impeller/core/runtime_types.h" +#include "lib/ui/semantics/semantics_node.h" +#include "third_party/rapidjson/include/rapidjson/writer.h" +#include "third_party/skia/include/codec/SkCodecAnimation.h" +#include "third_party/tonic/converter/dart_converter.h" + +#ifdef SHELL_ENABLE_VULKAN +#include "flutter/vulkan/vulkan_application.h" // nogncheck +#endif + +// CREATE_NATIVE_ENTRY is leaky by design +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +namespace flutter { +namespace testing { + +constexpr int64_t kImplicitViewId = 0ll; + +using ::testing::_; +using ::testing::Return; + +namespace { + +std::unique_ptr MakePlatformMessage( + const std::string& channel, + const std::map& values, + const fml::RefPtr& response) { + rapidjson::Document document; + auto& allocator = document.GetAllocator(); + document.SetObject(); + + for (const auto& pair : values) { + rapidjson::Value key(pair.first.c_str(), strlen(pair.first.c_str()), + allocator); + rapidjson::Value value(pair.second.c_str(), strlen(pair.second.c_str()), + allocator); + document.AddMember(key, value, allocator); + } + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + const uint8_t* data = reinterpret_cast(buffer.GetString()); + + std::unique_ptr message = std::make_unique( + channel, fml::MallocMapping::Copy(data, buffer.GetSize()), response); + return message; +} + +class MockPlatformViewDelegate : public PlatformView::Delegate { + MOCK_METHOD(void, + OnPlatformViewCreated, + (std::unique_ptr surface), + (override)); + + MOCK_METHOD(void, OnPlatformViewDestroyed, (), (override)); + + MOCK_METHOD(void, OnPlatformViewScheduleFrame, (), (override)); + + MOCK_METHOD(void, + OnPlatformViewAddView, + (int64_t view_id, + const ViewportMetrics& viewport_metrics, + AddViewCallback callback), + (override)); + + MOCK_METHOD(void, + OnPlatformViewRemoveView, + (int64_t view_id, RemoveViewCallback callback), + (override)); + + MOCK_METHOD(void, + OnPlatformViewSendViewFocusEvent, + (const ViewFocusEvent& event), + (override)); + + MOCK_METHOD(void, + OnPlatformViewSetNextFrameCallback, + (const fml::closure& closure), + (override)); + + MOCK_METHOD(void, + OnPlatformViewSetViewportMetrics, + (int64_t view_id, const ViewportMetrics& metrics), + (override)); + + MOCK_METHOD(void, + OnPlatformViewDispatchPlatformMessage, + (std::unique_ptr message), + (override)); + + MOCK_METHOD(void, + OnPlatformViewDispatchPointerDataPacket, + (std::unique_ptr packet), + (override)); + + MOCK_METHOD(void, + OnPlatformViewDispatchSemanticsAction, + (int64_t view_id, + int32_t id, + SemanticsAction action, + fml::MallocMapping args), + (override)); + + MOCK_METHOD(void, + OnPlatformViewSetSemanticsEnabled, + (bool enabled), + (override)); + + MOCK_METHOD(void, + OnPlatformViewSetAccessibilityFeatures, + (int32_t flags), + (override)); + + MOCK_METHOD(void, + OnPlatformViewRegisterTexture, + (std::shared_ptr texture), + (override)); + + MOCK_METHOD(void, + OnPlatformViewUnregisterTexture, + (int64_t texture_id), + (override)); + + MOCK_METHOD(void, + OnPlatformViewMarkTextureFrameAvailable, + (int64_t texture_id), + (override)); + + MOCK_METHOD(const Settings&, + OnPlatformViewGetSettings, + (), + (const, override)); + + MOCK_METHOD(void, + LoadDartDeferredLibrary, + (intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions), + (override)); + + MOCK_METHOD(void, + LoadDartDeferredLibraryError, + (intptr_t loading_unit_id, + const std::string error_message, + bool transient), + (override)); + + MOCK_METHOD(void, + UpdateAssetResolverByType, + (std::unique_ptr updated_asset_resolver, + AssetResolver::AssetResolverType type), + (override)); +}; + +class MockSurface : public Surface { + public: + MOCK_METHOD(bool, IsValid, (), (override)); + + MOCK_METHOD(std::unique_ptr, + AcquireFrame, + (const SkISize& size), + (override)); + + MOCK_METHOD(SkMatrix, GetRootTransformation, (), (const, override)); + + MOCK_METHOD(GrDirectContext*, GetContext, (), (override)); + + MOCK_METHOD(std::unique_ptr, + MakeRenderContextCurrent, + (), + (override)); + + MOCK_METHOD(bool, ClearRenderContext, (), (override)); +}; + +class MockPlatformView : public PlatformView { + public: + MockPlatformView(MockPlatformViewDelegate& delegate, + const TaskRunners& task_runners) + : PlatformView(delegate, task_runners) {} + MOCK_METHOD(std::unique_ptr, CreateRenderingSurface, (), (override)); + MOCK_METHOD(std::shared_ptr, + GetPlatformMessageHandler, + (), + (const, override)); +}; + +class TestPlatformView : public PlatformView { + public: + TestPlatformView(Shell& shell, const TaskRunners& task_runners) + : PlatformView(shell, task_runners) {} + MOCK_METHOD(std::unique_ptr, CreateRenderingSurface, (), (override)); +}; + +class MockPlatformMessageHandler : public PlatformMessageHandler { + public: + MOCK_METHOD(void, + HandlePlatformMessage, + (std::unique_ptr message), + (override)); + MOCK_METHOD(bool, + DoesHandlePlatformMessageOnPlatformThread, + (), + (const, override)); + MOCK_METHOD(void, + InvokePlatformMessageResponseCallback, + (int response_id, std::unique_ptr mapping), + (override)); + MOCK_METHOD(void, + InvokePlatformMessageEmptyResponseCallback, + (int response_id), + (override)); +}; + +class MockPlatformMessageResponse : public PlatformMessageResponse { + public: + static fml::RefPtr Create() { + return fml::AdoptRef(new MockPlatformMessageResponse()); + } + MOCK_METHOD(void, Complete, (std::unique_ptr data), (override)); + MOCK_METHOD(void, CompleteEmpty, (), (override)); +}; +} // namespace + +class TestAssetResolver : public AssetResolver { + public: + TestAssetResolver(bool valid, AssetResolver::AssetResolverType type) + : valid_(valid), type_(type) {} + + bool IsValid() const override { return true; } + + // This is used to identify if replacement was made or not. + bool IsValidAfterAssetManagerChange() const override { return valid_; } + + AssetResolver::AssetResolverType GetType() const override { return type_; } + + std::unique_ptr GetAsMapping( + const std::string& asset_name) const override { + return nullptr; + } + + std::vector> GetAsMappings( + const std::string& asset_pattern, + const std::optional& subdir) const override { + return {}; + }; + + bool operator==(const AssetResolver& other) const override { + return this == &other; + } + + private: + bool valid_; + AssetResolver::AssetResolverType type_; +}; + +class ThreadCheckingAssetResolver : public AssetResolver { + public: + explicit ThreadCheckingAssetResolver( + std::shared_ptr concurrent_loop) + : concurrent_loop_(std::move(concurrent_loop)) {} + + // |AssetResolver| + bool IsValid() const override { return true; } + + // |AssetResolver| + bool IsValidAfterAssetManagerChange() const override { return true; } + + // |AssetResolver| + AssetResolverType GetType() const { + return AssetResolverType::kApkAssetProvider; + } + + // |AssetResolver| + std::unique_ptr GetAsMapping( + const std::string& asset_name) const override { + if (asset_name == "FontManifest.json" || + asset_name == "NativeAssetsManifest.json") { + // This file is loaded directly by the engine. + return nullptr; + } + mapping_requests.push_back(asset_name); + EXPECT_TRUE(concurrent_loop_->RunsTasksOnCurrentThread()) + << fml::BacktraceHere(); + return nullptr; + } + + mutable std::vector mapping_requests; + + bool operator==(const AssetResolver& other) const override { + return this == &other; + } + + private: + std::shared_ptr concurrent_loop_; +}; + +static bool ValidateShell(Shell* shell) { + if (!shell) { + return false; + } + + if (!shell->IsSetup()) { + return false; + } + + ShellTest::PlatformViewNotifyCreated(shell); + + { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), [shell, &latch]() { + shell->GetPlatformView()->NotifyDestroyed(); + latch.Signal(); + }); + latch.Wait(); + } + + return true; +} + +static bool RasterizerIsTornDown(Shell* shell) { + fml::AutoResetWaitableEvent latch; + bool is_torn_down = false; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetRasterTaskRunner(), + [shell, &latch, &is_torn_down]() { + is_torn_down = shell->GetRasterizer()->IsTornDown(); + latch.Signal(); + }); + latch.Wait(); + return is_torn_down; +} + +static void ValidateDestroyPlatformView(Shell* shell) { + ASSERT_TRUE(shell != nullptr); + ASSERT_TRUE(shell->IsSetup()); + + ASSERT_FALSE(RasterizerIsTornDown(shell)); + ShellTest::PlatformViewNotifyDestroyed(shell); + ASSERT_TRUE(RasterizerIsTornDown(shell)); +} + +static std::string CreateFlagsString(std::vector& flags) { + if (flags.empty()) { + return ""; + } + std::string flags_string = flags[0]; + for (size_t i = 1; i < flags.size(); ++i) { + flags_string += ","; + flags_string += flags[i]; + } + return flags_string; +} + +static void TestDartVmFlags(std::vector& flags) { + std::string flags_string = CreateFlagsString(flags); + const std::vector options = { + fml::CommandLine::Option("dart-flags", flags_string)}; + fml::CommandLine command_line("", options, std::vector()); + flutter::Settings settings = flutter::SettingsFromCommandLine(command_line); + EXPECT_EQ(settings.dart_flags.size(), flags.size()); + for (size_t i = 0; i < flags.size(); ++i) { + EXPECT_EQ(settings.dart_flags[i], flags[i]); + } +} + +static void PostSync(const fml::RefPtr& task_runner, + const fml::closure& task) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask(task_runner, [&latch, &task] { + task(); + latch.Signal(); + }); + latch.Wait(); +} + +static sk_sp MakeSizedDisplayList(int width, int height) { + DisplayListBuilder builder(DlRect::MakeXYWH(0, 0, width, height)); + builder.DrawRect(DlRect::MakeXYWH(0, 0, width, height), + DlPaint(DlColor::kRed())); + return builder.Build(); +} + +TEST_F(ShellTest, InitializeWithInvalidThreads) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + TaskRunners task_runners("test", nullptr, nullptr, nullptr, nullptr); + auto shell = CreateShell(settings, task_runners); + ASSERT_FALSE(shell); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, InitializeWithDifferentThreads) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + std::string name_prefix = "io.flutter.test." + GetCurrentTestName() + "."; + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + name_prefix, ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + ASSERT_EQ(thread_host.name_prefix, name_prefix); + + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(ValidateShell(shell.get())); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, InitializeWithSingleThread) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, InitializeWithSingleThreadWhichIsTheCallingThread) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(ValidateShell(shell.get())); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, + InitializeWithMultipleThreadButCallingThreadAsPlatformThread) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kRaster | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + fml::MessageLoop::EnsureInitializedForCurrentThread(); + TaskRunners task_runners("test", + fml::MessageLoop::GetCurrent().GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + auto shell = Shell::Create( + flutter::PlatformData(), task_runners, settings, + [](Shell& shell) { + // This is unused in the platform view as we are not using the simulated + // vsync mechanism. We should have better DI in the tests. + const auto vsync_clock = std::make_shared(); + return ShellTestPlatformView::Create( + ShellTestPlatformView::DefaultBackendType(), shell, + shell.GetTaskRunners(), vsync_clock, + [task_runners = shell.GetTaskRunners()]() { + return static_cast>( + std::make_unique(task_runners)); + }, + nullptr, shell.GetIsGpuDisabledSyncSwitch()); + }, + [](Shell& shell) { return std::make_unique(shell); }); + ASSERT_TRUE(ValidateShell(shell.get())); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, InitializeWithDisabledGpu) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + auto shell = CreateShell({ + .settings = settings, + .task_runners = task_runners, + .is_gpu_disabled = true, + }); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + + bool is_disabled = false; + shell->GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers().SetIfTrue([&] { is_disabled = true; })); + ASSERT_TRUE(is_disabled); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, InitializeWithGPUAndPlatformThreadsTheSame) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners( + "test", + thread_host.platform_thread->GetTaskRunner(), // platform + thread_host.platform_thread->GetTaskRunner(), // raster + thread_host.ui_thread->GetTaskRunner(), // ui + thread_host.io_thread->GetTaskRunner() // io + ); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, FixturesAreFunctional) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + configuration.SetEntrypoint("fixturesAreFunctionalMain"); + + fml::AutoResetWaitableEvent main_latch; + AddNativeCallback( + "SayHiFromFixturesAreFunctionalMain", + CREATE_NATIVE_ENTRY([&main_latch](auto args) { main_latch.Signal(); })); + + RunEngine(shell.get(), std::move(configuration)); + main_latch.Wait(); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell)); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, SecondaryIsolateBindingsAreSetupViaShellSettings) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + configuration.SetEntrypoint("testCanLaunchSecondaryIsolate"); + + fml::CountDownLatch latch(2); + AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&latch](auto args) { + latch.CountDown(); + })); + + RunEngine(shell.get(), std::move(configuration)); + + latch.Wait(); + + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell)); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, LastEntrypoint) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + std::string entry_point = "fixturesAreFunctionalMain"; + configuration.SetEntrypoint(entry_point); + + fml::AutoResetWaitableEvent main_latch; + std::string last_entry_point; + AddNativeCallback( + "SayHiFromFixturesAreFunctionalMain", CREATE_NATIVE_ENTRY([&](auto args) { + last_entry_point = shell->GetEngine()->GetLastEntrypoint(); + main_latch.Signal(); + })); + + RunEngine(shell.get(), std::move(configuration)); + main_latch.Wait(); + EXPECT_EQ(entry_point, last_entry_point); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell)); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, LastEntrypointArgs) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + std::string entry_point = "fixturesAreFunctionalMain"; + std::vector entry_point_args = {"arg1"}; + configuration.SetEntrypoint(entry_point); + configuration.SetEntrypointArgs(entry_point_args); + + fml::AutoResetWaitableEvent main_latch; + std::vector last_entry_point_args; + AddNativeCallback( + "SayHiFromFixturesAreFunctionalMain", CREATE_NATIVE_ENTRY([&](auto args) { + last_entry_point_args = shell->GetEngine()->GetLastEntrypointArgs(); + main_latch.Signal(); + })); + + RunEngine(shell.get(), std::move(configuration)); + main_latch.Wait(); +#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) + EXPECT_EQ(last_entry_point_args, entry_point_args); +#else + ASSERT_TRUE(last_entry_point_args.empty()); +#endif + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell)); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, DisallowedDartVMFlag) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "This test flakes on Fuchsia. https://fxbug.dev/110006 "; +#else + + // Run this test in a thread-safe manner, otherwise gtest will complain. + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + + const std::vector options = { + fml::CommandLine::Option("dart-flags", "--verify_after_gc")}; + fml::CommandLine command_line("", options, std::vector()); + + // Upon encountering a disallowed Dart flag the process terminates. + const char* expected = + "Encountered disallowed Dart VM flag: --verify_after_gc"; + ASSERT_DEATH(flutter::SettingsFromCommandLine(command_line), expected); +#endif // OS_FUCHSIA +} + +TEST_F(ShellTest, AllowedDartVMFlag) { + std::vector flags = { + "--enable-isolate-groups", + "--no-enable-isolate-groups", + }; +#if !FLUTTER_RELEASE + flags.push_back("--max_profile_depth 1"); + flags.push_back("--random_seed 42"); + flags.push_back("--max_subtype_cache_entries=22"); + if (!DartVM::IsRunningPrecompiledCode()) { + flags.push_back("--enable_mirrors"); + } +#endif + + TestDartVmFlags(flags); +} + +TEST_F(ShellTest, NoNeedToReportTimingsByDefault) { + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + ASSERT_FALSE(GetNeedsReportTimings(shell.get())); + + // This assertion may or may not be the direct result of needs_report_timings_ + // being false. The count could be 0 simply because we just cleared + // unreported timings by reporting them. Hence this can't replace the + // ASSERT_FALSE(GetNeedsReportTimings(shell.get())) check. We added + // this assertion for an additional confidence that we're not pushing + // back to unreported timings unnecessarily. + // + // Conversely, do not assert UnreportedTimingsCount(shell.get()) to be + // positive in any tests. Otherwise those tests will be flaky as the clearing + // of unreported timings is unpredictive. + ASSERT_EQ(UnreportedTimingsCount(shell.get()), 0); + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, NeedsReportTimingsIsSetWithCallback) { + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("dummyReportTimingsMain"); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + ASSERT_TRUE(GetNeedsReportTimings(shell.get())); + DestroyShell(std::move(shell)); +} + +static void CheckFrameTimings(const std::vector& timings, + fml::TimePoint start, + fml::TimePoint finish) { + fml::TimePoint last_frame_start; + for (size_t i = 0; i < timings.size(); i += 1) { + // Ensure that timings are sorted. + ASSERT_TRUE(timings[i].Get(FrameTiming::kPhases[0]) >= last_frame_start); + last_frame_start = timings[i].Get(FrameTiming::kPhases[0]); + + fml::TimePoint last_phase_time; + for (auto phase : FrameTiming::kPhases) { + // raster finish wall time doesn't use the same clock base + // as rest of the frame timings. + if (phase == FrameTiming::kRasterFinishWallTime) { + continue; + } + + ASSERT_TRUE(timings[i].Get(phase) >= start); + ASSERT_TRUE(timings[i].Get(phase) <= finish); + + // phases should have weakly increasing time points + ASSERT_TRUE(last_phase_time <= timings[i].Get(phase)); + last_phase_time = timings[i].Get(phase); + } + } +} + +TEST_F(ShellTest, ReportTimingsIsCalled) { + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + // We MUST put |start| after |CreateShell| because the clock source will be + // reset through |TimePoint::SetClockSource()| in + // |DartVMInitializer::Initialize()| within |CreateShell()|. + fml::TimePoint start = fml::TimePoint::Now(); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + configuration.SetEntrypoint("reportTimingsMain"); + fml::AutoResetWaitableEvent reportLatch; + std::vector timestamps; + auto nativeTimingCallback = [&reportLatch, + ×tamps](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + ASSERT_EQ(timestamps.size(), 0ul); + timestamps = tonic::DartConverter>::FromArguments( + args, 0, exception); + reportLatch.Signal(); + }; + AddNativeCallback("NativeReportTimingsCallback", + CREATE_NATIVE_ENTRY(nativeTimingCallback)); + RunEngine(shell.get(), std::move(configuration)); + + // Pump many frames so we can trigger the report quickly instead of waiting + // for the 1 second threshold. + for (int i = 0; i < 200; i += 1) { + PumpOneFrame(shell.get()); + } + + reportLatch.Wait(); + DestroyShell(std::move(shell)); + + fml::TimePoint finish = fml::TimePoint::Now(); + ASSERT_TRUE(!timestamps.empty()); + ASSERT_TRUE(timestamps.size() % FrameTiming::kCount == 0); + std::vector timings(timestamps.size() / FrameTiming::kCount); + + for (size_t i = 0; i * FrameTiming::kCount < timestamps.size(); i += 1) { + for (auto phase : FrameTiming::kPhases) { + timings[i].Set( + phase, + fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromMicroseconds( + timestamps[i * FrameTiming::kCount + phase]))); + } + } + CheckFrameTimings(timings, start, finish); +} + +TEST_F(ShellTest, FrameRasterizedCallbackIsCalled) { + auto settings = CreateSettingsForFixture(); + + FrameTiming timing; + fml::AutoResetWaitableEvent timingLatch; + settings.frame_rasterized_callback = [&timing, + &timingLatch](const FrameTiming& t) { + timing = t; + timingLatch.Signal(); + }; + + std::unique_ptr shell = CreateShell(settings); + + // Wait to make |start| bigger than zero + using namespace std::chrono_literals; + std::this_thread::sleep_for(1ms); + + // We MUST put |start| after |CreateShell()| because the clock source will be + // reset through |TimePoint::SetClockSource()| in + // |DartVMInitializer::Initialize()| within |CreateShell()|. + fml::TimePoint start = fml::TimePoint::Now(); + + for (auto phase : FrameTiming::kPhases) { + timing.Set(phase, fml::TimePoint()); + // Check that the time points are initially smaller than start, so + // CheckFrameTimings will fail if they're not properly set later. + ASSERT_TRUE(timing.Get(phase) < start); + } + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("onBeginFrameMain"); + + int64_t frame_target_time; + auto nativeOnBeginFrame = [&frame_target_time](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + frame_target_time = + tonic::DartConverter::FromArguments(args, 0, exception); + }; + AddNativeCallback("NativeOnBeginFrame", + CREATE_NATIVE_ENTRY(nativeOnBeginFrame)); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + // Check that timing is properly set. This implies that + // settings.frame_rasterized_callback is called. + timingLatch.Wait(); + fml::TimePoint finish = fml::TimePoint::Now(); + std::vector timings = {timing}; + CheckFrameTimings(timings, start, finish); + + // Check that onBeginFrame, which is the frame_target_time, is after + // FrameTiming's build start + int64_t build_start = + timing.Get(FrameTiming::kBuildStart).ToEpochDelta().ToMicroseconds(); + ASSERT_GT(frame_target_time, build_start); + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, ExternalEmbedderNoThreadMerger) { + auto settings = CreateSettingsForFixture(); + fml::AutoResetWaitableEvent end_frame_latch; + bool end_frame_called = false; + auto end_frame_callback = + [&](bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + ASSERT_TRUE(raster_thread_merger.get() == nullptr); + ASSERT_FALSE(should_resubmit_frame); + end_frame_called = true; + end_frame_latch.Signal(); + }; + auto external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kResubmitFrame, false); + auto shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + end_frame_latch.Wait(); + ASSERT_TRUE(end_frame_called); + + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, PushBackdropFilterToVisitedPlatformViews) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. " + "https://github.com/flutter/flutter/issues/59816 "; +#else + + auto settings = CreateSettingsForFixture(); + + std::shared_ptr external_view_embedder; + + fml::AutoResetWaitableEvent end_frame_latch; + bool end_frame_called = false; + std::vector visited_platform_views; + MutatorsStack stack_50; + MutatorsStack stack_75; + auto end_frame_callback = + [&](bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + if (end_frame_called) { + return; + } + ASSERT_TRUE(raster_thread_merger.get() == nullptr); + ASSERT_FALSE(should_resubmit_frame); + end_frame_called = true; + visited_platform_views = + external_view_embedder->GetVisitedPlatformViews(); + stack_50 = external_view_embedder->GetStack(50); + stack_75 = external_view_embedder->GetStack(75); + end_frame_latch.Signal(); + }; + + external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kResubmitFrame, false); + auto shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto platform_view_layer = std::make_shared( + DlPoint(10, 10), DlSize(10, 10), 50); + root->Add(platform_view_layer); + auto transform_layer = std::make_shared( + DlMatrix::MakeTranslation({1.0f, 1.0f})); + root->Add(transform_layer); + auto clip_rect_layer = std::make_shared( + DlRect::MakeLTRB(0, 0, 30, 30), Clip::kHardEdge); + transform_layer->Add(clip_rect_layer); + auto filter = DlImageFilter::MakeBlur(5, 5, DlTileMode::kClamp); + auto backdrop_filter_layer = + std::make_shared(filter, DlBlendMode::kSrcOver); + clip_rect_layer->Add(backdrop_filter_layer); + auto platform_view_layer2 = std::make_shared( + DlPoint(10, 10), DlSize(10, 10), 75); + backdrop_filter_layer->Add(platform_view_layer2); + }; + + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + end_frame_latch.Wait(); + ASSERT_EQ(visited_platform_views, (std::vector{50, 75})); + ASSERT_TRUE(stack_75.is_empty()); + ASSERT_FALSE(stack_50.is_empty()); + + auto filter = DlImageFilter::MakeBlur(5, 5, DlTileMode::kClamp); + auto mutator = *stack_50.Begin(); + ASSERT_EQ(mutator->GetType(), MutatorType::kBackdropFilter); + ASSERT_EQ(mutator->GetFilterMutation().GetFilter(), *filter); + // Make sure the filterRect is in global coordinates (contains the (1,1) + // translation). + ASSERT_EQ(mutator->GetFilterMutation().GetFilterRect(), + DlRect::MakeLTRB(1, 1, 31, 31)); + + DestroyShell(std::move(shell)); +#endif // OS_FUCHSIA +} + +// TODO(https://github.com/flutter/flutter/issues/59816): Enable on fuchsia. +TEST_F(ShellTest, + ExternalEmbedderEndFrameIsCalledWhenPostPrerollResultIsResubmit) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. " + "https://github.com/flutter/flutter/issues/59816 "; +#else + + auto settings = CreateSettingsForFixture(); + fml::AutoResetWaitableEvent end_frame_latch; + bool end_frame_called = false; + auto end_frame_callback = + [&](bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + ASSERT_TRUE(raster_thread_merger.get() != nullptr); + ASSERT_TRUE(should_resubmit_frame); + end_frame_called = true; + end_frame_latch.Signal(); + }; + auto external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kResubmitFrame, true); + auto shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + end_frame_latch.Wait(); + + ASSERT_TRUE(end_frame_called); + + DestroyShell(std::move(shell)); +#endif // OS_FUCHSIA +} + +TEST_F(ShellTest, OnPlatformViewDestroyDisablesThreadMerger) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. " + "https://github.com/flutter/flutter/issues/59816 "; +#else + + auto settings = CreateSettingsForFixture(); + fml::RefPtr raster_thread_merger; + auto end_frame_callback = + [&](bool should_resubmit_frame, + fml::RefPtr thread_merger) { + raster_thread_merger = std::move(thread_merger); + }; + auto external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kSuccess, true); + + auto shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + + auto result = shell->WaitForFirstFrame(fml::TimeDelta::Max()); + // Wait for the rasterizer to process the frame. WaitForFirstFrame only waits + // for the Animator, but end_frame_callback is called by the Rasterizer. + PostSync(shell->GetTaskRunners().GetRasterTaskRunner(), [] {}); + ASSERT_TRUE(result.ok()) << "Result: " << static_cast(result.code()) + << ": " << result.message(); + + ASSERT_TRUE(raster_thread_merger->IsEnabled()); + + ValidateDestroyPlatformView(shell.get()); + ASSERT_TRUE(raster_thread_merger->IsEnabled()); + + // Validate the platform view can be recreated and destroyed again + ValidateShell(shell.get()); + ASSERT_TRUE(raster_thread_merger->IsEnabled()); + DestroyShell(std::move(shell)); +#endif // OS_FUCHSIA +} + +TEST_F(ShellTest, OnPlatformViewDestroyAfterMergingThreads) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. " + "https://github.com/flutter/flutter/issues/59816 "; +#else + + const int ThreadMergingLease = 10; + auto settings = CreateSettingsForFixture(); + fml::AutoResetWaitableEvent end_frame_latch; + std::shared_ptr external_view_embedder; + + auto end_frame_callback = + [&](bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + if (should_resubmit_frame && !raster_thread_merger->IsMerged()) { + raster_thread_merger->MergeWithLease(ThreadMergingLease); + + ASSERT_TRUE(raster_thread_merger->IsMerged()); + external_view_embedder->UpdatePostPrerollResult( + PostPrerollResult::kSuccess); + } + end_frame_latch.Signal(); + }; + external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kSuccess, true); + // Set resubmit once to trigger thread merging. + external_view_embedder->UpdatePostPrerollResult( + PostPrerollResult::kResubmitFrame); + auto shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + // Pump one frame to trigger thread merging. + end_frame_latch.Wait(); + // Pump another frame to ensure threads are merged and a regular layer tree is + // submitted. + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + // Threads are merged here. PlatformViewNotifyDestroy should be executed + // successfully. + ASSERT_TRUE(fml::TaskRunnerChecker::RunsOnTheSameThread( + shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(), + shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId())); + ValidateDestroyPlatformView(shell.get()); + + // Ensure threads are unmerged after platform view destroy + ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread( + shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(), + shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId())); + + // Validate the platform view can be recreated and destroyed again + ValidateShell(shell.get()); + + DestroyShell(std::move(shell)); +#endif // OS_FUCHSIA +} + +TEST_F(ShellTest, OnPlatformViewDestroyWhenThreadsAreMerging) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. " + "https://github.com/flutter/flutter/issues/59816 "; +#else + + const int kThreadMergingLease = 10; + auto settings = CreateSettingsForFixture(); + fml::AutoResetWaitableEvent end_frame_latch; + auto end_frame_callback = + [&](bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + if (should_resubmit_frame && !raster_thread_merger->IsMerged()) { + raster_thread_merger->MergeWithLease(kThreadMergingLease); + } + end_frame_latch.Signal(); + }; + // Start with a regular layer tree with `PostPrerollResult::kSuccess` so we + // can later check if the rasterizer is tore down using + // |ValidateDestroyPlatformView| + auto external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kSuccess, true); + + auto shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + // Pump one frame and threads aren't merged + end_frame_latch.Wait(); + ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread( + shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(), + shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId())); + + // Pump a frame with `PostPrerollResult::kResubmitFrame` to start merging + // threads + external_view_embedder->UpdatePostPrerollResult( + PostPrerollResult::kResubmitFrame); + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + + // Now destroy the platform view immediately. + // Two things can happen here: + // 1. Threads haven't merged. 2. Threads has already merged. + // |Shell:OnPlatformViewDestroy| should be able to handle both cases. + ValidateDestroyPlatformView(shell.get()); + + // Ensure threads are unmerged after platform view destroy + ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread( + shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(), + shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId())); + + // Validate the platform view can be recreated and destroyed again + ValidateShell(shell.get()); + + DestroyShell(std::move(shell)); +#endif // OS_FUCHSIA +} + +TEST_F(ShellTest, + OnPlatformViewDestroyWithThreadMergerWhileThreadsAreUnmerged) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. " + "https://github.com/flutter/flutter/issues/59816 "; +#else + + auto settings = CreateSettingsForFixture(); + fml::AutoResetWaitableEvent end_frame_latch; + auto end_frame_callback = + [&](bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + end_frame_latch.Signal(); + }; + auto external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kSuccess, true); + auto shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + end_frame_latch.Wait(); + + // Threads should not be merged. + ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread( + shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(), + shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId())); + ValidateDestroyPlatformView(shell.get()); + + // Ensure threads are unmerged after platform view destroy + ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread( + shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(), + shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId())); + + // Validate the platform view can be recreated and destroyed again + ValidateShell(shell.get()); + + DestroyShell(std::move(shell)); +#endif // OS_FUCHSIA +} + +TEST_F(ShellTest, OnPlatformViewDestroyWithoutRasterThreadMerger) { + auto settings = CreateSettingsForFixture(); + + auto shell = CreateShell(settings); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + + // Threads should not be merged. + ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread( + shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(), + shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId())); + ValidateDestroyPlatformView(shell.get()); + + // Ensure threads are unmerged after platform view destroy + ASSERT_FALSE(fml::TaskRunnerChecker::RunsOnTheSameThread( + shell->GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId(), + shell->GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId())); + + // Validate the platform view can be recreated and destroyed again + ValidateShell(shell.get()); + + DestroyShell(std::move(shell)); +} + +// TODO(https://github.com/flutter/flutter/issues/59816): Enable on fuchsia. +TEST_F(ShellTest, OnPlatformViewDestroyWithStaticThreadMerging) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. " + "https://github.com/flutter/flutter/issues/59816 "; +#else + + auto settings = CreateSettingsForFixture(); + fml::AutoResetWaitableEvent end_frame_latch; + auto end_frame_callback = + [&](bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + end_frame_latch.Signal(); + }; + auto external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kSuccess, true); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kIo | + ThreadHost::Type::kUi); + TaskRunners task_runners( + "test", + thread_host.platform_thread->GetTaskRunner(), // platform + thread_host.platform_thread->GetTaskRunner(), // raster + thread_host.ui_thread->GetTaskRunner(), // ui + thread_host.io_thread->GetTaskRunner() // io + ); + auto shell = CreateShell({ + .settings = settings, + .task_runners = task_runners, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + end_frame_latch.Wait(); + + ValidateDestroyPlatformView(shell.get()); + + // Validate the platform view can be recreated and destroyed again + ValidateShell(shell.get()); + + DestroyShell(std::move(shell), task_runners); +#endif // OS_FUCHSIA +} + +TEST_F(ShellTest, GetUsedThisFrameShouldBeSetBeforeEndFrame) { + auto settings = CreateSettingsForFixture(); + fml::AutoResetWaitableEvent end_frame_latch; + std::shared_ptr external_view_embedder; + bool used_this_frame = true; + auto end_frame_callback = + [&](bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + // We expect `used_this_frame` to be false. + used_this_frame = external_view_embedder->GetUsedThisFrame(); + end_frame_latch.Signal(); + }; + external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kSuccess, true); + auto shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + end_frame_latch.Wait(); + ASSERT_FALSE(used_this_frame); + + // Validate the platform view can be recreated and destroyed again + ValidateShell(shell.get()); + + DestroyShell(std::move(shell)); +} + +// TODO(https://github.com/flutter/flutter/issues/66056): Deflake on all other +// platforms +TEST_F(ShellTest, DISABLED_SkipAndSubmitFrame) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "RasterThreadMerger flakes on Fuchsia. " + "https://github.com/flutter/flutter/issues/59816 "; +#else + + auto settings = CreateSettingsForFixture(); + fml::AutoResetWaitableEvent end_frame_latch; + std::shared_ptr external_view_embedder; + + auto end_frame_callback = + [&](bool should_resubmit_frame, + const fml::RefPtr& raster_thread_merger) { + if (should_resubmit_frame && !raster_thread_merger->IsMerged()) { + raster_thread_merger->MergeWithLease(10); + external_view_embedder->UpdatePostPrerollResult( + PostPrerollResult::kSuccess); + } + end_frame_latch.Signal(); + }; + external_view_embedder = std::make_shared( + end_frame_callback, PostPrerollResult::kSkipAndRetryFrame, true); + + auto shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + RunEngine(shell.get(), std::move(configuration)); + + ASSERT_EQ(0, external_view_embedder->GetSubmittedFrameCount()); + + PumpOneFrame(shell.get()); + + // `EndFrame` changed the post preroll result to `kSuccess`. + end_frame_latch.Wait(); + + // Let the resubmitted frame to run and `GetSubmittedFrameCount` should be + // called. + end_frame_latch.Wait(); + // 2 frames are submitted because `kSkipAndRetryFrame`, but only the 2nd frame + // should be submitted with `external_view_embedder`, hence the below check. + ASSERT_EQ(1, external_view_embedder->GetSubmittedFrameCount()); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +#endif // OS_FUCHSIA +} + +TEST(SettingsTest, FrameTimingSetsAndGetsProperly) { + // Ensure that all phases are in kPhases. + ASSERT_EQ(sizeof(FrameTiming::kPhases), + FrameTiming::kCount * sizeof(FrameTiming::Phase)); + + int lastPhaseIndex = -1; + FrameTiming timing; + for (auto phase : FrameTiming::kPhases) { + ASSERT_TRUE(phase > lastPhaseIndex); // Ensure that kPhases are in order. + lastPhaseIndex = phase; + auto fake_time = + fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromMicroseconds(phase)); + timing.Set(phase, fake_time); + ASSERT_TRUE(timing.Get(phase) == fake_time); + } +} + +TEST_F(ShellTest, ReportTimingsIsCalledImmediatelyAfterTheFirstFrame) { + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + configuration.SetEntrypoint("reportTimingsMain"); + fml::AutoResetWaitableEvent reportLatch; + std::vector timestamps; + auto nativeTimingCallback = [&reportLatch, + ×tamps](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + ASSERT_EQ(timestamps.size(), 0ul); + timestamps = tonic::DartConverter>::FromArguments( + args, 0, exception); + reportLatch.Signal(); + }; + AddNativeCallback("NativeReportTimingsCallback", + CREATE_NATIVE_ENTRY(nativeTimingCallback)); + ASSERT_TRUE(configuration.IsValid()); + RunEngine(shell.get(), std::move(configuration)); + + for (int i = 0; i < 10; i += 1) { + PumpOneFrame(shell.get()); + } + + reportLatch.Wait(); + DestroyShell(std::move(shell)); + + // Check for the immediate callback of the first frame that doesn't wait for + // the other 9 frames to be rasterized. + ASSERT_EQ(timestamps.size(), FrameTiming::kCount); +} + +TEST_F(ShellTest, WaitForFirstFrame) { + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Max()); + ASSERT_TRUE(result.ok()); + + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, WaitForFirstFrameZeroSizeFrame) { + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get(), ViewContent::DummyView({1.0, 0.0, 0.0, 22, 0})); + fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Zero()); + EXPECT_FALSE(result.ok()); + EXPECT_EQ(result.message(), "timeout"); + EXPECT_EQ(result.code(), fml::StatusCode::kDeadlineExceeded); + + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, WaitForFirstFrameTimeout) { + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Zero()); + ASSERT_FALSE(result.ok()); + ASSERT_EQ(result.code(), fml::StatusCode::kDeadlineExceeded); + + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, WaitForFirstFrameMultiple) { + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Max()); + ASSERT_TRUE(result.ok()); + for (int i = 0; i < 100; ++i) { + result = shell->WaitForFirstFrame(fml::TimeDelta::Zero()); + ASSERT_TRUE(result.ok()); + } + + DestroyShell(std::move(shell)); +} + +/// Makes sure that WaitForFirstFrame works if we rendered a frame with the +/// single-thread setup. +TEST_F(ShellTest, WaitForFirstFrameInlined) { + Settings settings = CreateSettingsForFixture(); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + std::unique_ptr shell = CreateShell(settings, task_runners); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + fml::AutoResetWaitableEvent event; + task_runner->PostTask([&shell, &event] { + fml::Status result = shell->WaitForFirstFrame(fml::TimeDelta::Max()); + ASSERT_FALSE(result.ok()); + ASSERT_EQ(result.code(), fml::StatusCode::kFailedPrecondition); + event.Signal(); + }); + ASSERT_FALSE(event.WaitWithTimeout(fml::TimeDelta::Max())); + + DestroyShell(std::move(shell), task_runners); +} + +static size_t GetRasterizerResourceCacheBytesSync(const Shell& shell) { + size_t bytes = 0; + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + shell.GetTaskRunners().GetRasterTaskRunner(), [&]() { + if (auto rasterizer = shell.GetRasterizer()) { + bytes = rasterizer->GetResourceCacheMaxBytes().value_or(0U); + } + latch.Signal(); + }); + latch.Wait(); + return bytes; +} + +TEST_F(ShellTest, MultipleFluttersSetResourceCacheBytes) { + TaskRunners task_runners = GetTaskRunnersForFixture(); + auto settings = CreateSettingsForFixture(); + settings.resource_cache_max_bytes_threshold = 4000000U; + GrMockOptions main_context_options; + sk_sp main_context = + GrDirectContext::MakeMock(&main_context_options); + Shell::CreateCallback platform_view_create_callback = + [task_runners, main_context](flutter::Shell& shell) { + auto result = std::make_unique(shell, task_runners); + ON_CALL(*result, CreateRenderingSurface()) + .WillByDefault(::testing::Invoke([main_context] { + auto surface = std::make_unique(); + ON_CALL(*surface, GetContext()) + .WillByDefault(Return(main_context.get())); + ON_CALL(*surface, IsValid()).WillByDefault(Return(true)); + ON_CALL(*surface, MakeRenderContextCurrent()) + .WillByDefault(::testing::Invoke([] { + return std::make_unique(true); + })); + return surface; + })); + return result; + }; + + auto shell = CreateShell({ + .settings = settings, + .task_runners = task_runners, + .platform_view_create_callback = platform_view_create_callback, + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() { + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {1.0, 100, 100, 22, 0}); + }); + + // first cache bytes + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(480000U)); + + auto shell_spawn_callback = [&]() { + std::unique_ptr spawn; + PostSync( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [this, &spawn, &spawner = shell, platform_view_create_callback]() { + auto configuration = + RunConfiguration::InferFromSettings(CreateSettingsForFixture()); + configuration.SetEntrypoint("emptyMain"); + spawn = spawner->Spawn( + std::move(configuration), "", platform_view_create_callback, + [](Shell& shell) { return std::make_unique(shell); }); + ASSERT_NE(nullptr, spawn.get()); + ASSERT_TRUE(ValidateShell(spawn.get())); + }); + return spawn; + }; + + std::unique_ptr second_shell = shell_spawn_callback(); + PlatformViewNotifyCreated(second_shell.get()); + PostSync(second_shell->GetTaskRunners().GetPlatformTaskRunner(), + [&second_shell]() { + second_shell->GetPlatformView()->SetViewportMetrics( + kImplicitViewId, {1.0, 100, 100, 22, 0}); + }); + // first cache bytes + second cache bytes + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(960000U)); + + PostSync(second_shell->GetTaskRunners().GetPlatformTaskRunner(), + [&second_shell]() { + second_shell->GetPlatformView()->SetViewportMetrics( + kImplicitViewId, {1.0, 100, 300, 22, 0}); + }); + // first cache bytes + second cache bytes + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(1920000U)); + + std::unique_ptr third_shell = shell_spawn_callback(); + PlatformViewNotifyCreated(third_shell.get()); + PostSync(third_shell->GetTaskRunners().GetPlatformTaskRunner(), + [&third_shell]() { + third_shell->GetPlatformView()->SetViewportMetrics( + kImplicitViewId, {1.0, 400, 100, 22, 0}); + }); + // first cache bytes + second cache bytes + third cache bytes + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(3840000U)); + + PostSync(third_shell->GetTaskRunners().GetPlatformTaskRunner(), + [&third_shell]() { + third_shell->GetPlatformView()->SetViewportMetrics( + kImplicitViewId, {1.0, 800, 100, 22, 0}); + }); + // max bytes threshold + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(4000000U)); + DestroyShell(std::move(third_shell), task_runners); + // max bytes threshold + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(4000000U)); + + PostSync(second_shell->GetTaskRunners().GetPlatformTaskRunner(), + [&second_shell]() { + second_shell->GetPlatformView()->SetViewportMetrics( + kImplicitViewId, {1.0, 100, 100, 22, 0}); + }); + // first cache bytes + second cache bytes + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(960000U)); + + DestroyShell(std::move(second_shell), task_runners); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, SetResourceCacheSize) { + Settings settings = CreateSettingsForFixture(); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + std::unique_ptr shell = CreateShell(settings, task_runners); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + // The Vulkan and GL backends set different default values for the resource + // cache size. The default backend (specified by the default param of + // `CreateShell` in this test) will only resolve to Vulkan (in + // `ShellTestPlatformView::Create`) if GL is disabled. This situation arises + // when targeting the Fuchsia Emulator. +#if defined(SHELL_ENABLE_VULKAN) && !defined(SHELL_ENABLE_GL) + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + vulkan::kGrCacheMaxByteSize); +#elif defined(SHELL_ENABLE_METAL) + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(256 * (1 << 20))); +#else + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(24 * (1 << 20))); +#endif + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() { + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {1.0, 400, 200, 22, 0}); + }); + PumpOneFrame(shell.get()); + + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), 3840000U); + + std::string request_json = R"json({ + "method": "Skia.setResourceCacheMaxBytes", + "args": 10000 + })json"; + auto data = + fml::MallocMapping::Copy(request_json.c_str(), request_json.length()); + auto platform_message = std::make_unique( + "flutter/skia", std::move(data), nullptr); + SendEnginePlatformMessage(shell.get(), std::move(platform_message)); + PumpOneFrame(shell.get()); + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), 10000U); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() { + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {1.0, 800, 400, 22, 0}); + }); + PumpOneFrame(shell.get()); + + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), 10000U); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, SetResourceCacheSizeEarly) { + Settings settings = CreateSettingsForFixture(); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + std::unique_ptr shell = CreateShell(settings, task_runners); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() { + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {1.0, 400, 200, 22, 0}); + }); + PumpOneFrame(shell.get()); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(3840000U)); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, SetResourceCacheSizeNotifiesDart) { + Settings settings = CreateSettingsForFixture(); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + std::unique_ptr shell = CreateShell(settings, task_runners); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() { + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {1.0, 400, 200, 22, 0}); + }); + PumpOneFrame(shell.get()); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testSkiaResourceCacheSendsResponse"); + + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(3840000U)); + + fml::AutoResetWaitableEvent latch; + AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&latch](auto args) { + latch.Signal(); + })); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + latch.Wait(); + + EXPECT_EQ(GetRasterizerResourceCacheBytesSync(*shell), + static_cast(10000U)); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, CanCreateImagefromDecompressedBytes) { + Settings settings = CreateSettingsForFixture(); + auto task_runner = CreateNewThread(); + + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + + std::unique_ptr shell = CreateShell(settings, task_runners); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("canCreateImageFromDecompressedData"); + + fml::AutoResetWaitableEvent latch; + AddNativeCallback("NotifyWidthHeight", + CREATE_NATIVE_ENTRY([&latch](auto args) { + auto width = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + auto height = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 1)); + ASSERT_EQ(width, 10); + ASSERT_EQ(height, 10); + latch.Signal(); + })); + + RunEngine(shell.get(), std::move(configuration)); + + latch.Wait(); + DestroyShell(std::move(shell), task_runners); +} + +class MockTexture : public Texture { + public: + MockTexture(int64_t textureId, + std::shared_ptr latch) + : Texture(textureId), latch_(std::move(latch)) {} + + ~MockTexture() override = default; + + // Called from raster thread. + void Paint(PaintContext& context, + const DlRect& bounds, + bool freeze, + const DlImageSampling) override {} + + void OnGrContextCreated() override {} + + void OnGrContextDestroyed() override {} + + void MarkNewFrameAvailable() override { + frames_available_++; + latch_->Signal(); + } + + void OnTextureUnregistered() override { + unregistered_ = true; + latch_->Signal(); + } + + bool unregistered() { return unregistered_; } + int frames_available() { return frames_available_; } + + private: + bool unregistered_ = false; + int frames_available_ = 0; + std::shared_ptr latch_; +}; + +TEST_F(ShellTest, TextureFrameMarkedAvailableAndUnregister) { + Settings settings = CreateSettingsForFixture(); + auto configuration = RunConfiguration::InferFromSettings(settings); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + std::unique_ptr shell = CreateShell(settings, task_runners); + + ASSERT_TRUE(ValidateShell(shell.get())); + PlatformViewNotifyCreated(shell.get()); + + RunEngine(shell.get(), std::move(configuration)); + + std::shared_ptr latch = + std::make_shared(); + + std::shared_ptr mockTexture = + std::make_shared(0, latch); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetRasterTaskRunner(), [&]() { + shell->GetPlatformView()->RegisterTexture(mockTexture); + shell->GetPlatformView()->MarkTextureFrameAvailable(0); + }); + latch->Wait(); + + EXPECT_EQ(mockTexture->frames_available(), 1); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetRasterTaskRunner(), + [&]() { shell->GetPlatformView()->UnregisterTexture(0); }); + latch->Wait(); + + EXPECT_EQ(mockTexture->unregistered(), true); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, IsolateCanAccessPersistentIsolateData) { + const std::string message = "dummy isolate launch data."; + + Settings settings = CreateSettingsForFixture(); + settings.persistent_isolate_data = + std::make_shared(message); + TaskRunners task_runners("test", // label + GetCurrentTaskRunner(), // platform + CreateNewThread(), // raster + CreateNewThread(), // ui + CreateNewThread() // io + ); + + fml::AutoResetWaitableEvent message_latch; + AddNativeCallback("NotifyMessage", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + const auto message_from_dart = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + ASSERT_EQ(message, message_from_dart); + message_latch.Signal(); + })); + + std::unique_ptr shell = CreateShell(settings, task_runners); + + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("canAccessIsolateLaunchData"); + + fml::AutoResetWaitableEvent event; + shell->RunEngine(std::move(configuration), [&](auto result) { + ASSERT_EQ(result, Engine::RunStatus::Success); + }); + + message_latch.Wait(); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, CanScheduleFrameFromPlatform) { + Settings settings = CreateSettingsForFixture(); + TaskRunners task_runners = GetTaskRunnersForFixture(); + fml::AutoResetWaitableEvent latch; + AddNativeCallback( + "NotifyNative", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + fml::AutoResetWaitableEvent check_latch; + AddNativeCallback("NativeOnBeginFrame", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + check_latch.Signal(); + })); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell->IsSetup()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("onBeginFrameWithNotifyNativeMain"); + RunEngine(shell.get(), std::move(configuration)); + + // Wait for the application to attach the listener. + latch.Wait(); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [&shell]() { shell->GetPlatformView()->ScheduleFrame(); }); + check_latch.Wait(); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, SecondaryVsyncCallbackShouldBeCalledAfterVsyncCallback) { + bool is_on_begin_frame_called = false; + bool is_secondary_callback_called = false; + bool test_started = false; + Settings settings = CreateSettingsForFixture(); + TaskRunners task_runners = GetTaskRunnersForFixture(); + fml::AutoResetWaitableEvent latch; + AddNativeCallback( + "NotifyNative", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + fml::CountDownLatch count_down_latch(2); + AddNativeCallback("NativeOnBeginFrame", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + if (!test_started) { + return; + } + EXPECT_FALSE(is_on_begin_frame_called); + EXPECT_FALSE(is_secondary_callback_called); + is_on_begin_frame_called = true; + count_down_latch.CountDown(); + })); + std::unique_ptr shell = CreateShell({ + .settings = settings, + .task_runners = task_runners, + }); + ASSERT_TRUE(shell->IsSetup()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("onBeginFrameWithNotifyNativeMain"); + RunEngine(shell.get(), std::move(configuration)); + + // Wait for the application to attach the listener. + latch.Wait(); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetUITaskRunner(), [&]() { + shell->GetEngine()->ScheduleSecondaryVsyncCallback(0, [&]() { + if (!test_started) { + return; + } + EXPECT_TRUE(is_on_begin_frame_called); + EXPECT_FALSE(is_secondary_callback_called); + is_secondary_callback_called = true; + count_down_latch.CountDown(); + }); + shell->GetEngine()->ScheduleFrame(); + test_started = true; + }); + count_down_latch.Wait(); + EXPECT_TRUE(is_on_begin_frame_called); + EXPECT_TRUE(is_secondary_callback_called); + DestroyShell(std::move(shell), task_runners); +} + +static void LogSkData(const sk_sp& data, const char* title) { + FML_LOG(ERROR) << "---------- " << title; + std::ostringstream ostr; + for (size_t i = 0; i < data->size();) { + ostr << std::hex << std::setfill('0') << std::setw(2) + << static_cast(data->bytes()[i]) << " "; + i++; + if (i % 16 == 0 || i == data->size()) { + FML_LOG(ERROR) << ostr.str(); + ostr.str(""); + ostr.clear(); + } + } +} + +TEST_F(ShellTest, Screenshot) { + auto settings = CreateSettingsForFixture(); + fml::AutoResetWaitableEvent firstFrameLatch; + settings.frame_rasterized_callback = + [&firstFrameLatch](const FrameTiming& t) { firstFrameLatch.Signal(); }; + + std::unique_ptr shell = CreateShell(settings); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + LayerTreeBuilder builder = [&](const std::shared_ptr& root) { + auto display_list_layer = std::make_shared( + DlPoint(10, 10), MakeSizedDisplayList(80, 80), false, false); + root->Add(display_list_layer); + }; + + PumpOneFrame(shell.get(), ViewContent::ImplicitView(100, 100, builder)); + firstFrameLatch.Wait(); + + std::promise screenshot_promise; + auto screenshot_future = screenshot_promise.get_future(); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetRasterTaskRunner(), + [&screenshot_promise, &shell]() { + auto rasterizer = shell->GetRasterizer(); + screenshot_promise.set_value(rasterizer->ScreenshotLastLayerTree( + Rasterizer::ScreenshotType::CompressedImage, false)); + }); + + auto fixtures_dir = + fml::OpenDirectory(GetFixturesPath(), false, fml::FilePermission::kRead); + + auto reference_png = fml::FileMapping::CreateReadOnly( + fixtures_dir, "shelltest_screenshot.png"); + + // Use MakeWithoutCopy instead of MakeWithCString because we don't want to + // encode the null sentinel + sk_sp reference_data = SkData::MakeWithoutCopy( + reference_png->GetMapping(), reference_png->GetSize()); + + sk_sp screenshot_data = screenshot_future.get().data; + if (!reference_data->equals(screenshot_data.get())) { + LogSkData(reference_data, "reference"); + LogSkData(screenshot_data, "screenshot"); + ASSERT_TRUE(false); + } + + DestroyShell(std::move(shell)); +} + +// Compares local times as seen by the dart isolate and as seen by this test +// fixture, to a resolution of 1 hour. +// +// This verifies that (1) the isolate is able to get a timezone (doesn't lock +// up for example), and (2) that the host and the isolate agree on what the +// timezone is. +TEST_F(ShellTest, LocaltimesMatch) { + fml::AutoResetWaitableEvent latch; + std::string dart_isolate_time_str; + + // See fixtures/shell_test.dart, the callback NotifyLocalTime is declared + // there. + AddNativeCallback("NotifyLocalTime", CREATE_NATIVE_ENTRY([&](auto args) { + dart_isolate_time_str = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + latch.Signal(); + })); + + auto settings = CreateSettingsForFixture(); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("localtimesMatch"); + std::unique_ptr shell = CreateShell(settings); + ASSERT_NE(shell.get(), nullptr); + RunEngine(shell.get(), std::move(configuration)); + latch.Wait(); + + char timestr[200]; + const time_t timestamp = time(nullptr); + const struct tm* local_time = localtime(×tamp); + ASSERT_NE(local_time, nullptr) + << "Could not get local time: errno=" << errno << ": " << strerror(errno); + // Example: "2020-02-26 14" for 2pm on February 26, 2020. + const size_t format_size = + strftime(timestr, sizeof(timestr), "%Y-%m-%d %H", local_time); + ASSERT_NE(format_size, 0UL) + << "strftime failed: host time: " << std::string(timestr) + << " dart isolate time: " << dart_isolate_time_str; + + const std::string host_local_time_str = timestr; + + ASSERT_EQ(dart_isolate_time_str, host_local_time_str) + << "Local times in the dart isolate and the local time seen by the test " + << "differ by more than 1 hour, but are expected to be about equal"; + + DestroyShell(std::move(shell)); +} + +/// An image generator that always creates a 1x1 single-frame green image. +class SinglePixelImageGenerator : public ImageGenerator { + public: + SinglePixelImageGenerator() + : info_(SkImageInfo::MakeN32(1, 1, SkAlphaType::kOpaque_SkAlphaType)){}; + ~SinglePixelImageGenerator() = default; + const SkImageInfo& GetInfo() { return info_; } + + unsigned int GetFrameCount() const { return 1; } + + unsigned int GetPlayCount() const { return 1; } + + const ImageGenerator::FrameInfo GetFrameInfo(unsigned int frame_index) { + return {std::nullopt, 0, SkCodecAnimation::DisposalMethod::kKeep}; + } + + SkISize GetScaledDimensions(float scale) { + return SkISize::Make(info_.width(), info_.height()); + } + + bool GetPixels(const SkImageInfo& info, + void* pixels, + size_t row_bytes, + unsigned int frame_index, + std::optional prior_frame) { + assert(info.width() == 1); + assert(info.height() == 1); + assert(row_bytes == 4); + + reinterpret_cast(pixels)[0] = 0x00ff00ff; + return true; + }; + + private: + SkImageInfo info_; +}; + +TEST_F(ShellTest, CanRegisterImageDecoders) { + fml::AutoResetWaitableEvent latch; + AddNativeCallback("NotifyWidthHeight", CREATE_NATIVE_ENTRY([&](auto args) { + auto width = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + auto height = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 1)); + ASSERT_EQ(width, 1); + ASSERT_EQ(height, 1); + latch.Signal(); + })); + + auto settings = CreateSettingsForFixture(); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("canRegisterImageDecoders"); + std::unique_ptr shell = CreateShell(settings); + ASSERT_NE(shell.get(), nullptr); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() { + shell->RegisterImageDecoder( + [](const sk_sp& buffer) { + return std::make_unique(); + }, + 100); + }); + + RunEngine(shell.get(), std::move(configuration)); + latch.Wait(); + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, OnServiceProtocolGetSkSLsWorks) { + fml::ScopedTemporaryDirectory base_dir; + ASSERT_TRUE(base_dir.fd().is_valid()); + PersistentCache::SetCacheDirectoryPath(base_dir.path()); + PersistentCache::ResetCacheForProcess(); + + // Create 2 dummy SkSL cache file IE (base32 encoding of A), II (base32 + // encoding of B) with content x and y. + std::vector components = { + "flutter_engine", GetFlutterEngineVersion(), "skia", GetSkiaVersion(), + PersistentCache::kSkSLSubdirName}; + auto sksl_dir = fml::CreateDirectory(base_dir.fd(), components, + fml::FilePermission::kReadWrite); + const std::string x_key_str = "A"; + const std::string x_value_str = "x"; + sk_sp x_key = + SkData::MakeWithCopy(x_key_str.data(), x_key_str.size()); + sk_sp x_value = + SkData::MakeWithCopy(x_value_str.data(), x_value_str.size()); + auto x_data = PersistentCache::BuildCacheObject(*x_key, *x_value); + + const std::string y_key_str = "B"; + const std::string y_value_str = "y"; + sk_sp y_key = + SkData::MakeWithCopy(y_key_str.data(), y_key_str.size()); + sk_sp y_value = + SkData::MakeWithCopy(y_value_str.data(), y_value_str.size()); + auto y_data = PersistentCache::BuildCacheObject(*y_key, *y_value); + + ASSERT_TRUE(fml::WriteAtomically(sksl_dir, "x_cache", *x_data)); + ASSERT_TRUE(fml::WriteAtomically(sksl_dir, "y_cache", *y_data)); + + Settings settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + ServiceProtocol::Handler::ServiceProtocolMap empty_params; + rapidjson::Document document; + OnServiceProtocol(shell.get(), ServiceProtocolEnum::kGetSkSLs, + shell->GetTaskRunners().GetIOTaskRunner(), empty_params, + &document); + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + DestroyShell(std::move(shell)); + + const std::string expected_json1 = + "{\"type\":\"GetSkSLs\",\"SkSLs\":{\"II\":\"eQ==\",\"IE\":\"eA==\"}}"; + const std::string expected_json2 = + "{\"type\":\"GetSkSLs\",\"SkSLs\":{\"IE\":\"eA==\",\"II\":\"eQ==\"}}"; + bool json_is_expected = (expected_json1 == buffer.GetString()) || + (expected_json2 == buffer.GetString()); + ASSERT_TRUE(json_is_expected) << buffer.GetString() << " is not equal to " + << expected_json1 << " or " << expected_json2; +} + +TEST_F(ShellTest, RasterizerScreenshot) { + Settings settings = CreateSettingsForFixture(); + auto configuration = RunConfiguration::InferFromSettings(settings); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + std::unique_ptr shell = CreateShell(settings, task_runners); + + ASSERT_TRUE(ValidateShell(shell.get())); + PlatformViewNotifyCreated(shell.get()); + + RunEngine(shell.get(), std::move(configuration)); + + auto latch = std::make_shared(); + + PumpOneFrame(shell.get()); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetRasterTaskRunner(), [&shell, &latch]() { + Rasterizer::Screenshot screenshot = + shell->GetRasterizer()->ScreenshotLastLayerTree( + Rasterizer::ScreenshotType::CompressedImage, true); + EXPECT_NE(screenshot.data, nullptr); + + latch->Signal(); + }); + latch->Wait(); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, RasterizerMakeRasterSnapshot) { + Settings settings = CreateSettingsForFixture(); + auto configuration = RunConfiguration::InferFromSettings(settings); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + std::unique_ptr shell = CreateShell(settings, task_runners); + + ASSERT_TRUE(ValidateShell(shell.get())); + PlatformViewNotifyCreated(shell.get()); + + RunEngine(shell.get(), std::move(configuration)); + + auto latch = std::make_shared(); + + PumpOneFrame(shell.get()); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetRasterTaskRunner(), [&shell, &latch]() { + SnapshotDelegate* delegate = + reinterpret_cast(shell->GetRasterizer().get()); + sk_sp image = delegate->MakeRasterSnapshotSync( + MakeSizedDisplayList(50, 50), SkISize::Make(50, 50)); + EXPECT_NE(image, nullptr); + + latch->Signal(); + }); + latch->Wait(); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, OnServiceProtocolEstimateRasterCacheMemoryWorks) { + Settings settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + // 1. Construct a picture and a picture layer to be raster cached. + sk_sp display_list = MakeSizedDisplayList(10, 10); + auto display_list_layer = std::make_shared( + DlPoint(0, 0), MakeSizedDisplayList(100, 100), false, false); + display_list_layer->set_paint_bounds(DlRect::MakeWH(100, 100)); + + // 2. Rasterize the picture and the picture layer in the raster cache. + std::promise rasterized; + + shell->GetTaskRunners().GetRasterTaskRunner()->PostTask( + [&shell, &rasterized, &display_list, &display_list_layer] { + std::vector raster_cache_items; + auto* compositor_context = shell->GetRasterizer()->compositor_context(); + auto& raster_cache = compositor_context->raster_cache(); + + LayerStateStack state_stack; + FixedRefreshRateStopwatch raster_time; + FixedRefreshRateStopwatch ui_time; + PaintContext paint_context = { + // clang-format off + .state_stack = state_stack, + .canvas = nullptr, + .gr_context = nullptr, + .dst_color_space = nullptr, + .view_embedder = nullptr, + .raster_time = raster_time, + .ui_time = ui_time, + .texture_registry = nullptr, + .raster_cache = &raster_cache, + // clang-format on + }; + + PrerollContext preroll_context = { + // clang-format off + .raster_cache = &raster_cache, + .gr_context = nullptr, + .view_embedder = nullptr, + .state_stack = state_stack, + .dst_color_space = nullptr, + .surface_needs_readback = false, + .raster_time = raster_time, + .ui_time = ui_time, + .texture_registry = nullptr, + .has_platform_view = false, + .has_texture_layer = false, + .raster_cached_entries = &raster_cache_items, + // clang-format on + }; + + // 2.1. Rasterize the picture. Call Draw multiple times to pass the + // access threshold (default to 3) so a cache can be generated. + DisplayListBuilder dummy_canvas; + DlPaint paint; + bool picture_cache_generated; + DisplayListRasterCacheItem display_list_raster_cache_item( + display_list, SkPoint(), true, false); + for (int i = 0; i < 4; i += 1) { + DlMatrix matrix; + state_stack.set_preroll_delegate(matrix); + display_list_raster_cache_item.PrerollSetup(&preroll_context, matrix); + display_list_raster_cache_item.PrerollFinalize(&preroll_context, + matrix); + picture_cache_generated = + display_list_raster_cache_item.need_caching(); + state_stack.set_delegate(&dummy_canvas); + display_list_raster_cache_item.TryToPrepareRasterCache(paint_context); + display_list_raster_cache_item.Draw(paint_context, &dummy_canvas, + &paint); + } + ASSERT_TRUE(picture_cache_generated); + + // 2.2. Rasterize the picture layer. + LayerRasterCacheItem layer_raster_cache_item(display_list_layer.get()); + state_stack.set_preroll_delegate(DlMatrix()); + layer_raster_cache_item.PrerollSetup(&preroll_context, DlMatrix()); + layer_raster_cache_item.PrerollFinalize(&preroll_context, DlMatrix()); + state_stack.set_delegate(&dummy_canvas); + layer_raster_cache_item.TryToPrepareRasterCache(paint_context); + layer_raster_cache_item.Draw(paint_context, &dummy_canvas, &paint); + rasterized.set_value(true); + }); + rasterized.get_future().wait(); + + // 3. Call the service protocol and check its output. + ServiceProtocol::Handler::ServiceProtocolMap empty_params; + rapidjson::Document document; + OnServiceProtocol( + shell.get(), ServiceProtocolEnum::kEstimateRasterCacheMemory, + shell->GetTaskRunners().GetRasterTaskRunner(), empty_params, &document); + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + std::string expected_json = + "{\"type\":\"EstimateRasterCacheMemory\",\"layerBytes\":40024,\"picture" + "Bytes\":424}"; + std::string actual_json = buffer.GetString(); + ASSERT_EQ(actual_json, expected_json); + + DestroyShell(std::move(shell)); +} + +// TODO(https://github.com/flutter/flutter/issues/100273): Disabled due to +// flakiness. +// TODO(https://github.com/flutter/flutter/issues/100299): Fix it when +// re-enabling. +TEST_F(ShellTest, DISABLED_DiscardLayerTreeOnResize) { + auto settings = CreateSettingsForFixture(); + + SkISize wrong_size = SkISize::Make(400, 100); + SkISize expected_size = SkISize::Make(400, 200); + + fml::AutoResetWaitableEvent end_frame_latch; + auto end_frame_callback = + [&](bool should_merge_thread, + const fml::RefPtr& raster_thread_merger) { + end_frame_latch.Signal(); + }; + auto external_view_embedder = std::make_shared( + std::move(end_frame_callback), PostPrerollResult::kSuccess, false); + std::unique_ptr shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [&shell, &expected_size]() { + shell->GetPlatformView()->SetViewportMetrics( + kImplicitViewId, + {1.0, static_cast(expected_size.width()), + static_cast(expected_size.height()), 22, 0}); + }); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + PumpOneFrame(shell.get(), ViewContent::DummyView( + static_cast(wrong_size.width()), + static_cast(wrong_size.height()))); + end_frame_latch.Wait(); + // Wrong size, no frames are submitted. + ASSERT_EQ(0, external_view_embedder->GetSubmittedFrameCount()); + + PumpOneFrame(shell.get(), ViewContent::DummyView( + static_cast(expected_size.width()), + static_cast(expected_size.height()))); + end_frame_latch.Wait(); + // Expected size, 1 frame submitted. + ASSERT_EQ(1, external_view_embedder->GetSubmittedFrameCount()); + ASSERT_EQ(expected_size, external_view_embedder->GetLastSubmittedFrameSize()); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +} + +// TODO(https://github.com/flutter/flutter/issues/100273): Disabled due to +// flakiness. +// TODO(https://github.com/flutter/flutter/issues/100299): Fix it when +// re-enabling. +TEST_F(ShellTest, DISABLED_DiscardResubmittedLayerTreeOnResize) { + auto settings = CreateSettingsForFixture(); + + SkISize origin_size = SkISize::Make(400, 100); + SkISize new_size = SkISize::Make(400, 200); + + fml::AutoResetWaitableEvent end_frame_latch; + + fml::AutoResetWaitableEvent resize_latch; + + std::shared_ptr external_view_embedder; + fml::RefPtr raster_thread_merger_ref; + auto end_frame_callback = + [&](bool should_merge_thread, + const fml::RefPtr& raster_thread_merger) { + if (!raster_thread_merger_ref) { + raster_thread_merger_ref = raster_thread_merger; + } + if (should_merge_thread) { + raster_thread_merger->MergeWithLease(10); + external_view_embedder->UpdatePostPrerollResult( + PostPrerollResult::kSuccess); + } + end_frame_latch.Signal(); + + if (should_merge_thread) { + resize_latch.Wait(); + } + }; + + external_view_embedder = std::make_shared( + std::move(end_frame_callback), PostPrerollResult::kResubmitFrame, true); + + std::unique_ptr shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .shell_test_external_view_embedder = external_view_embedder, + }), + }); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [&shell, &origin_size]() { + shell->GetPlatformView()->SetViewportMetrics( + kImplicitViewId, + {1.0, static_cast(origin_size.width()), + static_cast(origin_size.height()), 22, 0}); + }); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + + RunEngine(shell.get(), std::move(configuration)); + + PumpOneFrame(shell.get(), ViewContent::DummyView( + static_cast(origin_size.width()), + static_cast(origin_size.height()))); + + end_frame_latch.Wait(); + ASSERT_EQ(0, external_view_embedder->GetSubmittedFrameCount()); + + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [&shell, &new_size, &resize_latch]() { + shell->GetPlatformView()->SetViewportMetrics( + kImplicitViewId, {1.0, static_cast(new_size.width()), + static_cast(new_size.height()), 22, 0}); + resize_latch.Signal(); + }); + + end_frame_latch.Wait(); + + // The frame resubmitted with origin size should be discarded after the + // viewport metrics changed. + ASSERT_EQ(0, external_view_embedder->GetSubmittedFrameCount()); + + // Threads will be merged at the end of this frame. + PumpOneFrame(shell.get(), + ViewContent::DummyView(static_cast(new_size.width()), + static_cast(new_size.height()))); + + end_frame_latch.Wait(); + ASSERT_TRUE(raster_thread_merger_ref->IsMerged()); + ASSERT_EQ(1, external_view_embedder->GetSubmittedFrameCount()); + ASSERT_EQ(new_size, external_view_embedder->GetLastSubmittedFrameSize()); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, IgnoresInvalidMetrics) { + fml::AutoResetWaitableEvent latch; + double last_device_pixel_ratio; + double last_width; + double last_height; + auto native_report_device_pixel_ratio = [&](Dart_NativeArguments args) { + auto dpr_handle = Dart_GetNativeArgument(args, 0); + ASSERT_TRUE(Dart_IsDouble(dpr_handle)); + Dart_DoubleValue(dpr_handle, &last_device_pixel_ratio); + ASSERT_FALSE(last_device_pixel_ratio == 0.0); + + auto width_handle = Dart_GetNativeArgument(args, 1); + ASSERT_TRUE(Dart_IsDouble(width_handle)); + Dart_DoubleValue(width_handle, &last_width); + ASSERT_FALSE(last_width == 0.0); + + auto height_handle = Dart_GetNativeArgument(args, 2); + ASSERT_TRUE(Dart_IsDouble(height_handle)); + Dart_DoubleValue(height_handle, &last_height); + ASSERT_FALSE(last_height == 0.0); + + latch.Signal(); + }; + + Settings settings = CreateSettingsForFixture(); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + + AddNativeCallback("ReportMetrics", + CREATE_NATIVE_ENTRY(native_report_device_pixel_ratio)); + + std::unique_ptr shell = CreateShell(settings, task_runners); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("reportMetrics"); + + RunEngine(shell.get(), std::move(configuration)); + + task_runner->PostTask([&]() { + // This one is invalid for having 0 pixel ratio. + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {0.0, 400, 200, 22, 0}); + task_runner->PostTask([&]() { + // This one is invalid for having 0 width. + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {0.8, 0.0, 200, 22, 0}); + task_runner->PostTask([&]() { + // This one is invalid for having 0 height. + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {0.8, 400, 0.0, 22, 0}); + task_runner->PostTask([&]() { + // This one makes it through. + shell->GetPlatformView()->SetViewportMetrics( + kImplicitViewId, {0.8, 400, 200.0, 22, 0}); + }); + }); + }); + }); + latch.Wait(); + ASSERT_EQ(last_device_pixel_ratio, 0.8); + ASSERT_EQ(last_width, 400.0); + ASSERT_EQ(last_height, 200.0); + latch.Reset(); + + task_runner->PostTask([&]() { + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {1.2, 600, 300, 22, 0}); + }); + latch.Wait(); + ASSERT_EQ(last_device_pixel_ratio, 1.2); + ASSERT_EQ(last_width, 600.0); + ASSERT_EQ(last_height, 300.0); + + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, IgnoresMetricsUpdateToInvalidView) { + fml::AutoResetWaitableEvent latch; + double last_device_pixel_ratio; + // This callback will be called whenever any view's metrics change. + auto native_report_device_pixel_ratio = [&](Dart_NativeArguments args) { + // The correct call will have a DPR of 3. + auto dpr_handle = Dart_GetNativeArgument(args, 0); + ASSERT_TRUE(Dart_IsDouble(dpr_handle)); + Dart_DoubleValue(dpr_handle, &last_device_pixel_ratio); + ASSERT_TRUE(last_device_pixel_ratio > 2.5); + + latch.Signal(); + }; + + Settings settings = CreateSettingsForFixture(); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + + AddNativeCallback("ReportMetrics", + CREATE_NATIVE_ENTRY(native_report_device_pixel_ratio)); + + std::unique_ptr shell = CreateShell(settings, task_runners); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("reportMetrics"); + + RunEngine(shell.get(), std::move(configuration)); + + task_runner->PostTask([&]() { + // This one is invalid for having an nonexistent view ID. + // Also, it has a DPR of 2.0 for detection. + shell->GetPlatformView()->SetViewportMetrics(2, {2.0, 400, 200, 22, 0}); + task_runner->PostTask([&]() { + // This one is valid with DPR 3.0. + shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, + {3.0, 400, 200, 22, 0}); + }); + }); + latch.Wait(); + ASSERT_EQ(last_device_pixel_ratio, 3.0); + latch.Reset(); + + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, OnServiceProtocolSetAssetBundlePathWorks) { + Settings settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + RunConfiguration configuration = + RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("canAccessResourceFromAssetDir"); + + // Verify isolate can load a known resource with the + // default asset directory - kernel_blob.bin + fml::AutoResetWaitableEvent latch; + + // Callback used to signal whether the resource was loaded successfully. + bool can_access_resource = false; + auto native_can_access_resource = [&can_access_resource, + &latch](Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + can_access_resource = + tonic::DartConverter::FromArguments(args, 0, exception); + latch.Signal(); + }; + AddNativeCallback("NotifyCanAccessResource", + CREATE_NATIVE_ENTRY(native_can_access_resource)); + + // Callback used to delay the asset load until after the service + // protocol method has finished. + auto native_notify_set_asset_bundle_path = + [&shell](Dart_NativeArguments args) { + // Update the asset directory to a bonus path. + ServiceProtocol::Handler::ServiceProtocolMap params; + params["assetDirectory"] = "assetDirectory"; + rapidjson::Document document; + OnServiceProtocol(shell.get(), ServiceProtocolEnum::kSetAssetBundlePath, + shell->GetTaskRunners().GetUITaskRunner(), params, + &document); + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + document.Accept(writer); + }; + AddNativeCallback("NotifySetAssetBundlePath", + CREATE_NATIVE_ENTRY(native_notify_set_asset_bundle_path)); + + RunEngine(shell.get(), std::move(configuration)); + + latch.Wait(); + ASSERT_TRUE(can_access_resource); + + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, EngineRootIsolateLaunchesDontTakeVMDataSettings) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + // Make sure the shell launch does not kick off the creation of the VM + // instance by already creating one upfront. + auto vm_settings = CreateSettingsForFixture(); + auto vm_ref = DartVMRef::Create(vm_settings); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + + auto settings = vm_settings; + fml::AutoResetWaitableEvent isolate_create_latch; + settings.root_isolate_create_callback = [&](const auto& isolate) { + isolate_create_latch.Signal(); + }; + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + RunEngine(shell.get(), std::move(configuration)); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + DestroyShell(std::move(shell)); + isolate_create_latch.Wait(); +} + +TEST_F(ShellTest, AssetManagerSingle) { + fml::ScopedTemporaryDirectory asset_dir; + fml::UniqueFD asset_dir_fd = fml::OpenDirectory( + asset_dir.path().c_str(), false, fml::FilePermission::kRead); + + std::string filename = "test_name"; + std::string content = "test_content"; + + bool success = fml::WriteAtomically(asset_dir_fd, filename.c_str(), + fml::DataMapping(content)); + ASSERT_TRUE(success); + + AssetManager asset_manager; + asset_manager.PushBack( + std::make_unique(std::move(asset_dir_fd), false)); + + auto mapping = asset_manager.GetAsMapping(filename); + ASSERT_TRUE(mapping != nullptr); + + std::string result(reinterpret_cast(mapping->GetMapping()), + mapping->GetSize()); + + ASSERT_TRUE(result == content); +} + +TEST_F(ShellTest, AssetManagerMulti) { + fml::ScopedTemporaryDirectory asset_dir; + fml::UniqueFD asset_dir_fd = fml::OpenDirectory( + asset_dir.path().c_str(), false, fml::FilePermission::kRead); + + std::vector filenames = { + "good0", + "bad0", + "good1", + "bad1", + }; + + for (const auto& filename : filenames) { + bool success = fml::WriteAtomically(asset_dir_fd, filename.c_str(), + fml::DataMapping(filename)); + ASSERT_TRUE(success); + } + + AssetManager asset_manager; + asset_manager.PushBack( + std::make_unique(std::move(asset_dir_fd), false)); + + auto mappings = asset_manager.GetAsMappings("(.*)", std::nullopt); + EXPECT_EQ(mappings.size(), 4u); + + std::vector expected_results = { + "good0", + "good1", + }; + + mappings = asset_manager.GetAsMappings("(.*)good(.*)", std::nullopt); + ASSERT_EQ(mappings.size(), expected_results.size()); + + for (auto& mapping : mappings) { + std::string result(reinterpret_cast(mapping->GetMapping()), + mapping->GetSize()); + EXPECT_NE( + std::find(expected_results.begin(), expected_results.end(), result), + expected_results.end()); + } +} + +#if defined(OS_FUCHSIA) +TEST_F(ShellTest, AssetManagerMultiSubdir) { + std::string subdir_path = "subdir"; + + fml::ScopedTemporaryDirectory asset_dir; + fml::UniqueFD asset_dir_fd = fml::OpenDirectory( + asset_dir.path().c_str(), false, fml::FilePermission::kRead); + fml::UniqueFD subdir_fd = + fml::OpenDirectory((asset_dir.path() + "/" + subdir_path).c_str(), true, + fml::FilePermission::kReadWrite); + + std::vector filenames = { + "bad0", + "notgood", // this is to make sure the pattern (.*)good(.*) only + // matches things in the subdirectory + }; + + std::vector subdir_filenames = { + "good0", + "good1", + "bad1", + }; + + for (auto filename : filenames) { + bool success = fml::WriteAtomically(asset_dir_fd, filename.c_str(), + fml::DataMapping(filename)); + ASSERT_TRUE(success); + } + + for (auto filename : subdir_filenames) { + bool success = fml::WriteAtomically(subdir_fd, filename.c_str(), + fml::DataMapping(filename)); + ASSERT_TRUE(success); + } + + AssetManager asset_manager; + asset_manager.PushBack( + std::make_unique(std::move(asset_dir_fd), false)); + + auto mappings = asset_manager.GetAsMappings("(.*)", std::nullopt); + EXPECT_EQ(mappings.size(), 5u); + + mappings = asset_manager.GetAsMappings("(.*)", subdir_path); + EXPECT_EQ(mappings.size(), 3u); + + std::vector expected_results = { + "good0", + "good1", + }; + + mappings = asset_manager.GetAsMappings("(.*)good(.*)", subdir_path); + ASSERT_EQ(mappings.size(), expected_results.size()); + + for (auto& mapping : mappings) { + std::string result(reinterpret_cast(mapping->GetMapping()), + mapping->GetSize()); + ASSERT_NE( + std::find(expected_results.begin(), expected_results.end(), result), + expected_results.end()); + } +} +#endif // OS_FUCHSIA + +TEST_F(ShellTest, Spawn) { + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + configuration.SetEntrypoint("fixturesAreFunctionalMain"); + + auto second_configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(second_configuration.IsValid()); + second_configuration.SetEntrypoint("testCanLaunchSecondaryIsolate"); + + const std::string initial_route("/foo"); + + fml::AutoResetWaitableEvent main_latch; + std::string last_entry_point; + // Fulfill native function for the first Shell's entrypoint. + AddNativeCallback( + "SayHiFromFixturesAreFunctionalMain", CREATE_NATIVE_ENTRY([&](auto args) { + last_entry_point = shell->GetEngine()->GetLastEntrypoint(); + main_latch.Signal(); + })); + // Fulfill native function for the second Shell's entrypoint. + fml::CountDownLatch second_latch(2); + AddNativeCallback( + // The Dart native function names aren't very consistent but this is + // just the native function name of the second vm entrypoint in the + // fixture. + "NotifyNative", + CREATE_NATIVE_ENTRY([&](auto args) { second_latch.CountDown(); })); + + RunEngine(shell.get(), std::move(configuration)); + main_latch.Wait(); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + // Check first Shell ran the first entrypoint. + ASSERT_EQ("fixturesAreFunctionalMain", last_entry_point); + + PostSync( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [this, &spawner = shell, &second_configuration, &second_latch, + initial_route]() { + MockPlatformViewDelegate platform_view_delegate; + auto spawn = spawner->Spawn( + std::move(second_configuration), initial_route, + [&platform_view_delegate](Shell& shell) { + auto result = std::make_unique( + platform_view_delegate, shell.GetTaskRunners()); + ON_CALL(*result, CreateRenderingSurface()) + .WillByDefault(::testing::Invoke( + [] { return std::make_unique(); })); + return result; + }, + [](Shell& shell) { return std::make_unique(shell); }); + ASSERT_NE(nullptr, spawn.get()); + ASSERT_TRUE(ValidateShell(spawn.get())); + + PostSync(spawner->GetTaskRunners().GetUITaskRunner(), [&spawn, &spawner, + initial_route] { + // Check second shell ran the second entrypoint. + ASSERT_EQ("testCanLaunchSecondaryIsolate", + spawn->GetEngine()->GetLastEntrypoint()); + ASSERT_EQ(initial_route, spawn->GetEngine()->InitialRoute()); + + ASSERT_NE(spawner->GetEngine() + ->GetRuntimeController() + ->GetRootIsolateGroup(), + 0u); + ASSERT_EQ(spawner->GetEngine() + ->GetRuntimeController() + ->GetRootIsolateGroup(), + spawn->GetEngine() + ->GetRuntimeController() + ->GetRootIsolateGroup()); + auto spawner_snapshot_delegate = spawner->GetEngine() + ->GetRuntimeController() + ->GetSnapshotDelegate(); + auto spawn_snapshot_delegate = + spawn->GetEngine()->GetRuntimeController()->GetSnapshotDelegate(); + PostSync(spawner->GetTaskRunners().GetRasterTaskRunner(), + [spawner_snapshot_delegate, spawn_snapshot_delegate] { + ASSERT_NE(spawner_snapshot_delegate.get(), + spawn_snapshot_delegate.get()); + }); + }); + PostSync( + spawner->GetTaskRunners().GetIOTaskRunner(), [&spawner, &spawn] { + ASSERT_EQ(spawner->GetIOManager()->GetResourceContext().get(), + spawn->GetIOManager()->GetResourceContext().get()); + }); + + // Before destroying the shell, wait for expectations of the spawned + // isolate to be met. + second_latch.Wait(); + + DestroyShell(std::move(spawn)); + }); + + DestroyShell(std::move(shell)); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, SpawnWithDartEntrypointArgs) { + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + configuration.SetEntrypoint("canReceiveArgumentsWhenEngineRun"); + const std::vector entrypoint_args{"foo", "bar"}; + configuration.SetEntrypointArgs(entrypoint_args); + + auto second_configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(second_configuration.IsValid()); + second_configuration.SetEntrypoint("canReceiveArgumentsWhenEngineSpawn"); + const std::vector second_entrypoint_args{"arg1", "arg2"}; + second_configuration.SetEntrypointArgs(second_entrypoint_args); + + const std::string initial_route("/foo"); + + fml::AutoResetWaitableEvent main_latch; + std::string last_entry_point; + // Fulfill native function for the first Shell's entrypoint. + AddNativeCallback("NotifyNativeWhenEngineRun", + CREATE_NATIVE_ENTRY(([&](Dart_NativeArguments args) { + ASSERT_TRUE(tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0))); + last_entry_point = + shell->GetEngine()->GetLastEntrypoint(); + main_latch.Signal(); + }))); + + fml::AutoResetWaitableEvent second_latch; + // Fulfill native function for the second Shell's entrypoint. + AddNativeCallback("NotifyNativeWhenEngineSpawn", + CREATE_NATIVE_ENTRY(([&](Dart_NativeArguments args) { + ASSERT_TRUE(tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0))); + last_entry_point = + shell->GetEngine()->GetLastEntrypoint(); + second_latch.Signal(); + }))); + + RunEngine(shell.get(), std::move(configuration)); + main_latch.Wait(); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + // Check first Shell ran the first entrypoint. + ASSERT_EQ("canReceiveArgumentsWhenEngineRun", last_entry_point); + + PostSync( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [this, &spawner = shell, &second_configuration, &second_latch, + initial_route]() { + MockPlatformViewDelegate platform_view_delegate; + auto spawn = spawner->Spawn( + std::move(second_configuration), initial_route, + [&platform_view_delegate](Shell& shell) { + auto result = std::make_unique( + platform_view_delegate, shell.GetTaskRunners()); + ON_CALL(*result, CreateRenderingSurface()) + .WillByDefault(::testing::Invoke( + [] { return std::make_unique(); })); + return result; + }, + [](Shell& shell) { return std::make_unique(shell); }); + ASSERT_NE(nullptr, spawn.get()); + ASSERT_TRUE(ValidateShell(spawn.get())); + + PostSync(spawner->GetTaskRunners().GetUITaskRunner(), + [&spawn, &spawner, initial_route] { + // Check second shell ran the second entrypoint. + ASSERT_EQ("canReceiveArgumentsWhenEngineSpawn", + spawn->GetEngine()->GetLastEntrypoint()); + ASSERT_EQ(initial_route, spawn->GetEngine()->InitialRoute()); + + ASSERT_NE(spawner->GetEngine() + ->GetRuntimeController() + ->GetRootIsolateGroup(), + 0u); + ASSERT_EQ(spawner->GetEngine() + ->GetRuntimeController() + ->GetRootIsolateGroup(), + spawn->GetEngine() + ->GetRuntimeController() + ->GetRootIsolateGroup()); + }); + + PostSync( + spawner->GetTaskRunners().GetIOTaskRunner(), [&spawner, &spawn] { + ASSERT_EQ(spawner->GetIOManager()->GetResourceContext().get(), + spawn->GetIOManager()->GetResourceContext().get()); + }); + + // Before destroying the shell, wait for expectations of the spawned + // isolate to be met. + second_latch.Wait(); + + DestroyShell(std::move(spawn)); + }); + + DestroyShell(std::move(shell)); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, IOManagerIsSharedBetweenParentAndSpawnedShell) { + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [this, + &spawner = shell, + &settings] { + auto second_configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(second_configuration.IsValid()); + second_configuration.SetEntrypoint("emptyMain"); + const std::string initial_route("/foo"); + MockPlatformViewDelegate platform_view_delegate; + auto spawn = spawner->Spawn( + std::move(second_configuration), initial_route, + [&platform_view_delegate](Shell& shell) { + auto result = std::make_unique( + platform_view_delegate, shell.GetTaskRunners()); + ON_CALL(*result, CreateRenderingSurface()) + .WillByDefault(::testing::Invoke( + [] { return std::make_unique(); })); + return result; + }, + [](Shell& shell) { return std::make_unique(shell); }); + ASSERT_TRUE(ValidateShell(spawn.get())); + + PostSync(spawner->GetTaskRunners().GetIOTaskRunner(), [&spawner, &spawn] { + ASSERT_NE(spawner->GetIOManager().get(), nullptr); + ASSERT_EQ(spawner->GetIOManager().get(), spawn->GetIOManager().get()); + }); + + // Destroy the child shell. + DestroyShell(std::move(spawn)); + }); + // Destroy the parent shell. + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, IOManagerInSpawnedShellIsNotNullAfterParentShellDestroyed) { + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + PostSync(shell->GetTaskRunners().GetUITaskRunner(), [&shell] { + // We must get engine on UI thread. + auto runtime_controller = shell->GetEngine()->GetRuntimeController(); + PostSync(shell->GetTaskRunners().GetIOTaskRunner(), + [&shell, &runtime_controller] { + // We must get io_manager on IO thread. + auto io_manager = runtime_controller->GetIOManager(); + // Check io_manager existence. + ASSERT_NE(io_manager.get(), nullptr); + ASSERT_NE(io_manager->GetSkiaUnrefQueue().get(), nullptr); + // Get io_manager directly from shell and check its existence. + ASSERT_NE(shell->GetIOManager().get(), nullptr); + }); + }); + + std::unique_ptr spawn; + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell, &settings, + &spawn] { + auto second_configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(second_configuration.IsValid()); + second_configuration.SetEntrypoint("emptyMain"); + const std::string initial_route("/foo"); + MockPlatformViewDelegate platform_view_delegate; + auto child = shell->Spawn( + std::move(second_configuration), initial_route, + [&platform_view_delegate](Shell& shell) { + auto result = std::make_unique( + platform_view_delegate, shell.GetTaskRunners()); + ON_CALL(*result, CreateRenderingSurface()) + .WillByDefault(::testing::Invoke( + [] { return std::make_unique(); })); + return result; + }, + [](Shell& shell) { return std::make_unique(shell); }); + spawn = std::move(child); + }); + // Destroy the parent shell. + DestroyShell(std::move(shell)); + + PostSync(spawn->GetTaskRunners().GetUITaskRunner(), [&spawn] { + // We must get engine on UI thread. + auto runtime_controller = spawn->GetEngine()->GetRuntimeController(); + PostSync(spawn->GetTaskRunners().GetIOTaskRunner(), + [&spawn, &runtime_controller] { + // We must get io_manager on IO thread. + auto io_manager = runtime_controller->GetIOManager(); + // Check io_manager existence here. + ASSERT_NE(io_manager.get(), nullptr); + ASSERT_NE(io_manager->GetSkiaUnrefQueue().get(), nullptr); + // Get io_manager directly from shell and check its existence. + ASSERT_NE(spawn->GetIOManager().get(), nullptr); + }); + }); + // Destroy the child shell. + DestroyShell(std::move(spawn)); +} + +TEST_F(ShellTest, ImageGeneratorRegistryNotNullAfterParentShellDestroyed) { + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + std::unique_ptr spawn; + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell, &settings, + &spawn] { + auto second_configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(second_configuration.IsValid()); + second_configuration.SetEntrypoint("emptyMain"); + const std::string initial_route("/foo"); + MockPlatformViewDelegate platform_view_delegate; + auto child = shell->Spawn( + std::move(second_configuration), initial_route, + [&platform_view_delegate](Shell& shell) { + auto result = std::make_unique( + platform_view_delegate, shell.GetTaskRunners()); + ON_CALL(*result, CreateRenderingSurface()) + .WillByDefault(::testing::Invoke( + [] { return std::make_unique(); })); + return result; + }, + [](Shell& shell) { return std::make_unique(shell); }); + spawn = std::move(child); + }); + + PostSync(spawn->GetTaskRunners().GetUITaskRunner(), [&spawn] { + std::shared_ptr isolate = + spawn->GetEngine()->GetRuntimeController()->GetRootIsolate().lock(); + ASSERT_TRUE(isolate); + ASSERT_TRUE(isolate->GetImageGeneratorRegistry()); + }); + + // Destroy the parent shell. + DestroyShell(std::move(shell)); + + PostSync(spawn->GetTaskRunners().GetUITaskRunner(), [&spawn] { + std::shared_ptr isolate = + spawn->GetEngine()->GetRuntimeController()->GetRootIsolate().lock(); + ASSERT_TRUE(isolate); + ASSERT_TRUE(isolate->GetImageGeneratorRegistry()); + }); + // Destroy the child shell. + DestroyShell(std::move(spawn)); +} + +TEST_F(ShellTest, UpdateAssetResolverByTypeReplaces) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + auto asset_manager = configuration.GetAssetManager(); + + shell->RunEngine(std::move(configuration), [&](auto result) { + ASSERT_EQ(result, Engine::RunStatus::Success); + }); + + auto platform_view = + std::make_unique(*shell.get(), task_runners); + + auto old_resolver = std::make_unique( + true, AssetResolver::AssetResolverType::kApkAssetProvider); + ASSERT_TRUE(old_resolver->IsValid()); + asset_manager->PushBack(std::move(old_resolver)); + + auto updated_resolver = std::make_unique( + false, AssetResolver::AssetResolverType::kApkAssetProvider); + ASSERT_FALSE(updated_resolver->IsValidAfterAssetManagerChange()); + platform_view->UpdateAssetResolverByType( + std::move(updated_resolver), + AssetResolver::AssetResolverType::kApkAssetProvider); + + auto resolvers = asset_manager->TakeResolvers(); + ASSERT_EQ(resolvers.size(), 2ull); + ASSERT_TRUE(resolvers[0]->IsValidAfterAssetManagerChange()); + + ASSERT_FALSE(resolvers[1]->IsValidAfterAssetManagerChange()); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, UpdateAssetResolverByTypeAppends) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + auto asset_manager = configuration.GetAssetManager(); + + shell->RunEngine(std::move(configuration), [&](auto result) { + ASSERT_EQ(result, Engine::RunStatus::Success); + }); + + auto platform_view = + std::make_unique(*shell.get(), task_runners); + + auto updated_resolver = std::make_unique( + false, AssetResolver::AssetResolverType::kApkAssetProvider); + ASSERT_FALSE(updated_resolver->IsValidAfterAssetManagerChange()); + platform_view->UpdateAssetResolverByType( + std::move(updated_resolver), + AssetResolver::AssetResolverType::kApkAssetProvider); + + auto resolvers = asset_manager->TakeResolvers(); + ASSERT_EQ(resolvers.size(), 2ull); + ASSERT_TRUE(resolvers[0]->IsValidAfterAssetManagerChange()); + + ASSERT_FALSE(resolvers[1]->IsValidAfterAssetManagerChange()); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, UpdateAssetResolverByTypeNull) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + "io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform)); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + auto asset_manager = configuration.GetAssetManager(); + RunEngine(shell.get(), std::move(configuration)); + + auto platform_view = + std::make_unique(*shell.get(), task_runners); + + auto old_resolver = std::make_unique( + true, AssetResolver::AssetResolverType::kApkAssetProvider); + ASSERT_TRUE(old_resolver->IsValid()); + asset_manager->PushBack(std::move(old_resolver)); + + platform_view->UpdateAssetResolverByType( + nullptr, AssetResolver::AssetResolverType::kApkAssetProvider); + + auto resolvers = asset_manager->TakeResolvers(); + ASSERT_EQ(resolvers.size(), 2ull); + ASSERT_TRUE(resolvers[0]->IsValidAfterAssetManagerChange()); + ASSERT_TRUE(resolvers[1]->IsValidAfterAssetManagerChange()); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, UpdateAssetResolverByTypeDoesNotReplaceMismatchType) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + auto asset_manager = configuration.GetAssetManager(); + + shell->RunEngine(std::move(configuration), [&](auto result) { + ASSERT_EQ(result, Engine::RunStatus::Success); + }); + + auto platform_view = + std::make_unique(*shell.get(), task_runners); + + auto old_resolver = std::make_unique( + true, AssetResolver::AssetResolverType::kAssetManager); + ASSERT_TRUE(old_resolver->IsValid()); + asset_manager->PushBack(std::move(old_resolver)); + + auto updated_resolver = std::make_unique( + false, AssetResolver::AssetResolverType::kApkAssetProvider); + ASSERT_FALSE(updated_resolver->IsValidAfterAssetManagerChange()); + platform_view->UpdateAssetResolverByType( + std::move(updated_resolver), + AssetResolver::AssetResolverType::kApkAssetProvider); + + auto resolvers = asset_manager->TakeResolvers(); + ASSERT_EQ(resolvers.size(), 3ull); + ASSERT_TRUE(resolvers[0]->IsValidAfterAssetManagerChange()); + + ASSERT_TRUE(resolvers[1]->IsValidAfterAssetManagerChange()); + + ASSERT_FALSE(resolvers[2]->IsValidAfterAssetManagerChange()); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, CanCreateShellsWithGLBackend) { +#if !SHELL_ENABLE_GL + // GL emulation does not exist on Fuchsia. + GTEST_SKIP(); +#else + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .rendering_backend = ShellTestPlatformView::BackendType::kGLBackend, + }), + }); + ASSERT_NE(shell, nullptr); + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + PlatformViewNotifyCreated(shell.get()); + configuration.SetEntrypoint("emptyMain"); + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +#endif // !SHELL_ENABLE_GL +} + +TEST_F(ShellTest, CanCreateShellsWithVulkanBackend) { +#if !SHELL_ENABLE_VULKAN + GTEST_SKIP(); +#else + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .rendering_backend = + ShellTestPlatformView::BackendType::kVulkanBackend, + }), + }); + ASSERT_NE(shell, nullptr); + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + PlatformViewNotifyCreated(shell.get()); + configuration.SetEntrypoint("emptyMain"); + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +#endif // !SHELL_ENABLE_VULKAN +} + +TEST_F(ShellTest, CanCreateShellsWithMetalBackend) { +#if !SHELL_ENABLE_METAL + GTEST_SKIP(); +#else + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .rendering_backend = + ShellTestPlatformView::BackendType::kMetalBackend, + }), + }); + ASSERT_NE(shell, nullptr); + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + PlatformViewNotifyCreated(shell.get()); + configuration.SetEntrypoint("emptyMain"); + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +#endif // !SHELL_ENABLE_METAL +} + +TEST_F(ShellTest, UserTagSetOnStartup) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + // Make sure the shell launch does not kick off the creation of the VM + // instance by already creating one upfront. + auto vm_settings = CreateSettingsForFixture(); + auto vm_ref = DartVMRef::Create(vm_settings); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + + auto settings = vm_settings; + fml::AutoResetWaitableEvent isolate_create_latch; + + // ensure that "AppStartUpTag" is set during isolate creation. + settings.root_isolate_create_callback = [&](const DartIsolate& isolate) { + Dart_Handle current_tag = Dart_GetCurrentUserTag(); + Dart_Handle startup_tag = Dart_NewUserTag("AppStartUp"); + EXPECT_TRUE(Dart_IdentityEquals(current_tag, startup_tag)); + + isolate_create_latch.Signal(); + }; + + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + + RunEngine(shell.get(), std::move(configuration)); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + + DestroyShell(std::move(shell)); + isolate_create_latch.Wait(); +} + +TEST_F(ShellTest, PrefetchDefaultFontManager) { + auto settings = CreateSettingsForFixture(); + settings.prefetched_default_font_manager = true; + std::unique_ptr shell; + + auto get_font_manager_count = [&] { + fml::AutoResetWaitableEvent latch; + size_t font_manager_count; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetUITaskRunner(), + [this, &shell, &latch, &font_manager_count]() { + font_manager_count = + GetFontCollection(shell.get())->GetFontManagersCount(); + latch.Signal(); + }); + latch.Wait(); + return font_manager_count; + }; + size_t initial_font_manager_count = 0; + settings.root_isolate_create_callback = [&](const auto& isolate) { + ASSERT_GT(initial_font_manager_count, 0ul); + // Should not have fetched the default font manager yet, since the root + // isolate was only just created. + ASSERT_EQ(get_font_manager_count(), initial_font_manager_count); + }; + + shell = CreateShell(settings); + + initial_font_manager_count = get_font_manager_count(); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + RunEngine(shell.get(), std::move(configuration)); + + // If the prefetched_default_font_manager flag is set, then the default font + // manager will not be added until the engine starts running. + ASSERT_EQ(get_font_manager_count(), initial_font_manager_count + 1); + + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, OnPlatformViewCreatedWhenUIThreadIsBusy) { + // This test will deadlock if the threading logic in + // Shell::OnCreatePlatformView is wrong. + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask(shell->GetTaskRunners().GetUITaskRunner(), + [&latch]() { latch.Wait(); }); + + ShellTest::PlatformViewNotifyCreated(shell.get()); + latch.Signal(); + + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, UIWorkAfterOnPlatformViewDestroyed) { + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("drawFrames"); + + fml::AutoResetWaitableEvent latch; + fml::AutoResetWaitableEvent notify_native_latch; + AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) { + notify_native_latch.Signal(); + latch.Wait(); + })); + + RunEngine(shell.get(), std::move(configuration)); + // Wait to make sure we get called back from Dart and thus have latched + // the UI thread before we create/destroy the platform view. + notify_native_latch.Wait(); + + ShellTest::PlatformViewNotifyCreated(shell.get()); + + fml::AutoResetWaitableEvent destroy_latch; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [&shell, &destroy_latch]() { + shell->GetPlatformView()->NotifyDestroyed(); + destroy_latch.Signal(); + }); + + destroy_latch.Wait(); + + // Unlatch the UI thread and let it send us a scene to render. + latch.Signal(); + + // Flush the UI task runner to make sure we process the render/scheduleFrame + // request. + fml::AutoResetWaitableEvent ui_flush_latch; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetUITaskRunner(), + [&ui_flush_latch]() { ui_flush_latch.Signal(); }); + ui_flush_latch.Wait(); + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, UsesPlatformMessageHandler) { + TaskRunners task_runners = GetTaskRunnersForFixture(); + auto settings = CreateSettingsForFixture(); + MockPlatformViewDelegate platform_view_delegate; + auto platform_message_handler = + std::make_shared(); + int message_id = 1; + EXPECT_CALL(*platform_message_handler, HandlePlatformMessage(_)); + EXPECT_CALL(*platform_message_handler, + InvokePlatformMessageEmptyResponseCallback(message_id)); + Shell::CreateCallback platform_view_create_callback = + [&platform_view_delegate, task_runners, + platform_message_handler](flutter::Shell& shell) { + auto result = std::make_unique(platform_view_delegate, + task_runners); + EXPECT_CALL(*result, GetPlatformMessageHandler()) + .WillOnce(Return(platform_message_handler)); + return result; + }; + auto shell = CreateShell({ + .settings = settings, + .task_runners = task_runners, + .platform_view_create_callback = platform_view_create_callback, + }); + + EXPECT_EQ(platform_message_handler, shell->GetPlatformMessageHandler()); + PostSync(task_runners.GetUITaskRunner(), [&shell]() { + size_t data_size = 4; + fml::MallocMapping bytes = + fml::MallocMapping(static_cast(malloc(data_size)), data_size); + fml::RefPtr response = + MockPlatformMessageResponse::Create(); + auto message = std::make_unique( + /*channel=*/"foo", /*data=*/std::move(bytes), /*response=*/response); + (static_cast(shell.get())) + ->OnEngineHandlePlatformMessage(std::move(message)); + }); + shell->GetPlatformMessageHandler() + ->InvokePlatformMessageEmptyResponseCallback(message_id); + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, SpawnWorksWithOnError) { + auto settings = CreateSettingsForFixture(); + auto shell = CreateShell(settings); + ASSERT_TRUE(ValidateShell(shell.get())); + + auto configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(configuration.IsValid()); + configuration.SetEntrypoint("onErrorA"); + + auto second_configuration = RunConfiguration::InferFromSettings(settings); + ASSERT_TRUE(second_configuration.IsValid()); + second_configuration.SetEntrypoint("onErrorB"); + + fml::CountDownLatch latch(2); + + AddNativeCallback( + "NotifyErrorA", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + auto string_handle = Dart_GetNativeArgument(args, 0); + const char* c_str; + Dart_StringToCString(string_handle, &c_str); + EXPECT_STREQ(c_str, "Exception: I should be coming from A"); + latch.CountDown(); + })); + + AddNativeCallback( + "NotifyErrorB", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + auto string_handle = Dart_GetNativeArgument(args, 0); + const char* c_str; + Dart_StringToCString(string_handle, &c_str); + EXPECT_STREQ(c_str, "Exception: I should be coming from B"); + latch.CountDown(); + })); + + RunEngine(shell.get(), std::move(configuration)); + + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + + PostSync( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [this, &spawner = shell, &second_configuration, &latch]() { + ::testing::NiceMock platform_view_delegate; + auto spawn = spawner->Spawn( + std::move(second_configuration), "", + [&platform_view_delegate](Shell& shell) { + auto result = + std::make_unique<::testing::NiceMock>( + platform_view_delegate, shell.GetTaskRunners()); + ON_CALL(*result, CreateRenderingSurface()) + .WillByDefault(::testing::Invoke([] { + return std::make_unique<::testing::NiceMock>(); + })); + return result; + }, + [](Shell& shell) { return std::make_unique(shell); }); + ASSERT_NE(nullptr, spawn.get()); + ASSERT_TRUE(ValidateShell(spawn.get())); + + // Before destroying the shell, wait for expectations of the spawned + // isolate to be met. + latch.Wait(); + + DestroyShell(std::move(spawn)); + }); + + DestroyShell(std::move(shell)); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, ImmutableBufferLoadsAssetOnBackgroundThread) { + Settings settings = CreateSettingsForFixture(); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + std::unique_ptr shell = CreateShell(settings, task_runners); + + fml::CountDownLatch latch(1); + AddNativeCallback("NotifyNative", + CREATE_NATIVE_ENTRY([&](auto args) { latch.CountDown(); })); + + // Create the surface needed by rasterizer + PlatformViewNotifyCreated(shell.get()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testThatAssetLoadingHappensOnWorkerThread"); + auto asset_manager = configuration.GetAssetManager(); + auto test_resolver = std::make_unique( + shell->GetDartVM()->GetConcurrentMessageLoop()); + auto leaked_resolver = test_resolver.get(); + asset_manager->PushBack(std::move(test_resolver)); + + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + latch.Wait(); + + EXPECT_EQ(leaked_resolver->mapping_requests[0], "DoesNotExist"); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, PictureToImageSync) { +#if !SHELL_ENABLE_GL + // This test uses the GL backend. + GTEST_SKIP(); +#else + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .rendering_backend = ShellTestPlatformView::BackendType::kGLBackend, + }), + }); + + AddNativeCallback("NativeOnBeforeToImageSync", + CREATE_NATIVE_ENTRY([&](auto args) { + // nop + })); + + fml::CountDownLatch latch(2); + AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) { + // Teardown and set up rasterizer again. + PlatformViewNotifyDestroyed(shell.get()); + PlatformViewNotifyCreated(shell.get()); + latch.CountDown(); + })); + + ASSERT_NE(shell, nullptr); + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + PlatformViewNotifyCreated(shell.get()); + configuration.SetEntrypoint("toImageSync"); + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + latch.Wait(); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +#endif // !SHELL_ENABLE_GL +} + +TEST_F(ShellTest, PictureToImageSyncImpellerNoSurface) { +#if !SHELL_ENABLE_METAL + // This test uses the Metal backend. + GTEST_SKIP(); +#else + auto settings = CreateSettingsForFixture(); + settings.enable_impeller = true; + std::unique_ptr shell = CreateShell({ + .settings = settings, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .rendering_backend = + ShellTestPlatformView::BackendType::kMetalBackend, + }), + }); + + AddNativeCallback("NativeOnBeforeToImageSync", + CREATE_NATIVE_ENTRY([&](auto args) { + // nop + })); + + fml::CountDownLatch latch(2); + AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) { + // Teardown and set up rasterizer again. + PlatformViewNotifyDestroyed(shell.get()); + PlatformViewNotifyCreated(shell.get()); + latch.CountDown(); + })); + + ASSERT_NE(shell, nullptr); + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + + // Important: Do not create the platform view yet! + // This test is making sure that the rasterizer can create the texture + // as expected without a surface. + + configuration.SetEntrypoint("toImageSync"); + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + latch.Wait(); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +#endif // !SHELL_ENABLE_METAL +} + +#if SHELL_ENABLE_GL +// This test uses the GL backend and refers to symbols in egl.h +TEST_F(ShellTest, PictureToImageSyncWithTrampledContext) { + // make it easier to trample the GL context by running on a single task + // runner. + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell({ + .settings = settings, + .task_runners = task_runners, + .platform_view_create_callback = ShellTestPlatformViewBuilder({ + .rendering_backend = ShellTestPlatformView::BackendType::kGLBackend, + }), + }); + + AddNativeCallback( + "NativeOnBeforeToImageSync", CREATE_NATIVE_ENTRY([&](auto args) { + // Trample the GL context. If the rasterizer fails + // to make the right one current again, test will + // fail. + ::eglMakeCurrent(::eglGetCurrentDisplay(), NULL, NULL, NULL); + })); + + fml::CountDownLatch latch(2); + AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) { + // Teardown and set up rasterizer again. + PlatformViewNotifyDestroyed(shell.get()); + PlatformViewNotifyCreated(shell.get()); + latch.CountDown(); + })); + + ASSERT_NE(shell, nullptr); + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + PlatformViewNotifyCreated(shell.get()); + configuration.SetEntrypoint("toImageSync"); + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + latch.Wait(); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell), task_runners); +} +#endif // SHELL_ENABLE_GL + +TEST_F(ShellTest, PluginUtilitiesCallbackHandleErrorHandling) { + auto settings = CreateSettingsForFixture(); + std::unique_ptr shell = CreateShell(settings); + + fml::AutoResetWaitableEvent latch; + bool test_passed; + AddNativeCallback("NotifyNativeBool", CREATE_NATIVE_ENTRY([&](auto args) { + Dart_Handle exception = nullptr; + test_passed = tonic::DartConverter::FromArguments( + args, 0, exception); + latch.Signal(); + })); + + ASSERT_NE(shell, nullptr); + ASSERT_TRUE(shell->IsSetup()); + auto configuration = RunConfiguration::InferFromSettings(settings); + PlatformViewNotifyCreated(shell.get()); + configuration.SetEntrypoint("testPluginUtilitiesCallbackHandle"); + RunEngine(shell.get(), std::move(configuration)); + PumpOneFrame(shell.get()); + + latch.Wait(); + + ASSERT_TRUE(test_passed); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell)); +} + +TEST_F(ShellTest, NotifyIdleRejectsPastAndNearFuture) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::kUi | + ThreadHost::kIo | ThreadHost::kRaster); + auto platform_task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + + fml::AutoResetWaitableEvent latch; + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("emptyMain"); + RunEngine(shell.get(), std::move(configuration)); + + fml::TaskRunner::RunNowOrPostTask( + task_runners.GetUITaskRunner(), [&latch, &shell]() { + auto runtime_controller = const_cast( + shell->GetEngine()->GetRuntimeController()); + + auto now = fml::TimeDelta::FromMicroseconds(Dart_TimelineGetMicros()); + + EXPECT_FALSE(runtime_controller->NotifyIdle( + now - fml::TimeDelta::FromMilliseconds(10))); + EXPECT_FALSE(runtime_controller->NotifyIdle(now)); + EXPECT_FALSE(runtime_controller->NotifyIdle( + now + fml::TimeDelta::FromNanoseconds(100))); + + EXPECT_TRUE(runtime_controller->NotifyIdle( + now + fml::TimeDelta::FromMilliseconds(100))); + latch.Signal(); + }); + + latch.Wait(); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, NotifyIdleNotCalledInLatencyMode) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::kUi | + ThreadHost::kIo | ThreadHost::kRaster); + auto platform_task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + + // we start off in balanced mode, where we expect idle notifications to + // succeed. After the first `NotifyNativeBool` we expect to be in latency + // mode, where we expect idle notifications to fail. + fml::CountDownLatch latch(2); + AddNativeCallback( + "NotifyNativeBool", CREATE_NATIVE_ENTRY([&](auto args) { + Dart_Handle exception = nullptr; + bool is_in_latency_mode = + tonic::DartConverter::FromArguments(args, 0, exception); + auto runtime_controller = const_cast( + shell->GetEngine()->GetRuntimeController()); + bool success = + runtime_controller->NotifyIdle(fml::TimeDelta::FromMicroseconds( + Dart_TimelineGetMicros() + 100000)); + EXPECT_EQ(success, !is_in_latency_mode); + latch.CountDown(); + })); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("performanceModeImpactsNotifyIdle"); + RunEngine(shell.get(), std::move(configuration)); + + latch.Wait(); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, NotifyDestroyed) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::kUi | + ThreadHost::kIo | ThreadHost::kRaster); + auto platform_task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + auto shell = CreateShell(settings, task_runners); + ASSERT_TRUE(DartVMRef::IsInstanceRunning()); + ASSERT_TRUE(ValidateShell(shell.get())); + + fml::CountDownLatch latch(1); + AddNativeCallback("NotifyDestroyed", CREATE_NATIVE_ENTRY([&](auto args) { + auto runtime_controller = const_cast( + shell->GetEngine()->GetRuntimeController()); + bool success = runtime_controller->NotifyDestroyed(); + EXPECT_TRUE(success); + latch.CountDown(); + })); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("callNotifyDestroyed"); + RunEngine(shell.get(), std::move(configuration)); + + latch.Wait(); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, PrintsErrorWhenPlatformMessageSentFromWrongThread) { +#if FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG || OS_FUCHSIA + GTEST_SKIP() << "Test is for debug mode only on non-fuchsia targets."; +#else + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + auto shell = CreateShell(settings, task_runners); + + { + fml::testing::LogCapture log_capture; + + // The next call will result in a thread checker violation. + fml::ThreadChecker::DisableNextThreadCheckFailure(); + SendPlatformMessage(shell.get(), std::make_unique( + "com.test.plugin", nullptr)); + + EXPECT_THAT( + log_capture.str(), + ::testing::EndsWith( + "The 'com.test.plugin' channel sent a message from native to " + "Flutter on a non-platform thread. Platform channel messages " + "must be sent on the platform thread. Failure to do so may " + "result in data loss or crashes, and must be fixed in the " + "plugin or application code creating that channel.\nSee " + "https://docs.flutter.dev/platform-integration/" + "platform-channels#channels-and-platform-threading for more " + "information.\n")); + } + + { + fml::testing::LogCapture log_capture; + + // The next call will result in a thread checker violation. + fml::ThreadChecker::DisableNextThreadCheckFailure(); + SendPlatformMessage(shell.get(), std::make_unique( + "com.test.plugin", nullptr)); + + EXPECT_EQ(log_capture.str(), ""); + } + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +#endif +} + +TEST_F(ShellTest, NavigationMessageDispachedImmediately) { + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + auto shell = CreateShell(settings, task_runners); + + auto latch = std::make_shared(1u); + task_runner->PostTask([&]() { + auto message = MakePlatformMessage( + "flutter/navigation", + {{"method", "setInitialRoute"}, {"args", "/testo"}}, nullptr); + SendPlatformMessage(shell.get(), std::move(message)); + EXPECT_EQ(shell->GetEngine()->InitialRoute(), "/testo"); + + latch->CountDown(); + }); + latch->Wait(); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +// Verifies a semantics Action will flush the dart event loop. +TEST_F(ShellTest, SemanticsActionsFlushMessageLoop) { + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + + EXPECT_EQ(task_runners.GetPlatformTaskRunner(), + task_runners.GetUITaskRunner()); + auto shell = CreateShell(settings, task_runners); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testSemanticsActions"); + + RunEngine(shell.get(), std::move(configuration)); + fml::CountDownLatch latch(1); + AddNativeCallback( + // The Dart native function names aren't very consistent but this is + // just the native function name of the second vm entrypoint in the + // fixture. + "NotifyNative", + CREATE_NATIVE_ENTRY([&](auto args) { latch.CountDown(); })); + + task_runners.GetPlatformTaskRunner()->PostTask([&] { + SendSemanticsAction(shell.get(), 456, 0, SemanticsAction::kTap, + fml::MallocMapping(nullptr, 0)); + }); + latch.Wait(); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +// Verifies a pointer event will flush the dart event loop. +TEST_F(ShellTest, PointerPacketFlushMessageLoop) { + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + + EXPECT_EQ(task_runners.GetPlatformTaskRunner(), + task_runners.GetUITaskRunner()); + auto shell = CreateShell(settings, task_runners); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testPointerActions"); + + RunEngine(shell.get(), std::move(configuration)); + fml::CountDownLatch latch(1); + AddNativeCallback( + // The Dart native function names aren't very consistent but this is + // just the native function name of the second vm entrypoint in the + // fixture. + "NotifyNative", + CREATE_NATIVE_ENTRY([&](auto args) { latch.CountDown(); })); + + DispatchFakePointerData(shell.get(), 23); + latch.Wait(); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +// Verifies a pointer event will flush the dart event loop. +TEST_F(ShellTest, DISABLED_PointerPacketsAreDispatchedWithTask) { + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + + EXPECT_EQ(task_runners.GetPlatformTaskRunner(), + task_runners.GetUITaskRunner()); + auto shell = CreateShell(settings, task_runners); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testDispatchEvents"); + + RunEngine(shell.get(), std::move(configuration)); + fml::CountDownLatch latch(1); + bool did_invoke_callback = false; + AddNativeCallback( + // The Dart native function names aren't very consistent but this is + // just the native function name of the second vm entrypoint in the + // fixture. + "NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) { + did_invoke_callback = true; + latch.CountDown(); + })); + + DispatchFakePointerData(shell.get(), 23); + EXPECT_FALSE(did_invoke_callback); + latch.Wait(); + EXPECT_TRUE(did_invoke_callback); + + DestroyShell(std::move(shell), task_runners); + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); +} + +TEST_F(ShellTest, DiesIfSoftwareRenderingAndImpellerAreEnabledDeathTest) { +#if defined(OS_FUCHSIA) + GTEST_SKIP() << "Fuchsia"; +#else + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + Settings settings = CreateSettingsForFixture(); + settings.enable_impeller = true; + settings.enable_software_rendering = true; + ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform); + auto task_runner = thread_host.platform_thread->GetTaskRunner(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + EXPECT_DEATH_IF_SUPPORTED( + CreateShell(settings, task_runners), + "Software rendering is incompatible with Impeller."); +#endif // OS_FUCHSIA +} + +// Parse the arguments of NativeReportViewIdsCallback and +// store them in hasImplicitView and viewIds. +static void ParseViewIdsCallback(const Dart_NativeArguments& args, + bool* hasImplicitView, + std::vector* viewIds) { + Dart_Handle exception = nullptr; + viewIds->clear(); + *hasImplicitView = + tonic::DartConverter::FromArguments(args, 0, exception); + ASSERT_EQ(exception, nullptr); + *viewIds = tonic::DartConverter>::FromArguments( + args, 1, exception); + ASSERT_EQ(exception, nullptr); +} + +TEST_F(ShellTest, ShellStartsWithImplicitView) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + auto task_runner = CreateNewThread(); + TaskRunners task_runners("test", task_runner, task_runner, task_runner, + task_runner); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell); + + bool hasImplicitView; + std::vector viewIds; + fml::AutoResetWaitableEvent reportLatch; + auto nativeViewIdsCallback = [&reportLatch, &hasImplicitView, + &viewIds](Dart_NativeArguments args) { + ParseViewIdsCallback(args, &hasImplicitView, &viewIds); + reportLatch.Signal(); + }; + AddNativeCallback("NativeReportViewIdsCallback", + CREATE_NATIVE_ENTRY(nativeViewIdsCallback)); + + PlatformViewNotifyCreated(shell.get()); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testReportViewIds"); + RunEngine(shell.get(), std::move(configuration)); + reportLatch.Wait(); + + ASSERT_TRUE(hasImplicitView); + ASSERT_EQ(viewIds.size(), 1u); + ASSERT_EQ(viewIds[0], 0ll); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell), task_runners); +} + +// Tests that Shell::AddView and Shell::RemoveView works. +TEST_F(ShellTest, ShellCanAddViewOrRemoveView) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + "io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell); + + bool hasImplicitView; + std::vector viewIds; + fml::AutoResetWaitableEvent reportLatch; + auto nativeViewIdsCallback = [&reportLatch, &hasImplicitView, + &viewIds](Dart_NativeArguments args) { + ParseViewIdsCallback(args, &hasImplicitView, &viewIds); + reportLatch.Signal(); + }; + AddNativeCallback("NativeReportViewIdsCallback", + CREATE_NATIVE_ENTRY(nativeViewIdsCallback)); + + PlatformViewNotifyCreated(shell.get()); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testReportViewIds"); + RunEngine(shell.get(), std::move(configuration)); + + reportLatch.Wait(); + ASSERT_TRUE(hasImplicitView); + ASSERT_EQ(viewIds.size(), 1u); + ASSERT_EQ(viewIds[0], 0ll); + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell] { + shell->GetPlatformView()->AddView(2, ViewportMetrics{}, + [](bool added) { EXPECT_TRUE(added); }); + }); + reportLatch.Wait(); + ASSERT_TRUE(hasImplicitView); + ASSERT_EQ(viewIds.size(), 2u); + ASSERT_EQ(viewIds[1], 2ll); + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell] { + shell->GetPlatformView()->RemoveView( + 2, [](bool removed) { ASSERT_TRUE(removed); }); + }); + reportLatch.Wait(); + ASSERT_TRUE(hasImplicitView); + ASSERT_EQ(viewIds.size(), 1u); + ASSERT_EQ(viewIds[0], 0ll); + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell] { + shell->GetPlatformView()->AddView(4, ViewportMetrics{}, + [](bool added) { EXPECT_TRUE(added); }); + }); + reportLatch.Wait(); + ASSERT_TRUE(hasImplicitView); + ASSERT_EQ(viewIds.size(), 2u); + ASSERT_EQ(viewIds[1], 4ll); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell), task_runners); +} + +// Test that add view fails if the view ID already exists. +TEST_F(ShellTest, ShellCannotAddDuplicateViewId) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + "io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell); + + bool has_implicit_view; + std::vector view_ids; + fml::AutoResetWaitableEvent report_latch; + AddNativeCallback("NativeReportViewIdsCallback", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + ParseViewIdsCallback(args, &has_implicit_view, &view_ids); + report_latch.Signal(); + })); + + PlatformViewNotifyCreated(shell.get()); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testReportViewIds"); + RunEngine(shell.get(), std::move(configuration)); + + report_latch.Wait(); + ASSERT_TRUE(has_implicit_view); + ASSERT_EQ(view_ids.size(), 1u); + ASSERT_EQ(view_ids[0], kImplicitViewId); + + // Add view 123. + fml::AutoResetWaitableEvent add_latch; + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell, + &add_latch] { + shell->GetPlatformView()->AddView(123, ViewportMetrics{}, [&](bool added) { + EXPECT_TRUE(added); + add_latch.Signal(); + }); + }); + + add_latch.Wait(); + + report_latch.Wait(); + ASSERT_EQ(view_ids.size(), 2u); + ASSERT_EQ(view_ids[0], kImplicitViewId); + ASSERT_EQ(view_ids[1], 123); + + // Attempt to add duplicate view ID 123. This should fail. + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell, + &add_latch] { + shell->GetPlatformView()->AddView(123, ViewportMetrics{}, [&](bool added) { + EXPECT_FALSE(added); + add_latch.Signal(); + }); + }); + + add_latch.Wait(); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell), task_runners); +} + +// Test that remove view fails if the view ID does not exist. +TEST_F(ShellTest, ShellCannotRemoveNonexistentId) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + "io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell); + + bool has_implicit_view; + std::vector view_ids; + fml::AutoResetWaitableEvent report_latch; + AddNativeCallback("NativeReportViewIdsCallback", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + ParseViewIdsCallback(args, &has_implicit_view, &view_ids); + report_latch.Signal(); + })); + + PlatformViewNotifyCreated(shell.get()); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testReportViewIds"); + RunEngine(shell.get(), std::move(configuration)); + + report_latch.Wait(); + ASSERT_TRUE(has_implicit_view); + ASSERT_EQ(view_ids.size(), 1u); + ASSERT_EQ(view_ids[0], kImplicitViewId); + + // Remove view 123. This should fail as this view doesn't exist. + fml::AutoResetWaitableEvent remove_latch; + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), + [&shell, &remove_latch] { + shell->GetPlatformView()->RemoveView(123, [&](bool removed) { + EXPECT_FALSE(removed); + remove_latch.Signal(); + }); + }); + + remove_latch.Wait(); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell), task_runners); +} + +// Parse the arguments of NativeReportViewWidthsCallback and +// store them in viewWidths. +static void ParseViewWidthsCallback(const Dart_NativeArguments& args, + std::map* viewWidths) { + Dart_Handle exception = nullptr; + viewWidths->clear(); + std::vector viewWidthPacket = + tonic::DartConverter>::FromArguments(args, 0, + exception); + ASSERT_EQ(exception, nullptr); + ASSERT_EQ(viewWidthPacket.size() % 2, 0ul); + for (size_t packetIndex = 0; packetIndex < viewWidthPacket.size(); + packetIndex += 2) { + (*viewWidths)[viewWidthPacket[packetIndex]] = + viewWidthPacket[packetIndex + 1]; + } +} + +// Ensure that PlatformView::SetViewportMetrics and Shell::AddView that were +// dispatched before the isolate is run have been flushed to the Dart VM when +// the main function starts. +TEST_F(ShellTest, ShellFlushesPlatformStatesByMain) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + "io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell); + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell] { + auto platform_view = shell->GetPlatformView(); + // The construtor for ViewportMetrics{_, width, _, _, _} (only the 2nd + // argument matters in this test). + platform_view->SetViewportMetrics(0, ViewportMetrics{1, 10, 1, 0, 0}); + shell->GetPlatformView()->AddView(1, ViewportMetrics{1, 30, 1, 0, 0}, + [](bool added) { ASSERT_TRUE(added); }); + platform_view->SetViewportMetrics(0, ViewportMetrics{1, 20, 1, 0, 0}); + }); + + bool first_report = true; + std::map viewWidths; + fml::AutoResetWaitableEvent reportLatch; + auto nativeViewWidthsCallback = [&reportLatch, &viewWidths, + &first_report](Dart_NativeArguments args) { + EXPECT_TRUE(first_report); + first_report = false; + ParseViewWidthsCallback(args, &viewWidths); + reportLatch.Signal(); + }; + AddNativeCallback("NativeReportViewWidthsCallback", + CREATE_NATIVE_ENTRY(nativeViewWidthsCallback)); + + PlatformViewNotifyCreated(shell.get()); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testReportViewWidths"); + RunEngine(shell.get(), std::move(configuration)); + + reportLatch.Wait(); + EXPECT_EQ(viewWidths.size(), 2u); + EXPECT_EQ(viewWidths[0], 20ll); + EXPECT_EQ(viewWidths[1], 30ll); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell), task_runners); +} + +// A view can be added and removed before the Dart isolate is launched. +TEST_F(ShellTest, CanRemoveViewBeforeLaunchingIsolate) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + "io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell); + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell] { + auto platform_view = shell->GetPlatformView(); + + // A view can be added and removed all before the isolate launches. + // The pending add view operation is cancelled, the view is never + // added to the Dart isolate. + shell->GetPlatformView()->AddView(123, ViewportMetrics{1, 30, 1, 0, 0}, + [](bool added) { ASSERT_FALSE(added); }); + shell->GetPlatformView()->RemoveView( + 123, [](bool removed) { ASSERT_FALSE(removed); }); + }); + + bool first_report = true; + std::map view_widths; + fml::AutoResetWaitableEvent report_latch; + AddNativeCallback("NativeReportViewWidthsCallback", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + EXPECT_TRUE(first_report); + first_report = false; + ParseViewWidthsCallback(args, &view_widths); + report_latch.Signal(); + })); + + PlatformViewNotifyCreated(shell.get()); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testReportViewWidths"); + RunEngine(shell.get(), std::move(configuration)); + + report_latch.Wait(); + EXPECT_EQ(view_widths.size(), 1u); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell), task_runners); +} + +// Ensure pending "add views" failures are properly flushed when the Dart +// isolate is launched. +TEST_F(ShellTest, IgnoresBadAddViewsBeforeLaunchingIsolate) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + "io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell); + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell] { + auto platform_view = shell->GetPlatformView(); + + // Add the same view twice. The second time should fail. + shell->GetPlatformView()->AddView(123, ViewportMetrics{1, 100, 1, 0, 0}, + [](bool added) { ASSERT_TRUE(added); }); + + shell->GetPlatformView()->AddView(123, ViewportMetrics{1, 200, 1, 0, 0}, + [](bool added) { ASSERT_FALSE(added); }); + + // Add another view. Previous failures should not affect this. + shell->GetPlatformView()->AddView(456, ViewportMetrics{1, 300, 1, 0, 0}, + [](bool added) { ASSERT_TRUE(added); }); + }); + + bool first_report = true; + std::map view_widths; + fml::AutoResetWaitableEvent report_latch; + AddNativeCallback("NativeReportViewWidthsCallback", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + EXPECT_TRUE(first_report); + first_report = false; + ParseViewWidthsCallback(args, &view_widths); + report_latch.Signal(); + })); + + PlatformViewNotifyCreated(shell.get()); + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("testReportViewWidths"); + RunEngine(shell.get(), std::move(configuration)); + + report_latch.Wait(); + EXPECT_EQ(view_widths.size(), 3u); + EXPECT_EQ(view_widths[0], 0); + EXPECT_EQ(view_widths[123], 100); + EXPECT_EQ(view_widths[456], 300); + + PlatformViewNotifyDestroyed(shell.get()); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, RuntimeStageBackendDefaultsToSkSLWithoutImpeller) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + settings.enable_impeller = false; + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + "io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell); + + fml::AutoResetWaitableEvent latch; + AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY([&latch](auto args) { + auto backend = + UIDartState::Current()->GetRuntimeStageBackend(); + EXPECT_EQ(backend, impeller::RuntimeStageBackend::kSkSL); + latch.Signal(); + })); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("mainNotifyNative"); + RunEngine(shell.get(), std::move(configuration)); + + latch.Wait(); + + DestroyShell(std::move(shell), task_runners); +} + +#if IMPELLER_SUPPORTS_RENDERING +TEST_F(ShellTest, RuntimeStageBackendWithImpeller) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + settings.enable_impeller = true; + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + "io.flutter.test." + GetCurrentTestName() + ".", + ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo | ThreadHost::Type::kUi)); + TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell); + + fml::AutoResetWaitableEvent latch; + + impeller::Context::BackendType impeller_backend; + fml::TaskRunner::RunNowOrPostTask( + shell->GetTaskRunners().GetPlatformTaskRunner(), + [platform_view = shell->GetPlatformView(), &latch, &impeller_backend]() { + auto impeller_context = platform_view->GetImpellerContext(); + EXPECT_TRUE(impeller_context); + impeller_backend = impeller_context->GetBackendType(); + latch.Signal(); + }); + latch.Wait(); + + AddNativeCallback( + "NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) { + auto backend = UIDartState::Current()->GetRuntimeStageBackend(); + switch (impeller_backend) { + case impeller::Context::BackendType::kMetal: + EXPECT_EQ(backend, impeller::RuntimeStageBackend::kMetal); + break; + case impeller::Context::BackendType::kOpenGLES: + EXPECT_EQ(backend, impeller::RuntimeStageBackend::kOpenGLES3); + break; + case impeller::Context::BackendType::kVulkan: + EXPECT_EQ(backend, impeller::RuntimeStageBackend::kVulkan); + break; + } + latch.Signal(); + })); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("mainNotifyNative"); + RunEngine(shell.get(), std::move(configuration)); + + latch.Wait(); + + DestroyShell(std::move(shell), task_runners); +} +#endif // IMPELLER_SUPPORTS_RENDERING + +TEST_F(ShellTest, WillLogWarningWhenImpellerIsOptedOut) { +#if !IMPELLER_SUPPORTS_RENDERING + GTEST_SKIP() << "This platform doesn't support Impeller."; +#endif + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + Settings settings = CreateSettingsForFixture(); + settings.enable_impeller = false; + settings.warn_on_impeller_opt_out = true; + // Log captures are thread specific. Just put the shell in single threaded + // configuration. + const auto& runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + TaskRunners task_runners("test", runner, runner, runner, runner); + std::ostringstream stream; + fml::LogMessage::CaptureNextLog(&stream); + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(stream.str().find( + "[Action Required] The application opted out of Impeller") != + std::string::npos); + ASSERT_TRUE(shell); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, SendViewFocusEvent) { + Settings settings = CreateSettingsForFixture(); + TaskRunners task_runners = GetTaskRunnersForFixture(); + fml::AutoResetWaitableEvent latch; + std::string last_event; + + AddNativeCallback( + "NotifyNative", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); })); + + AddNativeCallback("NotifyMessage", + CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + const auto message_from_dart = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + last_event = message_from_dart; + latch.Signal(); + })); + fml::AutoResetWaitableEvent check_latch; + + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell->IsSetup()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + + configuration.SetEntrypoint("testSendViewFocusEvent"); + RunEngine(shell.get(), std::move(configuration)); + latch.Wait(); + latch.Reset(); + + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() { + shell->GetPlatformView()->SendViewFocusEvent(ViewFocusEvent( + 1, ViewFocusState::kFocused, ViewFocusDirection::kUndefined)); + }); + latch.Wait(); + ASSERT_EQ(last_event, + "1 ViewFocusState.focused ViewFocusDirection.undefined"); + + latch.Reset(); + PostSync(shell->GetTaskRunners().GetPlatformTaskRunner(), [&shell]() { + shell->GetPlatformView()->SendViewFocusEvent(ViewFocusEvent( + 2, ViewFocusState::kUnfocused, ViewFocusDirection::kBackward)); + }); + latch.Wait(); + ASSERT_EQ(last_event, + "2 ViewFocusState.unfocused ViewFocusDirection.backward"); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, ProvidesEngineId) { + Settings settings = CreateSettingsForFixture(); + TaskRunners task_runners = GetTaskRunnersForFixture(); + fml::AutoResetWaitableEvent latch; + + std::optional reported_handle = std::nullopt; + + AddNativeCallback( + "ReportEngineId", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + Dart_Handle arg = Dart_GetNativeArgument(args, 0); + if (Dart_IsNull(arg)) { + reported_handle = std::nullopt; + } else { + reported_handle = tonic::DartConverter::FromDart(arg); + } + latch.Signal(); + })); + fml::AutoResetWaitableEvent check_latch; + + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell->IsSetup()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEngineId(99); + configuration.SetEntrypoint("providesEngineId"); + RunEngine(shell.get(), std::move(configuration)); + + latch.Wait(); + ASSERT_EQ(reported_handle, 99); + DestroyShell(std::move(shell), task_runners); +} + +TEST_F(ShellTest, ProvidesNullEngineId) { + Settings settings = CreateSettingsForFixture(); + TaskRunners task_runners = GetTaskRunnersForFixture(); + fml::AutoResetWaitableEvent latch; + + std::optional reported_handle = std::nullopt; + + AddNativeCallback( + "ReportEngineId", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + Dart_Handle arg = Dart_GetNativeArgument(args, 0); + if (Dart_IsNull(arg)) { + reported_handle = std::nullopt; + } else { + reported_handle = tonic::DartConverter::FromDart(arg); + } + latch.Signal(); + })); + fml::AutoResetWaitableEvent check_latch; + + std::unique_ptr shell = CreateShell(settings, task_runners); + ASSERT_TRUE(shell->IsSetup()); + + auto configuration = RunConfiguration::InferFromSettings(settings); + configuration.SetEntrypoint("providesEngineId"); + RunEngine(shell.get(), std::move(configuration)); + + latch.Wait(); + ASSERT_EQ(reported_handle, std::nullopt); + DestroyShell(std::move(shell), task_runners); +} + +} // namespace testing +} // namespace flutter + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/flutter/engine/src/flutter/shell/common/skia_event_tracer_impl.cc b/flutter/engine/src/flutter/shell/common/skia_event_tracer_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..e7c15f4c7e766bee36257808f22e4bb756de946e --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/skia_event_tracer_impl.cc @@ -0,0 +1,337 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/skia_event_tracer_impl.h" + +#define TRACE_EVENT_HIDE_MACROS +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/posix_wrappers.h" +#include "flutter/fml/trace_event.h" +#include "third_party/dart/runtime/include/dart_tools_api.h" +#include "third_party/skia/include/utils/SkEventTracer.h" +#include "third_party/skia/include/utils/SkTraceEventPhase.h" + +#if defined(OS_FUCHSIA) + +#include +#include + +#include +#include + +// Skia's copy of these flags are defined in a private header, so, as is +// commonly done with "trace_event_common.h" values, copy them inline here (see +// https://cs.chromium.org/chromium/src/base/trace_event/common/trace_event_common.h?l=1102-1110&rcl=239b85aeb3a6c07b33b5f162cd0ae8128eabf44d). +// +// Type values for identifying types in the TraceValue union. +#define TRACE_VALUE_TYPE_BOOL (static_cast(1)) +#define TRACE_VALUE_TYPE_UINT (static_cast(2)) +#define TRACE_VALUE_TYPE_INT (static_cast(3)) +#define TRACE_VALUE_TYPE_DOUBLE (static_cast(4)) +#define TRACE_VALUE_TYPE_POINTER (static_cast(5)) +#define TRACE_VALUE_TYPE_STRING (static_cast(6)) +#define TRACE_VALUE_TYPE_COPY_STRING (static_cast(7)) +#define TRACE_VALUE_TYPE_CONVERTABLE (static_cast(8)) + +#endif // defined(OS_FUCHSIA) + +namespace flutter { + +namespace { + +// Skia prepends this string to the category names of its trace events. +// Defined in Skia's src/core/SkTraceEvent.h. +constexpr std::string_view kTraceCategoryPrefix = "disabled-by-default-"; + +// Category name used for shader compilation events. +constexpr std::string_view kShaderCategoryName = + "disabled-by-default-skia.shaders"; + +#if !defined(OS_FUCHSIA) +// Argument name of the tag used by DevTools. +constexpr char kDevtoolsTagArg[] = "devtoolsTag"; + +// DevtoolsTag value for shader events. +constexpr char kShadersDevtoolsTag[] = "shaders"; +#endif // !defined(OS_FUCHSIA) + +#if defined(OS_FUCHSIA) +template +inline T BitCast(const U& u) { + static_assert(sizeof(T) == sizeof(U)); + + T t; + memcpy(&t, &u, sizeof(t)); + return t; +} +#endif // defined(OS_FUCHSIA) + +} // namespace + +class FlutterEventTracer : public SkEventTracer { + public: + static constexpr const char* kSkiaTag = "skia"; + static constexpr uint8_t kYes = 1; + static constexpr uint8_t kNo = 0; + + FlutterEventTracer(bool enabled, + const std::optional>& allowlist) + : enabled_(enabled ? kYes : kNo) { + if (allowlist.has_value()) { + allowlist_.emplace(); + for (const std::string& category : *allowlist) { + allowlist_->insert(std::string(kTraceCategoryPrefix) + category); + } + } + }; + + SkEventTracer::Handle addTraceEvent(char phase, + const uint8_t* category_enabled_flag, + const char* name, + uint64_t id, + int num_args, + const char** p_arg_names, + const uint8_t* p_arg_types, + const uint64_t* p_arg_values, + uint8_t flags) override { +#if defined(OS_FUCHSIA) + static trace_site_t trace_site; + trace_string_ref_t category_ref; + trace_context_t* trace_context = trace_acquire_context_for_category_cached( + kSkiaTag, &trace_site, &category_ref); + + if (likely(!trace_context)) { + return 0; + } + + trace_ticks_t ticks = zx_ticks_get(); + + trace_thread_ref_t thread_ref; + trace_context_register_current_thread(trace_context, &thread_ref); + trace_string_ref_t name_ref; + trace_context_register_string_literal(trace_context, name, &name_ref); + + constexpr int kMaxArgs = 2; + trace_arg_t trace_args[kMaxArgs] = {}; + FML_DCHECK(num_args >= 0); + int num_trace_args = std::min(kMaxArgs, num_args); + + for (int i = 0; i < num_trace_args; i++) { + const char* arg_name = p_arg_names[i]; + const uint8_t arg_type = p_arg_types[i]; + const uint64_t arg_value = p_arg_values[i]; + + trace_string_ref_t arg_name_string_ref = + trace_context_make_registered_string_literal(trace_context, arg_name); + + trace_arg_value_t trace_arg_value; + switch (arg_type) { + case TRACE_VALUE_TYPE_BOOL: { + trace_arg_value = trace_make_bool_arg_value(!!arg_value); + break; + } + case TRACE_VALUE_TYPE_UINT: + trace_arg_value = trace_make_uint64_arg_value(arg_value); + break; + case TRACE_VALUE_TYPE_INT: + trace_arg_value = + trace_make_int64_arg_value(BitCast(arg_value)); + break; + case TRACE_VALUE_TYPE_DOUBLE: + trace_arg_value = + trace_make_double_arg_value(BitCast(arg_value)); + break; + case TRACE_VALUE_TYPE_POINTER: + trace_arg_value = + trace_make_pointer_arg_value(BitCast(arg_value)); + break; + case TRACE_VALUE_TYPE_STRING: { + trace_string_ref_t arg_value_string_ref = + trace_context_make_registered_string_literal( + trace_context, reinterpret_cast(arg_value)); + trace_arg_value = trace_make_string_arg_value(arg_value_string_ref); + break; + } + case TRACE_VALUE_TYPE_COPY_STRING: { + const char* arg_value_as_cstring = + reinterpret_cast(arg_value); + trace_string_ref_t arg_value_string_ref = + trace_context_make_registered_string_copy( + trace_context, arg_value_as_cstring, + strlen(arg_value_as_cstring)); + trace_arg_value = trace_make_string_arg_value(arg_value_string_ref); + break; + } + case TRACE_VALUE_TYPE_CONVERTABLE: + trace_arg_value = trace_make_null_arg_value(); + break; + default: + trace_arg_value = trace_make_null_arg_value(); + } + + trace_args[i] = trace_make_arg(arg_name_string_ref, trace_arg_value); + } + + switch (phase) { + case TRACE_EVENT_PHASE_BEGIN: + case TRACE_EVENT_PHASE_COMPLETE: + trace_context_write_duration_begin_event_record( + trace_context, ticks, &thread_ref, &category_ref, &name_ref, + trace_args, num_trace_args); + break; + case TRACE_EVENT_PHASE_END: + trace_context_write_duration_end_event_record( + trace_context, ticks, &thread_ref, &category_ref, &name_ref, + trace_args, num_trace_args); + break; + case TRACE_EVENT_PHASE_INSTANT: + trace_context_write_instant_event_record( + trace_context, ticks, &thread_ref, &category_ref, &name_ref, + TRACE_SCOPE_THREAD, trace_args, num_trace_args); + break; + case TRACE_EVENT_PHASE_ASYNC_BEGIN: + trace_context_write_async_begin_event_record( + trace_context, ticks, &thread_ref, &category_ref, &name_ref, id, + trace_args, num_trace_args); + break; + case TRACE_EVENT_PHASE_ASYNC_END: + trace_context_write_async_end_event_record( + trace_context, ticks, &thread_ref, &category_ref, &name_ref, id, + trace_args, num_trace_args); + break; + default: + break; + } + + trace_release_context(trace_context); + +#else // defined(OS_FUCHSIA) + const char* devtoolsTag = nullptr; + if (shaders_category_flag_ && + category_enabled_flag == shaders_category_flag_) { + devtoolsTag = kShadersDevtoolsTag; + } + switch (phase) { + case TRACE_EVENT_PHASE_BEGIN: + case TRACE_EVENT_PHASE_COMPLETE: + if (devtoolsTag) { + fml::tracing::TraceEvent1(kSkiaTag, name, /*flow_id_count=*/0, + /*flow_ids=*/nullptr, kDevtoolsTagArg, + devtoolsTag); + } else { + fml::tracing::TraceEvent0(kSkiaTag, name, /*flow_id_count=*/0, + /*flow_ids=*/nullptr); + } + break; + case TRACE_EVENT_PHASE_END: + fml::tracing::TraceEventEnd(name); + break; + case TRACE_EVENT_PHASE_INSTANT: + if (devtoolsTag) { + fml::tracing::TraceEventInstant1(kSkiaTag, name, + /*flow_id_count=*/0, + /*flow_ids=*/nullptr, + kDevtoolsTagArg, devtoolsTag); + } else { + fml::tracing::TraceEventInstant0(kSkiaTag, name, + /*flow_id_count=*/0, + /*flow_ids=*/nullptr); + } + break; + case TRACE_EVENT_PHASE_ASYNC_BEGIN: + if (devtoolsTag) { + fml::tracing::TraceEventAsyncBegin1(kSkiaTag, name, id, + /*flow_id_count=*/0, + /*flow_ids=*/nullptr, + kDevtoolsTagArg, devtoolsTag); + } else { + fml::tracing::TraceEventAsyncBegin0(kSkiaTag, name, id, + /*flow_id_count=*/0, + /*flow_ids=*/nullptr); + } + break; + case TRACE_EVENT_PHASE_ASYNC_END: + if (devtoolsTag) { + fml::tracing::TraceEventAsyncEnd1(kSkiaTag, name, id, kDevtoolsTagArg, + devtoolsTag); + } else { + fml::tracing::TraceEventAsyncEnd0(kSkiaTag, name, id); + } + break; + default: + break; + } +#endif // defined(OS_FUCHSIA) + return 0; + } + + void updateTraceEventDuration(const uint8_t* category_enabled_flag, + const char* name, + SkEventTracer::Handle handle) override { + // This is only ever called from a scoped trace event so we will just end + // the section. +#if defined(OS_FUCHSIA) + TRACE_DURATION_END(kSkiaTag, name); +#else + fml::tracing::TraceEventEnd(name); +#endif + } + + const uint8_t* getCategoryGroupEnabled(const char* name) override { + // Skia will only use long-lived string literals as event names. + std::lock_guard lock(flag_map_mutex_); + auto flag_it = category_flag_map_.find(name); + if (flag_it == category_flag_map_.end()) { + bool allowed; + if (enabled_) { + allowed = !allowlist_.has_value() || + allowlist_->find(name) != allowlist_->end(); + } else { + allowed = false; + } + flag_it = category_flag_map_.insert(std::make_pair(name, allowed)).first; + const uint8_t* flag = &flag_it->second; + reverse_flag_map_.insert(std::make_pair(flag, name)); + if (kShaderCategoryName == name) { + shaders_category_flag_ = flag; + } + } + return &flag_it->second; + } + + const char* getCategoryGroupName( + const uint8_t* category_enabled_flag) override { + std::lock_guard lock(flag_map_mutex_); + auto reverse_it = reverse_flag_map_.find(category_enabled_flag); + if (reverse_it != reverse_flag_map_.end()) { + return reverse_it->second; + } else { + return kSkiaTag; + } + } + + private: + uint8_t enabled_; + std::optional> allowlist_; + std::mutex flag_map_mutex_; + std::map category_flag_map_; + std::map reverse_flag_map_; + const uint8_t* shaders_category_flag_ = nullptr; + FML_DISALLOW_COPY_AND_ASSIGN(FlutterEventTracer); +}; + +void InitSkiaEventTracer( + bool enabled, + const std::optional>& allowlist) { + auto tracer = new FlutterEventTracer(enabled, allowlist); + // Initialize the binding to Skia's tracing events. Skia will + // take ownership of and clean up the memory allocated here. + SkEventTracer::SetInstance(tracer); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/skia_event_tracer_impl.h b/flutter/engine/src/flutter/shell/common/skia_event_tracer_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..aa5fe2305724693c393a6eee4876bd8916f8b68f --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/skia_event_tracer_impl.h @@ -0,0 +1,21 @@ +// 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_COMMON_SKIA_EVENT_TRACER_IMPL_H_ +#define FLUTTER_SHELL_COMMON_SKIA_EVENT_TRACER_IMPL_H_ + +#include +#include +#include +#include + +namespace flutter { + +void InitSkiaEventTracer( + bool enabled, + const std::optional>& allowlist); + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SKIA_EVENT_TRACER_IMPL_H_ diff --git a/flutter/engine/src/flutter/shell/common/snapshot_controller.cc b/flutter/engine/src/flutter/shell/common/snapshot_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..ebde42d9cf024094b77bf162caf11b9fbf4118a2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/snapshot_controller.cc @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/snapshot_controller.h" + +#include "flutter/shell/common/snapshot_controller_skia.h" + +#if IMPELLER_SUPPORTS_RENDERING +#include "flutter/shell/common/snapshot_controller_impeller.h" +#endif // IMPELLER_SUPPORTS_RENDERING + +namespace flutter { + +std::unique_ptr SnapshotController::Make( + const Delegate& delegate, + const Settings& settings) { +#if IMPELLER_SUPPORTS_RENDERING + if (settings.enable_impeller) { + return std::make_unique(delegate); + } +#endif // IMPELLER_SUPPORTS_RENDERING +#if !SLIMPELLER + return std::make_unique(delegate); +#else // !SLIMPELLER + FML_LOG(FATAL) + << "Cannot create a Skia snapshot controller in an Impeller build."; + return nullptr; +#endif // !SLIMPELLER +} + +SnapshotController::SnapshotController(const Delegate& delegate) + : delegate_(delegate) {} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/snapshot_controller.h b/flutter/engine/src/flutter/shell/common/snapshot_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..442d456fb2cbdbf3d21822025237922de459b9b9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/snapshot_controller.h @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_H_ +#define FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_H_ + +#include "flutter/common/settings.h" +#include "flutter/display_list/image/dl_image.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/synchronization/sync_switch.h" +#include "flutter/lib/ui/snapshot_delegate.h" +#include "flutter/shell/common/snapshot_surface_producer.h" + +namespace impeller { +class AiksContext; +} + +namespace flutter { + +class SnapshotController { + public: + class Delegate { + public: + virtual ~Delegate() = default; + virtual const std::unique_ptr& GetSurface() const = 0; + virtual bool IsAiksContextInitialized() const = 0; + virtual std::shared_ptr GetAiksContext() const = 0; + virtual const std::unique_ptr& + GetSnapshotSurfaceProducer() const = 0; + virtual std::shared_ptr GetIsGpuDisabledSyncSwitch() + const = 0; + }; + + static std::unique_ptr Make(const Delegate& delegate, + const Settings& settings); + + virtual ~SnapshotController() = default; + + virtual void MakeRasterSnapshot( + sk_sp display_list, + SkISize picture_size, + std::function&)> callback) = 0; + + // Note that this image is not guaranteed to be UIThreadSafe and must + // be converted to a DlImageGPU if it is to be handed back to the UI + // thread. + virtual sk_sp MakeRasterSnapshotSync(sk_sp display_list, + SkISize picture_size) = 0; + + virtual sk_sp ConvertToRasterImage(sk_sp image) = 0; + + virtual void CacheRuntimeStage( + const std::shared_ptr& runtime_stage) = 0; + + protected: + explicit SnapshotController(const Delegate& delegate); + const Delegate& GetDelegate() { return delegate_; } + + private: + const Delegate& delegate_; + + FML_DISALLOW_COPY_AND_ASSIGN(SnapshotController); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_H_ diff --git a/flutter/engine/src/flutter/shell/common/snapshot_controller_impeller.cc b/flutter/engine/src/flutter/shell/common/snapshot_controller_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..119db75b367c1254267feb7cd218fde39c99f7f1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/snapshot_controller_impeller.cc @@ -0,0 +1,166 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/snapshot_controller_impeller.h" + +#include + +#include "flutter/flow/surface.h" +#include "flutter/fml/build_config.h" +#include "flutter/fml/trace_event.h" +#include "flutter/impeller/display_list/dl_dispatcher.h" +#include "flutter/impeller/display_list/dl_image_impeller.h" +#include "flutter/impeller/geometry/size.h" +#include "flutter/shell/common/snapshot_controller.h" +#include "impeller/entity/contents/runtime_effect_contents.h" + +namespace flutter { + +namespace { + +sk_sp DoMakeRasterSnapshot( + const sk_sp& display_list, + SkISize size, + const std::shared_ptr& context) { + TRACE_EVENT0("flutter", __FUNCTION__); + if (!context) { + return nullptr; + } + // Determine render target size. + auto max_size = context->GetContext() + ->GetResourceAllocator() + ->GetMaxTextureSizeSupported(); + double scale_factor_x = + static_cast(max_size.width) / static_cast(size.width()); + double scale_factor_y = + static_cast(max_size.height) / static_cast(size.height()); + double scale_factor = std::min({1.0, scale_factor_x, scale_factor_y}); + + auto render_target_size = impeller::ISize(size.width(), size.height()); + + // Scale down the render target size to the max supported by the + // GPU if necessary. Exceeding the max would otherwise cause a + // null result. + if (scale_factor < 1.0) { + render_target_size.width *= scale_factor; + render_target_size.height *= scale_factor; + } + + return impeller::DlImageImpeller::Make( + impeller::DisplayListToTexture(display_list, render_target_size, *context, + /*reset_host_buffer=*/false, + /*generate_mips=*/true), + DlImage::OwningContext::kRaster); +} + +sk_sp DoMakeRasterSnapshot( + const sk_sp& display_list, + SkISize size, + const SnapshotController::Delegate& delegate) { + // Ensure that the current thread has a rendering context. This must be done + // before calling GetAiksContext because constructing the AiksContext may + // invoke graphics APIs. + std::unique_ptr pbuffer_surface; + if (delegate.GetSurface()) { + delegate.GetSurface()->MakeRenderContextCurrent(); + } else if (delegate.GetSnapshotSurfaceProducer()) { + pbuffer_surface = + delegate.GetSnapshotSurfaceProducer()->CreateSnapshotSurface(); + if (pbuffer_surface) { + pbuffer_surface->MakeRenderContextCurrent(); + } + } + + return DoMakeRasterSnapshot(display_list, size, delegate.GetAiksContext()); +} + +sk_sp DoMakeRasterSnapshot( + sk_sp display_list, + SkISize picture_size, + const std::shared_ptr& sync_switch, + const std::shared_ptr& context) { + sk_sp result; + sync_switch->Execute(fml::SyncSwitch::Handlers() + .SetIfTrue([&] { + // Do nothing. + }) + .SetIfFalse([&] { + result = DoMakeRasterSnapshot( + display_list, picture_size, context); + })); + + return result; +} +} // namespace + +void SnapshotControllerImpeller::MakeRasterSnapshot( + sk_sp display_list, + SkISize picture_size, + std::function&)> callback) { + std::shared_ptr sync_switch = + GetDelegate().GetIsGpuDisabledSyncSwitch(); + sync_switch->Execute( + fml::SyncSwitch::Handlers() + .SetIfTrue([&] { + std::shared_ptr context = + GetDelegate().GetAiksContext(); + if (context) { + context->GetContext()->StoreTaskForGPU( + [context, sync_switch, display_list = std::move(display_list), + picture_size, callback] { + callback(DoMakeRasterSnapshot(display_list, picture_size, + sync_switch, context)); + }, + [callback]() { callback(nullptr); }); + } else { +#if FML_OS_IOS_SIMULATOR + callback(impeller::DlImageImpeller::Make( + nullptr, DlImage::OwningContext::kRaster, + /*is_fake_image=*/true)); +#else + callback(nullptr); + +#endif // FML_OS_IOS_SIMULATOR + } + }) + .SetIfFalse([&] { +#if FML_OS_IOS_SIMULATOR + if (!GetDelegate().GetAiksContext()) { + callback(impeller::DlImageImpeller::Make( + nullptr, DlImage::OwningContext::kRaster, + /*is_fake_image=*/true)); + return; + } +#endif + callback(DoMakeRasterSnapshot(display_list, picture_size, + GetDelegate())); + })); +} + +sk_sp SnapshotControllerImpeller::MakeRasterSnapshotSync( + sk_sp display_list, + SkISize picture_size) { + return DoMakeRasterSnapshot(display_list, picture_size, GetDelegate()); +} + +void SnapshotControllerImpeller::CacheRuntimeStage( + const std::shared_ptr& runtime_stage) { + if (!GetDelegate().IsAiksContextInitialized()) { + return; + } + auto context = GetDelegate().GetAiksContext(); + if (!context) { + return; + } + impeller::RuntimeEffectContents runtime_effect; + runtime_effect.SetRuntimeStage(runtime_stage); + runtime_effect.BootstrapShader(context->GetContentContext()); +} + +sk_sp SnapshotControllerImpeller::ConvertToRasterImage( + sk_sp image) { + FML_UNREACHABLE(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/snapshot_controller_impeller.h b/flutter/engine/src/flutter/shell/common/snapshot_controller_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..9d7e53b4bee8f73c288bad0264d33037c1a45ede --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/snapshot_controller_impeller.h @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_IMPELLER_H_ +#define FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_IMPELLER_H_ + +#include "flutter/shell/common/snapshot_controller.h" +#include "impeller/runtime_stage/runtime_stage.h" + +namespace flutter { + +class SnapshotControllerImpeller : public SnapshotController { + public: + explicit SnapshotControllerImpeller( + const SnapshotController::Delegate& delegate) + : SnapshotController(delegate) {} + + void MakeRasterSnapshot( + sk_sp display_list, + SkISize picture_size, + std::function&)> callback) override; + + sk_sp MakeRasterSnapshotSync(sk_sp display_list, + SkISize picture_size) override; + + sk_sp ConvertToRasterImage(sk_sp image) override; + + void CacheRuntimeStage( + const std::shared_ptr& runtime_stage) override; + + private: + FML_DISALLOW_COPY_AND_ASSIGN(SnapshotControllerImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/common/snapshot_controller_skia.cc b/flutter/engine/src/flutter/shell/common/snapshot_controller_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..539736893562e0e7acdb27649c740697733e7f87 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/snapshot_controller_skia.cc @@ -0,0 +1,177 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#if !SLIMPELLER + +#include "flutter/shell/common/snapshot_controller_skia.h" + +#include "display_list/image/dl_image.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/trace_event.h" +#include "flutter/shell/common/snapshot_controller.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" + +namespace flutter { + +namespace { +sk_sp DrawSnapshot( + const sk_sp& surface, + const std::function& draw_callback) { + if (surface == nullptr || surface->getCanvas() == nullptr) { + return nullptr; + } + + draw_callback(surface->getCanvas()); + auto dContext = GrAsDirectContext(surface->recordingContext()); + if (dContext) { + dContext->flushAndSubmit(); + } + + sk_sp device_snapshot; + { + TRACE_EVENT0("flutter", "MakeDeviceSnapshot"); + device_snapshot = surface->makeImageSnapshot(); + } + + if (device_snapshot == nullptr) { + return nullptr; + } + + { + TRACE_EVENT0("flutter", "DeviceHostTransfer"); + if (auto raster_image = device_snapshot->makeRasterImage()) { + return raster_image; + } + } + + return nullptr; +} +} // namespace + +void SnapshotControllerSkia::MakeRasterSnapshot( + sk_sp display_list, + SkISize picture_size, + std::function&)> callback) { + callback(MakeRasterSnapshotSync(display_list, picture_size)); +} + +sk_sp SnapshotControllerSkia::DoMakeRasterSnapshot( + SkISize size, + std::function draw_callback) { + TRACE_EVENT0("flutter", __FUNCTION__); + sk_sp result; + SkImageInfo image_info = SkImageInfo::MakeN32Premul( + size.width(), size.height(), SkColorSpace::MakeSRGB()); + + std::unique_ptr pbuffer_surface; + Surface* snapshot_surface = nullptr; + auto& delegate = GetDelegate(); + if (delegate.GetSurface() && delegate.GetSurface()->GetContext()) { + snapshot_surface = delegate.GetSurface().get(); + } else if (delegate.GetSnapshotSurfaceProducer()) { + pbuffer_surface = + delegate.GetSnapshotSurfaceProducer()->CreateSnapshotSurface(); + if (pbuffer_surface && pbuffer_surface->GetContext()) { + snapshot_surface = pbuffer_surface.get(); + } + } + + if (!snapshot_surface) { + // Raster surface is fine if there is no on screen surface. This might + // happen in case of software rendering. + sk_sp sk_surface = SkSurfaces::Raster(image_info); + result = DrawSnapshot(sk_surface, draw_callback); + } else { + delegate.GetIsGpuDisabledSyncSwitch()->Execute( + fml::SyncSwitch::Handlers() + .SetIfTrue([&] { + sk_sp surface = SkSurfaces::Raster(image_info); + result = DrawSnapshot(surface, draw_callback); + }) + .SetIfFalse([&] { + FML_DCHECK(snapshot_surface); + auto context_switch = + snapshot_surface->MakeRenderContextCurrent(); + if (!context_switch->GetResult()) { + return; + } + + GrRecordingContext* context = snapshot_surface->GetContext(); + auto max_size = context->maxRenderTargetSize(); + double scale_factor = std::min( + 1.0, static_cast(max_size) / + static_cast(std::max(image_info.width(), + image_info.height()))); + + // Scale down the render target size to the max supported by the + // GPU if necessary. Exceeding the max would otherwise cause a + // null result. + if (scale_factor < 1.0) { + image_info = image_info.makeWH( + static_cast(image_info.width()) * scale_factor, + static_cast(image_info.height()) * scale_factor); + } + + // When there is an on screen surface, we need a render target + // SkSurface because we want to access texture backed images. + sk_sp sk_surface = + SkSurfaces::RenderTarget(context, // context + skgpu::Budgeted::kNo, // budgeted + image_info // image info + ); + if (!sk_surface) { + FML_LOG(ERROR) + << "DoMakeRasterSnapshot can not create GPU render target"; + return; + } + + sk_surface->getCanvas()->scale(scale_factor, scale_factor); + result = DrawSnapshot(sk_surface, draw_callback); + })); + } + + // It is up to the caller to create a DlImageGPU version of this image + // if the result will interact with the UI thread. + return DlImage::Make(result); +} + +sk_sp SnapshotControllerSkia::MakeRasterSnapshotSync( + sk_sp display_list, + SkISize size) { + return DoMakeRasterSnapshot(size, [display_list](SkCanvas* canvas) { + DlSkCanvasAdapter(canvas).DrawDisplayList(display_list); + }); +} + +sk_sp SnapshotControllerSkia::ConvertToRasterImage( + sk_sp image) { + // If the rasterizer does not have a surface with a GrContext, then it will + // be unable to render a cross-context SkImage. The caller will need to + // create the raster image on the IO thread. + if (GetDelegate().GetSurface() == nullptr || + GetDelegate().GetSurface()->GetContext() == nullptr) { + return nullptr; + } + + if (image == nullptr) { + return nullptr; + } + + SkISize image_size = image->dimensions(); + + auto result = DoMakeRasterSnapshot( + image_size, [image = std::move(image)](SkCanvas* canvas) { + canvas->drawImage(image, 0, 0); + }); + return result->skia_image(); +} + +void SnapshotControllerSkia::CacheRuntimeStage( + const std::shared_ptr& runtime_stage) {} + +} // namespace flutter + +#endif // !SLIMPELLER diff --git a/flutter/engine/src/flutter/shell/common/snapshot_controller_skia.h b/flutter/engine/src/flutter/shell/common/snapshot_controller_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..a9c755ce218078aed9ec4d3a01aeffaa3eb608e6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/snapshot_controller_skia.h @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_SKIA_H_ +#define FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_SKIA_H_ + +#if !SLIMPELLER + +#include "flutter/shell/common/snapshot_controller.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { + +class SnapshotControllerSkia : public SnapshotController { + public: + explicit SnapshotControllerSkia(const SnapshotController::Delegate& delegate) + : SnapshotController(delegate) {} + + void MakeRasterSnapshot( + sk_sp display_list, + SkISize picture_size, + std::function&)> callback) override; + + sk_sp MakeRasterSnapshotSync(sk_sp display_list, + SkISize size) override; + + virtual sk_sp ConvertToRasterImage(sk_sp image) override; + + void CacheRuntimeStage( + const std::shared_ptr& runtime_stage) override; + + private: + sk_sp DoMakeRasterSnapshot( + SkISize size, + std::function draw_callback); + + FML_DISALLOW_COPY_AND_ASSIGN(SnapshotControllerSkia); +}; + +} // namespace flutter + +#endif // !SLIMPELLER + +#endif // FLUTTER_SHELL_COMMON_SNAPSHOT_CONTROLLER_SKIA_H_ diff --git a/flutter/engine/src/flutter/shell/common/snapshot_surface_producer.h b/flutter/engine/src/flutter/shell/common/snapshot_surface_producer.h new file mode 100644 index 0000000000000000000000000000000000000000..9c61ff1e293fca8474cf1ff4c52c75a0b8320e6e --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/snapshot_surface_producer.h @@ -0,0 +1,22 @@ +// 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_COMMON_SNAPSHOT_SURFACE_PRODUCER_H_ +#define FLUTTER_SHELL_COMMON_SNAPSHOT_SURFACE_PRODUCER_H_ + +#include + +#include "flutter/flow/surface.h" + +namespace flutter { + +class SnapshotSurfaceProducer { + public: + virtual ~SnapshotSurfaceProducer() = default; + + virtual std::unique_ptr CreateSnapshotSurface() = 0; +}; + +} // namespace flutter +#endif // FLUTTER_SHELL_COMMON_SNAPSHOT_SURFACE_PRODUCER_H_ diff --git a/flutter/engine/src/flutter/shell/common/switches.cc b/flutter/engine/src/flutter/shell/common/switches.cc new file mode 100644 index 0000000000000000000000000000000000000000..eeec6951d4ecd97cd3e70690d31750a63f3971ba --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/switches.cc @@ -0,0 +1,543 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/native_library.h" +#include "flutter/fml/paths.h" +#include "flutter/shell/version/version.h" + +// Include once for the default enum definition. +#include "flutter/shell/common/switches.h" + +#undef FLUTTER_SHELL_COMMON_SWITCHES_H_ + +struct SwitchDesc { + flutter::Switch sw; + const std::string_view flag; + const char* help; +}; + +#undef DEF_SWITCHES_START +#undef DEF_SWITCH +#undef DEF_SWITCHES_END + +// clang-format off +#define DEF_SWITCHES_START static const struct SwitchDesc gSwitchDescs[] = { +#define DEF_SWITCH(p_swtch, p_flag, p_help) \ + { flutter::Switch:: p_swtch, p_flag, p_help }, +#define DEF_SWITCHES_END }; +// clang-format on + +// List of common and safe VM flags to allow to be passed directly to the VM. +#if FLUTTER_RELEASE + +// clang-format off +static const std::string kAllowedDartFlags[] = { + "--enable-isolate-groups", + "--no-enable-isolate-groups", +}; +// clang-format on + +#else + +// clang-format off +static const std::string kAllowedDartFlags[] = { + "--enable-isolate-groups", + "--no-enable-isolate-groups", + "--enable_mirrors", + "--enable-service-port-fallback", + "--max_profile_depth", + "--profile_period", + "--random_seed", + "--sample-buffer-duration", + "--trace-kernel", + "--trace-reload", + "--trace-reload-verbose", + "--write-service-info", + "--max_subtype_cache_entries", + "--enable-asserts", +}; +// clang-format on + +#endif // FLUTTER_RELEASE + +// Include again for struct definition. +#include "flutter/shell/common/switches.h" + +// Define symbols for the ICU data that is linked into the Flutter library on +// Android. This is a workaround for crashes seen when doing dynamic lookups +// of the engine's own symbols on some older versions of Android. +#if FML_OS_ANDROID +extern uint8_t _binary_icudtl_dat_start[]; +extern size_t _binary_icudtl_dat_size; + +static std::unique_ptr GetICUStaticMapping() { + return std::make_unique(_binary_icudtl_dat_start, + _binary_icudtl_dat_size); +} +#endif + +namespace flutter { + +void PrintUsage(const std::string& executable_name) { + std::cerr << std::endl << " " << executable_name << std::endl << std::endl; + + std::cerr << "Versions: " << std::endl << std::endl; + + std::cerr << "Flutter Engine Version: " << GetFlutterEngineVersion() + << std::endl; + std::cerr << "Skia Version: " << GetSkiaVersion() << std::endl; + + std::cerr << "Dart Version: " << GetDartVersion() << std::endl << std::endl; + + std::cerr << "Available Flags:" << std::endl; + + const uint32_t column_width = 80; + + const uint32_t flags_count = static_cast(Switch::Sentinel); + + uint32_t max_width = 2; + for (uint32_t i = 0; i < flags_count; i++) { + auto desc = gSwitchDescs[i]; + max_width = std::max(desc.flag.size() + 2, max_width); + } + + const uint32_t help_width = column_width - max_width - 3; + + std::cerr << std::string(column_width, '-') << std::endl; + for (uint32_t i = 0; i < flags_count; i++) { + auto desc = gSwitchDescs[i]; + + std::cerr << std::setw(max_width) + << std::string("--") + + std::string{desc.flag.data(), desc.flag.size()} + << " : "; + + std::istringstream stream(desc.help); + int32_t remaining = help_width; + + std::string word; + while (stream >> word && remaining > 0) { + remaining -= (word.size() + 1); + if (remaining <= 0) { + std::cerr << std::endl + << std::string(max_width, ' ') << " " << word << " "; + remaining = help_width; + } else { + std::cerr << word << " "; + } + } + + std::cerr << std::endl; + } + std::cerr << std::string(column_width, '-') << std::endl; +} + +const std::string_view FlagForSwitch(Switch swtch) { + for (uint32_t i = 0; i < static_cast(Switch::Sentinel); i++) { + if (gSwitchDescs[i].sw == swtch) { + return gSwitchDescs[i].flag; + } + } + return std::string_view(); +} + +static std::vector ParseCommaDelimited(const std::string& input) { + std::istringstream ss(input); + std::vector result; + std::string token; + while (std::getline(ss, token, ',')) { + result.push_back(token); + } + return result; +} + +static bool IsAllowedDartVMFlag(const std::string& flag) { + for (uint32_t i = 0; i < std::size(kAllowedDartFlags); ++i) { + const std::string& allowed = kAllowedDartFlags[i]; + // Check that the prefix of the flag matches one of the allowed flags. This + // is to handle cases where flags take arguments, such as in + // "--max_profile_depth 1". + // + // We don't need to worry about cases like "--safe --sneaky_dangerous" as + // the VM will discard these as a single unrecognized flag. + if (flag.length() >= allowed.length() && + std::equal(allowed.begin(), allowed.end(), flag.begin())) { + return true; + } + } + return false; +} + +template +static bool GetSwitchValue(const fml::CommandLine& command_line, + Switch sw, + T* result) { + std::string switch_string; + + if (!command_line.GetOptionValue(FlagForSwitch(sw), &switch_string)) { + return false; + } + + std::stringstream stream(switch_string); + T value = 0; + if (stream >> value) { + *result = value; + return true; + } + + return false; +} + +std::unique_ptr GetSymbolMapping( + const std::string& symbol_prefix, + const std::string& native_lib_path) { + const uint8_t* mapping = nullptr; + intptr_t size; + + auto lookup_symbol = [&mapping, &size, symbol_prefix]( + const fml::RefPtr& library) { + mapping = library->ResolveSymbol((symbol_prefix + "_start").c_str()); + size = reinterpret_cast( + library->ResolveSymbol((symbol_prefix + "_size").c_str())); + }; + + fml::RefPtr library = + fml::NativeLibrary::CreateForCurrentProcess(); + lookup_symbol(library); + + if (!(mapping && size)) { + // Symbol lookup for the current process fails on some devices. As a + // fallback, try doing the lookup based on the path to the Flutter library. + library = fml::NativeLibrary::Create(native_lib_path.c_str()); + lookup_symbol(library); + } + + FML_CHECK(mapping && size) << "Unable to resolve symbols: " << symbol_prefix; + return std::make_unique(mapping, size); +} + +Settings SettingsFromCommandLine(const fml::CommandLine& command_line) { + Settings settings = {}; + + // Set executable name. + if (command_line.has_argv0()) { + settings.executable_name = command_line.argv0(); + } + + // Enable the VM Service + settings.enable_vm_service = + !command_line.HasOption(FlagForSwitch(Switch::DisableVMService)) && + // TODO(bkonyi): remove once flutter_tools no longer uses this option. + // See https://github.com/dart-lang/sdk/issues/50233 + !command_line.HasOption(FlagForSwitch(Switch::DisableObservatory)); + + // Enable mDNS VM Service Publication + settings.enable_vm_service_publication = + !command_line.HasOption( + FlagForSwitch(Switch::DisableVMServicePublication)) && + !command_line.HasOption( + FlagForSwitch(Switch::DisableObservatoryPublication)); + + // Set VM Service Host + if (command_line.HasOption(FlagForSwitch(Switch::DeviceVMServiceHost))) { + command_line.GetOptionValue(FlagForSwitch(Switch::DeviceVMServiceHost), + &settings.vm_service_host); + } else if (command_line.HasOption( + FlagForSwitch(Switch::DeviceObservatoryHost))) { + // TODO(bkonyi): remove once flutter_tools no longer uses this option. + // See https://github.com/dart-lang/sdk/issues/50233 + command_line.GetOptionValue(FlagForSwitch(Switch::DeviceObservatoryHost), + &settings.vm_service_host); + } + // Default the VM Service port based on --ipv6 if not set. + if (settings.vm_service_host.empty()) { + settings.vm_service_host = + command_line.HasOption(FlagForSwitch(Switch::IPv6)) ? "::1" + : "127.0.0.1"; + } + + // Set VM Service Port + if (command_line.HasOption(FlagForSwitch(Switch::DeviceVMServicePort))) { + if (!GetSwitchValue(command_line, Switch::DeviceVMServicePort, + &settings.vm_service_port)) { + FML_LOG(INFO) + << "VM Service port specified was malformed. Will default to " + << settings.vm_service_port; + } + } else if (command_line.HasOption( + FlagForSwitch(Switch::DeviceObservatoryPort))) { + // TODO(bkonyi): remove once flutter_tools no longer uses this option. + // See https://github.com/dart-lang/sdk/issues/50233 + if (!GetSwitchValue(command_line, Switch::DeviceObservatoryPort, + &settings.vm_service_port)) { + FML_LOG(INFO) + << "VM Service port specified was malformed. Will default to " + << settings.vm_service_port; + } + } + + settings.may_insecurely_connect_to_all_domains = !command_line.HasOption( + FlagForSwitch(Switch::DisallowInsecureConnections)); + + command_line.GetOptionValue(FlagForSwitch(Switch::DomainNetworkPolicy), + &settings.domain_network_policy); + + // Disable need for authentication codes for VM service communication, if + // specified. + settings.disable_service_auth_codes = + command_line.HasOption(FlagForSwitch(Switch::DisableServiceAuthCodes)); + + // Allow fallback to automatic port selection if binding to a specified port + // fails. + settings.enable_service_port_fallback = + command_line.HasOption(FlagForSwitch(Switch::EnableServicePortFallback)); + + // Checked mode overrides. + settings.disable_dart_asserts = + command_line.HasOption(FlagForSwitch(Switch::DisableDartAsserts)); + + settings.start_paused = + command_line.HasOption(FlagForSwitch(Switch::StartPaused)); + + settings.enable_checked_mode = + command_line.HasOption(FlagForSwitch(Switch::EnableCheckedMode)); + + settings.enable_dart_profiling = + command_line.HasOption(FlagForSwitch(Switch::EnableDartProfiling)); + + settings.enable_software_rendering = + command_line.HasOption(FlagForSwitch(Switch::EnableSoftwareRendering)); + + settings.endless_trace_buffer = + command_line.HasOption(FlagForSwitch(Switch::EndlessTraceBuffer)); + + settings.trace_startup = + command_line.HasOption(FlagForSwitch(Switch::TraceStartup)); + + settings.enable_serial_gc = + command_line.HasOption(FlagForSwitch(Switch::EnableSerialGC)); + +#if !FLUTTER_RELEASE + settings.trace_skia = true; + + if (command_line.HasOption(FlagForSwitch(Switch::TraceSkia))) { + // If --trace-skia is specified, then log all Skia events. + settings.trace_skia_allowlist.reset(); + } else { + std::string trace_skia_allowlist; + command_line.GetOptionValue(FlagForSwitch(Switch::TraceSkiaAllowlist), + &trace_skia_allowlist); + if (trace_skia_allowlist.size()) { + settings.trace_skia_allowlist = ParseCommaDelimited(trace_skia_allowlist); + } else { + settings.trace_skia_allowlist = {"skia.shaders"}; + } + } +#endif // !FLUTTER_RELEASE + + std::string trace_allowlist; + command_line.GetOptionValue(FlagForSwitch(Switch::TraceAllowlist), + &trace_allowlist); + settings.trace_allowlist = ParseCommaDelimited(trace_allowlist); + + settings.trace_systrace = + command_line.HasOption(FlagForSwitch(Switch::TraceSystrace)); + + command_line.GetOptionValue(FlagForSwitch(Switch::TraceToFile), + &settings.trace_to_file); + + settings.skia_deterministic_rendering_on_cpu = + command_line.HasOption(FlagForSwitch(Switch::SkiaDeterministicRendering)); + + settings.verbose_logging = + command_line.HasOption(FlagForSwitch(Switch::VerboseLogging)); + + command_line.GetOptionValue(FlagForSwitch(Switch::FlutterAssetsDir), + &settings.assets_path); + + std::vector aot_shared_library_name = + command_line.GetOptionValues(FlagForSwitch(Switch::AotSharedLibraryName)); + + std::vector vmservice_shared_library_name = + command_line.GetOptionValues( + FlagForSwitch(Switch::AotVMServiceSharedLibraryName)); + for (auto path : vmservice_shared_library_name) { + settings.vmservice_snapshot_library_path.emplace_back(path); + } + + std::string snapshot_asset_path; + command_line.GetOptionValue(FlagForSwitch(Switch::SnapshotAssetPath), + &snapshot_asset_path); + + std::string vm_snapshot_data_filename; + command_line.GetOptionValue(FlagForSwitch(Switch::VmSnapshotData), + &vm_snapshot_data_filename); + + command_line.GetOptionValue(FlagForSwitch(Switch::Route), &settings.route); + + std::string vm_snapshot_instr_filename; + command_line.GetOptionValue(FlagForSwitch(Switch::VmSnapshotInstructions), + &vm_snapshot_instr_filename); + + std::string isolate_snapshot_data_filename; + command_line.GetOptionValue(FlagForSwitch(Switch::IsolateSnapshotData), + &isolate_snapshot_data_filename); + + std::string isolate_snapshot_instr_filename; + command_line.GetOptionValue( + FlagForSwitch(Switch::IsolateSnapshotInstructions), + &isolate_snapshot_instr_filename); + + if (!aot_shared_library_name.empty()) { + for (std::string_view name : aot_shared_library_name) { + settings.application_library_path.emplace_back(name); + } + } else if (!snapshot_asset_path.empty()) { + settings.vm_snapshot_data_path = + fml::paths::JoinPaths({snapshot_asset_path, vm_snapshot_data_filename}); + settings.vm_snapshot_instr_path = fml::paths::JoinPaths( + {snapshot_asset_path, vm_snapshot_instr_filename}); + settings.isolate_snapshot_data_path = fml::paths::JoinPaths( + {snapshot_asset_path, isolate_snapshot_data_filename}); + settings.isolate_snapshot_instr_path = fml::paths::JoinPaths( + {snapshot_asset_path, isolate_snapshot_instr_filename}); + } + + command_line.GetOptionValue(FlagForSwitch(Switch::CacheDirPath), + &settings.temp_directory_path); + + bool leak_vm = "true" == command_line.GetOptionValueWithDefault( + FlagForSwitch(Switch::LeakVM), "true"); + settings.leak_vm = leak_vm; + + if (settings.icu_initialization_required) { + command_line.GetOptionValue(FlagForSwitch(Switch::ICUDataFilePath), + &settings.icu_data_path); + if (command_line.HasOption(FlagForSwitch(Switch::ICUSymbolPrefix))) { + std::string icu_symbol_prefix, native_lib_path; + command_line.GetOptionValue(FlagForSwitch(Switch::ICUSymbolPrefix), + &icu_symbol_prefix); + command_line.GetOptionValue(FlagForSwitch(Switch::ICUNativeLibPath), + &native_lib_path); + +#if FML_OS_ANDROID + settings.icu_mapper = GetICUStaticMapping; +#else + settings.icu_mapper = [icu_symbol_prefix, native_lib_path] { + return GetSymbolMapping(icu_symbol_prefix, native_lib_path); + }; +#endif + } + } + + settings.use_test_fonts = + command_line.HasOption(FlagForSwitch(Switch::UseTestFonts)); + settings.use_asset_fonts = + !command_line.HasOption(FlagForSwitch(Switch::DisableAssetFonts)); + +#if FML_OS_IOS || FML_OS_IOS_SIMULATOR +// On these configurations, the Impeller flags are completely ignored with the +// default taking hold. +#else // FML_OS_IOS && !FML_OS_IOS_SIMULATOR + { + std::string enable_impeller_value; + if (command_line.GetOptionValue(FlagForSwitch(Switch::EnableImpeller), + &enable_impeller_value)) { + settings.enable_impeller = + enable_impeller_value.empty() || "true" == enable_impeller_value; + } + } +#endif // FML_OS_IOS && !FML_OS_IOS_SIMULATOR + + { + std::string impeller_backend_value; + if (command_line.GetOptionValue(FlagForSwitch(Switch::ImpellerBackend), + &impeller_backend_value)) { + if (!impeller_backend_value.empty()) { + settings.requested_rendering_backend = impeller_backend_value; + } + } + } + + settings.enable_vulkan_validation = + command_line.HasOption(FlagForSwitch(Switch::EnableVulkanValidation)); + settings.enable_opengl_gpu_tracing = + command_line.HasOption(FlagForSwitch(Switch::EnableOpenGLGPUTracing)); + settings.enable_vulkan_gpu_tracing = + command_line.HasOption(FlagForSwitch(Switch::EnableVulkanGPUTracing)); + + settings.enable_embedder_api = + command_line.HasOption(FlagForSwitch(Switch::EnableEmbedderAPI)); + + settings.prefetched_default_font_manager = command_line.HasOption( + FlagForSwitch(Switch::PrefetchedDefaultFontManager)); + + std::string all_dart_flags; + if (command_line.GetOptionValue(FlagForSwitch(Switch::DartFlags), + &all_dart_flags)) { + // Assume that individual flags are comma separated. + std::vector flags = ParseCommaDelimited(all_dart_flags); + for (const auto& flag : flags) { + if (!IsAllowedDartVMFlag(flag)) { + FML_LOG(FATAL) << "Encountered disallowed Dart VM flag: " << flag; + } + settings.dart_flags.push_back(flag); + } + } + +#if !FLUTTER_RELEASE + command_line.GetOptionValue(FlagForSwitch(Switch::LogTag), &settings.log_tag); +#endif + + settings.dump_skp_on_shader_compilation = + command_line.HasOption(FlagForSwitch(Switch::DumpSkpOnShaderCompilation)); + + settings.cache_sksl = + command_line.HasOption(FlagForSwitch(Switch::CacheSkSL)); + + settings.purge_persistent_cache = + command_line.HasOption(FlagForSwitch(Switch::PurgePersistentCache)); + + if (command_line.HasOption(FlagForSwitch(Switch::OldGenHeapSize))) { + std::string old_gen_heap_size; + command_line.GetOptionValue(FlagForSwitch(Switch::OldGenHeapSize), + &old_gen_heap_size); + settings.old_gen_heap_size = std::stoi(old_gen_heap_size); + } + + if (command_line.HasOption( + FlagForSwitch(Switch::ResourceCacheMaxBytesThreshold))) { + std::string resource_cache_max_bytes_threshold; + command_line.GetOptionValue( + FlagForSwitch(Switch::ResourceCacheMaxBytesThreshold), + &resource_cache_max_bytes_threshold); + settings.resource_cache_max_bytes_threshold = + std::stoi(resource_cache_max_bytes_threshold); + } + + settings.enable_platform_isolates = + command_line.HasOption(FlagForSwitch(Switch::EnablePlatformIsolates)); + + settings.enable_surface_control = command_line.HasOption( + FlagForSwitch(Switch::EnableAndroidSurfaceControl)); + + settings.merged_platform_ui_thread = !command_line.HasOption( + FlagForSwitch(Switch::DisableMergedPlatformUIThread)); + + settings.impeller_enable_lazy_shader_mode = + command_line.HasOption(FlagForSwitch(Switch::ImpellerLazyShaderMode)); + settings.impeller_antialiased_lines = + command_line.HasOption(FlagForSwitch(Switch::ImpellerAntialiasLines)); + + return settings; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/switches.h b/flutter/engine/src/flutter/shell/common/switches.h new file mode 100644 index 0000000000000000000000000000000000000000..528d3e9f07bc2852fb8148ea32f9480dbb0b29a6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/switches.h @@ -0,0 +1,320 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/common/settings.h" +#include "flutter/fml/command_line.h" + +#ifndef FLUTTER_SHELL_COMMON_SWITCHES_H_ +#define FLUTTER_SHELL_COMMON_SWITCHES_H_ + +namespace flutter { + +// clang-format off +#ifndef DEF_SWITCHES_START +#define DEF_SWITCHES_START enum class Switch { +#endif +#ifndef DEF_SWITCH +#define DEF_SWITCH(swtch, flag, help) swtch, +#endif +#ifndef DEF_SWITCHES_END +#define DEF_SWITCHES_END Sentinel, } ; +#endif +// clang-format on + +DEF_SWITCHES_START +DEF_SWITCH(AotSharedLibraryName, + "aot-shared-library-name", + "Name of the *.so containing AOT compiled Dart assets.") +DEF_SWITCH(AotVMServiceSharedLibraryName, + "aot-vmservice-shared-library-name", + "Name of the *.so containing AOT compiled Dart assets for " + "launching the service isolate.") +DEF_SWITCH(SnapshotAssetPath, + "snapshot-asset-path", + "Path to the directory containing the four files specified by " + "VmSnapshotData, VmSnapshotInstructions, " + "VmSnapshotInstructions and IsolateSnapshotInstructions.") +DEF_SWITCH(VmSnapshotData, + "vm-snapshot-data", + "The VM snapshot data that will be memory mapped as read-only. " + "SnapshotAssetPath must be present.") +DEF_SWITCH(VmSnapshotInstructions, + "vm-snapshot-instr", + "The VM instructions snapshot that will be memory mapped as read " + "and executable. SnapshotAssetPath must be present.") +DEF_SWITCH(IsolateSnapshotData, + "isolate-snapshot-data", + "The isolate snapshot data that will be memory mapped as read-only. " + "SnapshotAssetPath must be present.") +DEF_SWITCH(IsolateSnapshotInstructions, + "isolate-snapshot-instr", + "The isolate instructions snapshot that will be memory mapped as " + "read and executable. SnapshotAssetPath must be present.") +DEF_SWITCH(CacheDirPath, + "cache-dir-path", + "Path to the cache directory. " + "This is different from the persistent_cache_path in embedder.h, " + "which is used for Skia shader cache.") +DEF_SWITCH(ICUDataFilePath, "icu-data-file-path", "Path to the ICU data file.") +DEF_SWITCH(ICUSymbolPrefix, + "icu-symbol-prefix", + "Prefix for the symbols representing ICU data linked into the " + "Flutter library.") +DEF_SWITCH(ICUNativeLibPath, + "icu-native-lib-path", + "Path to the library file that exports the ICU data.") +DEF_SWITCH(DartFlags, + "dart-flags", + "Flags passed directly to the Dart VM without being interpreted " + "by the Flutter shell.") +DEF_SWITCH(DeviceVMServiceHost, + "vm-service-host", + "The hostname/IP address on which the Dart VM Service should " + "be served. If not set, defaults to 127.0.0.1 or ::1 depending on " + "whether --ipv6 is specified.") +// TODO(bkonyi): remove once flutter_tools no longer uses this option. +// See https://github.com/dart-lang/sdk/issues/50233 +DEF_SWITCH( + DeviceObservatoryHost, + "observatory-host", + "(deprecated) The hostname/IP address on which the Dart VM Service should " + "be served. If not set, defaults to 127.0.0.1 or ::1 depending on " + "whether --ipv6 is specified.") +DEF_SWITCH(DeviceVMServicePort, + "vm-service-port", + "A custom Dart VM Service port. The default is to pick a randomly " + "available open port.") +// TODO(bkonyi): remove once flutter_tools no longer uses this option. +// See https://github.com/dart-lang/sdk/issues/50233 +DEF_SWITCH(DeviceObservatoryPort, + "observatory-port", + "(deprecated) A custom Dart VM Service port. The default is to pick " + "a randomly " + "available open port.") +DEF_SWITCH( + DisableVMService, + "disable-vm-service", + "Disable the Dart VM Service. The Dart VM Service is never available " + "in release mode.") +// TODO(bkonyi): remove once flutter_tools no longer uses this option. +// See https://github.com/dart-lang/sdk/issues/50233 +DEF_SWITCH(DisableObservatory, + "disable-observatory", + "(deprecated) Disable the Dart VM Service. The Dart VM Service is " + "never available " + "in release mode.") +DEF_SWITCH(DisableVMServicePublication, + "disable-vm-service-publication", + "Disable mDNS Dart VM Service publication.") +// TODO(bkonyi): remove once flutter_tools no longer uses this option. +// See https://github.com/dart-lang/sdk/issues/50233 +DEF_SWITCH(DisableObservatoryPublication, + "disable-observatory-publication", + "(deprecated) Disable mDNS Dart VM Service publication.") +DEF_SWITCH(IPv6, + "ipv6", + "Bind to the IPv6 localhost address for the Dart VM Service. " + "Ignored if --vm-service-host is set.") +DEF_SWITCH(EnableDartProfiling, + "enable-dart-profiling", + "Enable Dart profiling. Profiling information can be viewed from " + "Dart / Flutter DevTools.") +DEF_SWITCH(EndlessTraceBuffer, + "endless-trace-buffer", + "Enable an endless trace buffer. The default is a ring buffer. " + "This is useful when very old events need to viewed. For example, " + "during application launch. Memory usage will continue to grow " + "indefinitely however.") +DEF_SWITCH(EnableSoftwareRendering, + "enable-software-rendering", + "Enable rendering using the Skia software backend. This is useful " + "when testing Flutter on emulators. By default, Flutter will " + "attempt to either use OpenGL, Metal, or Vulkan.") +DEF_SWITCH(Route, + "route", + "Start app with an specific route defined on the framework") +DEF_SWITCH(SkiaDeterministicRendering, + "skia-deterministic-rendering", + "Skips the call to SkGraphics::Init(), thus avoiding swapping out " + "some Skia function pointers based on available CPU features. This " + "is used to obtain 100% deterministic behavior in Skia rendering.") +DEF_SWITCH(FlutterAssetsDir, + "flutter-assets-dir", + "Path to the Flutter assets directory.") +DEF_SWITCH(Help, "help", "Display this help text.") +DEF_SWITCH(LogTag, "log-tag", "Tag associated with log messages.") +DEF_SWITCH(DisableServiceAuthCodes, + "disable-service-auth-codes", + "Disable the requirement for authentication codes for communicating" + " with the VM service.") +DEF_SWITCH(EnableServicePortFallback, + "enable-service-port-fallback", + "Allow the VM service to fallback to automatic port selection if" + " binding to a specified port fails.") +DEF_SWITCH(StartPaused, + "start-paused", + "Start the application paused in the Dart debugger.") +DEF_SWITCH(EnableCheckedMode, "enable-checked-mode", "Enable checked mode.") +DEF_SWITCH(TraceStartup, + "trace-startup", + "Trace early application lifecycle. Automatically switches to an " + "endless trace buffer.") +DEF_SWITCH(TraceSkia, + "trace-skia", + "Trace Skia calls. This is useful when debugging the GPU threed." + "By default, Skia tracing is not enabled to reduce the number of " + "traced events") +DEF_SWITCH(TraceSkiaAllowlist, + "trace-skia-allowlist", + "Filters out all Skia trace event categories except those that are " + "specified in this comma separated list.") +DEF_SWITCH( + TraceAllowlist, + "trace-allowlist", + "Filters out all trace events except those that are specified in this " + "comma separated list of allowed prefixes.") +DEF_SWITCH(DumpSkpOnShaderCompilation, + "dump-skp-on-shader-compilation", + "Automatically dump the skp that triggers new shader compilations. " + "This is useful for writing custom ShaderWarmUp to reduce jank. " + "By default, this is not enabled to reduce the overhead. ") +DEF_SWITCH(CacheSkSL, + "cache-sksl", + "Only cache the shader in SkSL instead of binary or GLSL. This " + "should only be used during development phases. The generated SkSLs " + "can later be used in the release build for shader precompilation " + "at launch in order to eliminate the shader-compile jank.") +DEF_SWITCH(PurgePersistentCache, + "purge-persistent-cache", + "Remove all existing persistent cache. This is mainly for debugging " + "purposes such as reproducing the shader compilation jank.") +DEF_SWITCH( + TraceSystrace, + "trace-systrace", + "Trace to the system tracer (instead of the timeline) on platforms where " + "such a tracer is available. Currently only supported on Android and " + "Fuchsia.") +DEF_SWITCH(TraceToFile, + "trace-to-file", + "Write the timeline trace to a file at the specified path. The file " + "will be in Perfetto's proto format; it will be possible to load " + "the file into Perfetto's trace viewer.") +DEF_SWITCH(UseTestFonts, + "use-test-fonts", + "Running tests that layout and measure text will not yield " + "consistent results across various platforms. Enabling this option " + "will make font resolution default to the Ahem test font on all " + "platforms (See https://www.w3.org/Style/CSS/Test/Fonts/Ahem/). " + "This option is only available on the desktop test shells.") +DEF_SWITCH(DisableAssetFonts, + "disable-asset-fonts", + "Prevents usage of any non-test fonts unless they were explicitly " + "Loaded via dart:ui font APIs. This option is only available on the " + "desktop test shells.") +DEF_SWITCH(PrefetchedDefaultFontManager, + "prefetched-default-font-manager", + "Indicates whether the embedding started a prefetch of the " + "default font manager before creating the engine.") +DEF_SWITCH(VerboseLogging, + "verbose-logging", + "By default, only errors are logged. This flag enabled logging at " + "all severity levels. This is NOT a per shell flag and affect log " + "levels for all shells in the process.") +DEF_SWITCH(RunForever, + "run-forever", + "In non-interactive mode, keep the shell running after the Dart " + "script has completed.") +DEF_SWITCH(DisableDartAsserts, + "disable-dart-asserts", + "Dart code runs with assertions enabled when the runtime mode is " + "debug. In profile and release product modes, assertions are " + "disabled. This flag may be specified if the user wishes to run " + "with assertions disabled in the debug product mode (i.e. with JIT " + "or DBC).") +DEF_SWITCH(EnableSerialGC, + "enable-serial-gc", + "On low power devices with low core counts, running concurrent " + "GC tasks on threads can cause them to contend with the UI thread " + "which could potentially lead to jank. This option turns off all " + "concurrent GC activities") +DEF_SWITCH(DisallowInsecureConnections, + "disallow-insecure-connections", + "By default, dart:io allows all socket connections. If this switch " + "is set, all insecure connections are rejected.") +DEF_SWITCH(DomainNetworkPolicy, + "domain-network-policy", + "JSON encoded network policy per domain. This overrides the " + "DisallowInsecureConnections switch. Embedder can specify whether " + "to allow or disallow insecure connections at a domain level.") +DEF_SWITCH( + ForceMultithreading, + "force-multithreading", + "Uses separate threads for the platform, UI, GPU and IO task runners. " + "By default, a single thread is used for all task runners. Only available " + "in the flutter_tester.") +DEF_SWITCH(OldGenHeapSize, + "old-gen-heap-size", + "The size limit in megabytes for the Dart VM old gen heap space.") + +DEF_SWITCH(ResourceCacheMaxBytesThreshold, + "resource-cache-max-bytes-threshold", + "The max bytes threshold of resource cache, or 0 for unlimited.") +DEF_SWITCH(EnableImpeller, + "enable-impeller", + "Enable the Impeller renderer on supported platforms. Ignored if " + "Impeller is not supported on the platform.") +DEF_SWITCH(ImpellerBackend, + "impeller-backend", + "Requests a particular Impeller backend on platforms that support " + "multiple backends. (ex `opengles` or `vulkan`)") +DEF_SWITCH(EnableVulkanValidation, + "enable-vulkan-validation", + "Enable loading Vulkan validation layers. The layers must be " + "available to the application and loadable. On non-Vulkan backends, " + "this flag does nothing.") +DEF_SWITCH(EnableOpenGLGPUTracing, + "enable-opengl-gpu-tracing", + "Enable tracing of GPU execution time when using the Impeller " + "OpenGLES backend.") +DEF_SWITCH(EnableVulkanGPUTracing, + "enable-vulkan-gpu-tracing", + "Enable tracing of GPU execution time when using the Impeller " + "Vulkan backend.") +DEF_SWITCH(LeakVM, + "leak-vm", + "When the last shell shuts down, the shared VM is leaked by default " + "(the leak_vm in VM settings is true). To clean up the leak VM, set " + "this value to false.") +DEF_SWITCH(EnableEmbedderAPI, + "enable-embedder-api", + "Enable the embedder api. Defaults to false. iOS only.") +DEF_SWITCH(EnablePlatformIsolates, + "enable-platform-isolates", + "Enable support for isolates that run on the platform thread.") +DEF_SWITCH(DisableMergedPlatformUIThread, + "no-enable-merged-platform-ui-thread", + "Merge the ui thread and platform thread.") +DEF_SWITCH(EnableAndroidSurfaceControl, + "enable-surface-control", + "Enable the SurfaceControl backed swapchain when supported.") +DEF_SWITCH(ImpellerLazyShaderMode, + "impeller-lazy-shader-mode", + "Whether to defer initialization of all required PSOs for the " + "Impeller backend. Defaults to false.") +DEF_SWITCH(ImpellerAntialiasLines, + "impeller-antialias-lines", + "Experimental flag to test drawing lines with antialiasing.") +DEF_SWITCHES_END + +void PrintUsage(const std::string& executable_name); + +const std::string_view FlagForSwitch(Switch swtch); + +Settings SettingsFromCommandLine(const fml::CommandLine& command_line); + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_SWITCHES_H_ diff --git a/flutter/engine/src/flutter/shell/common/switches_unittests.cc b/flutter/engine/src/flutter/shell/common/switches_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..217ad9153c637fe05f45e34e1a898dcf81d20043 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/switches_unittests.cc @@ -0,0 +1,121 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/common/settings.h" +#include "flutter/fml/command_line.h" +#include "flutter/shell/common/switches.h" + +#include "gtest/gtest.h" + +// TODO(zanderso): https://github.com/flutter/flutter/issues/127701 +// NOLINTBEGIN(bugprone-unchecked-optional-access) + +namespace flutter { +namespace testing { + +TEST(SwitchesTest, SkiaTraceAllowlistFlag) { + fml::CommandLine command_line = + fml::CommandLineFromInitializerList({"command"}); + Settings settings = SettingsFromCommandLine(command_line); +#if !FLUTTER_RELEASE + EXPECT_TRUE(settings.trace_skia); + EXPECT_TRUE(settings.trace_skia_allowlist.has_value()); + EXPECT_EQ(settings.trace_skia_allowlist->size(), 1ul); +#else + EXPECT_FALSE(settings.trace_skia); +#endif + + command_line = + fml::CommandLineFromInitializerList({"command", "--trace-skia"}); + settings = SettingsFromCommandLine(command_line); +#if !FLUTTER_RELEASE + EXPECT_TRUE(settings.trace_skia); + EXPECT_FALSE(settings.trace_skia_allowlist.has_value()); +#else + EXPECT_FALSE(settings.trace_skia); +#endif + + command_line = fml::CommandLineFromInitializerList( + {"command", "--trace-skia-allowlist=aaa,bbb,ccc"}); + settings = SettingsFromCommandLine(command_line); +#if !FLUTTER_RELEASE + EXPECT_TRUE(settings.trace_skia); + EXPECT_TRUE(settings.trace_skia_allowlist.has_value()); + EXPECT_EQ(settings.trace_skia_allowlist->size(), 3ul); + EXPECT_EQ(settings.trace_skia_allowlist->back(), "ccc"); +#else + EXPECT_FALSE(settings.trace_skia); +#endif +} + +TEST(SwitchesTest, TraceToFile) { + fml::CommandLine command_line = fml::CommandLineFromInitializerList( + {"command", "--trace-to-file=trace.binpb"}); + EXPECT_TRUE(command_line.HasOption("trace-to-file")); + Settings settings = SettingsFromCommandLine(command_line); + EXPECT_EQ(settings.trace_to_file, "trace.binpb"); +} + +TEST(SwitchesTest, RouteParsedFlag) { + fml::CommandLine command_line = + fml::CommandLineFromInitializerList({"command", "--route=/animation"}); + Settings settings = SettingsFromCommandLine(command_line); + EXPECT_EQ(settings.route, "/animation"); + command_line = fml::CommandLineFromInitializerList({"command", "--route"}); + settings = SettingsFromCommandLine(command_line); + EXPECT_TRUE(settings.route.empty()); +} + +TEST(SwitchesTest, EnableEmbedderAPI) { + { + // enable + fml::CommandLine command_line = fml::CommandLineFromInitializerList( + {"command", "--enable-embedder-api"}); + Settings settings = SettingsFromCommandLine(command_line); + EXPECT_EQ(settings.enable_embedder_api, true); + } + { + // default + fml::CommandLine command_line = + fml::CommandLineFromInitializerList({"command"}); + Settings settings = SettingsFromCommandLine(command_line); + EXPECT_EQ(settings.enable_embedder_api, false); + } +} + +TEST(SwitchesTest, NoEnableImpeller) { + { + // enable + fml::CommandLine command_line = + fml::CommandLineFromInitializerList({"command", "--enable-impeller"}); + EXPECT_TRUE(command_line.HasOption("enable-impeller")); + Settings settings = SettingsFromCommandLine(command_line); + EXPECT_EQ(settings.enable_impeller, true); + } + { + // disable + fml::CommandLine command_line = fml::CommandLineFromInitializerList( + {"command", "--enable-impeller=false"}); + EXPECT_TRUE(command_line.HasOption("enable-impeller")); + Settings settings = SettingsFromCommandLine(command_line); + EXPECT_EQ(settings.enable_impeller, false); + } +} + +#if !FLUTTER_RELEASE +TEST(SwitchesTest, EnableAsserts) { + fml::CommandLine command_line = fml::CommandLineFromInitializerList( + {"command", "--dart-flags=--enable-asserts"}); + Settings settings = SettingsFromCommandLine(command_line); + ASSERT_EQ(settings.dart_flags.size(), 1ul); + EXPECT_EQ(settings.dart_flags[0], "--enable-asserts"); +} +#endif + +} // namespace testing +} // namespace flutter + +// NOLINTEND(bugprone-unchecked-optional-access) diff --git a/flutter/engine/src/flutter/shell/common/thread_host.cc b/flutter/engine/src/flutter/shell/common/thread_host.cc new file mode 100644 index 0000000000000000000000000000000000000000..3b90460cbc357fe15bc8cce6c770c605a9821a6c --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/thread_host.cc @@ -0,0 +1,107 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/thread_host.h" + +#include +#include +#include +#include +#include + +namespace flutter { + +std::string ThreadHost::ThreadHostConfig::MakeThreadName( + Type type, + const std::string& prefix) { + switch (type) { + case Type::kPlatform: + return prefix + ".platform"; + case Type::kUi: + return prefix + ".ui"; + case Type::kIo: + return prefix + ".io"; + case Type::kRaster: + return prefix + ".raster"; + case Type::kProfiler: + return prefix + ".profiler"; + } +} + +void ThreadHost::ThreadHostConfig::SetIOConfig(const ThreadConfig& config) { + type_mask |= ThreadHost::Type::kIo; + io_config = config; +} + +void ThreadHost::ThreadHostConfig::SetUIConfig(const ThreadConfig& config) { + type_mask |= ThreadHost::Type::kUi; + ui_config = config; +} + +void ThreadHost::ThreadHostConfig::SetPlatformConfig( + const ThreadConfig& config) { + type_mask |= ThreadHost::Type::kPlatform; + platform_config = config; +} + +void ThreadHost::ThreadHostConfig::SetRasterConfig(const ThreadConfig& config) { + type_mask |= ThreadHost::Type::kRaster; + raster_config = config; +} + +void ThreadHost::ThreadHostConfig::SetProfilerConfig( + const ThreadConfig& config) { + type_mask |= ThreadHost::Type::kProfiler; + profiler_config = config; +} + +std::unique_ptr ThreadHost::CreateThread( + Type type, + std::optional thread_config, + const ThreadHostConfig& host_config) const { + /// if not specified ThreadConfig, create a ThreadConfig. + if (!thread_config.has_value()) { + thread_config = ThreadConfig( + ThreadHostConfig::MakeThreadName(type, host_config.name_prefix)); + } + return std::make_unique(host_config.config_setter, + thread_config.value()); +} + +ThreadHost::ThreadHost() = default; + +ThreadHost::ThreadHost(ThreadHost&&) = default; + +ThreadHost::ThreadHost(const std::string& name_prefix, uint64_t mask) + : ThreadHost(ThreadHostConfig(name_prefix, mask)) {} + +ThreadHost::ThreadHost(const ThreadHostConfig& host_config) + : name_prefix(host_config.name_prefix) { + if (host_config.isThreadNeeded(ThreadHost::Type::kPlatform)) { + platform_thread = + CreateThread(Type::kPlatform, host_config.platform_config, host_config); + } + + if (host_config.isThreadNeeded(ThreadHost::Type::kUi)) { + ui_thread = CreateThread(Type::kUi, host_config.ui_config, host_config); + } + + if (host_config.isThreadNeeded(ThreadHost::Type::kRaster)) { + raster_thread = + CreateThread(Type::kRaster, host_config.raster_config, host_config); + } + + if (host_config.isThreadNeeded(ThreadHost::Type::kIo)) { + io_thread = CreateThread(Type::kIo, host_config.io_config, host_config); + } + + if (host_config.isThreadNeeded(ThreadHost::Type::kProfiler)) { + profiler_thread = + CreateThread(Type::kProfiler, host_config.profiler_config, host_config); + } +} + +ThreadHost::~ThreadHost() = default; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/thread_host.h b/flutter/engine/src/flutter/shell/common/thread_host.h new file mode 100644 index 0000000000000000000000000000000000000000..eabd5eb92f1374782ea58d8205a40a552fc2805b --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/thread_host.h @@ -0,0 +1,110 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_THREAD_HOST_H_ +#define FLUTTER_SHELL_COMMON_THREAD_HOST_H_ + +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/thread.h" + +namespace flutter { + +using ThreadConfig = fml::Thread::ThreadConfig; +using ThreadConfigSetter = fml::Thread::ThreadConfigSetter; + +/// The collection of all the threads used by the engine. +struct ThreadHost { + enum Type { + kPlatform = 1 << 0, + kUi = 1 << 1, + kRaster = 1 << 2, + kIo = 1 << 3, + kProfiler = 1 << 4, + }; + + /// The collection of all the thread configures, and we create custom thread + /// configure in engine to info the thread. + struct ThreadHostConfig { + explicit ThreadHostConfig( + const ThreadConfigSetter& setter = fml::Thread::SetCurrentThreadName) + : type_mask(0), config_setter(setter) {} + + ThreadHostConfig( + const std::string& name_prefix, + uint64_t mask, + const ThreadConfigSetter& setter = fml::Thread::SetCurrentThreadName) + : type_mask(mask), name_prefix(name_prefix), config_setter(setter) {} + + explicit ThreadHostConfig( + uint64_t mask, + const ThreadConfigSetter& setter = fml::Thread::SetCurrentThreadName) + : ThreadHostConfig("", mask, setter) {} + + /// Check if need to create thread. + bool isThreadNeeded(Type type) const { return type_mask & type; } + + /// Use the prefix and thread type to generator a thread name. + static std::string MakeThreadName(Type type, const std::string& prefix); + + /// Specified the UI Thread Config, meanwhile set the mask. + void SetUIConfig(const ThreadConfig&); + + /// Specified the Platform Thread Config, meanwhile set the mask. + void SetPlatformConfig(const ThreadConfig&); + + /// Specified the IO Thread Config, meanwhile set the mask. + void SetRasterConfig(const ThreadConfig&); + + /// Specified the IO Thread Config, meanwhile set the mask. + void SetIOConfig(const ThreadConfig&); + + /// Specified the ProfilerThread Config, meanwhile set the mask. + void SetProfilerConfig(const ThreadConfig&); + + uint64_t type_mask; + + std::string name_prefix = ""; + + const ThreadConfigSetter config_setter; + + std::optional platform_config; + std::optional ui_config; + std::optional raster_config; + std::optional io_config; + std::optional profiler_config; + }; + + std::string name_prefix; + std::unique_ptr platform_thread; + std::unique_ptr ui_thread; + std::unique_ptr raster_thread; + std::unique_ptr io_thread; + std::unique_ptr profiler_thread; + + ThreadHost(); + + ThreadHost(ThreadHost&&); + + ThreadHost& operator=(ThreadHost&&) = default; + + ThreadHost(const std::string& name_prefix, uint64_t mask); + + explicit ThreadHost(const ThreadHostConfig& host_config); + + ~ThreadHost(); + + private: + std::unique_ptr CreateThread( + Type type, + std::optional thread_config, + const ThreadHostConfig& host_config) const; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_THREAD_HOST_H_ diff --git a/flutter/engine/src/flutter/shell/common/variable_refresh_rate_display.cc b/flutter/engine/src/flutter/shell/common/variable_refresh_rate_display.cc new file mode 100644 index 0000000000000000000000000000000000000000..138fc0edb6ad5fd9edb1f44bafee7f0879af0bc3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/variable_refresh_rate_display.cc @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/variable_refresh_rate_display.h" +#include "flutter/fml/logging.h" + +static double GetInitialRefreshRate( + const std::weak_ptr& + refresh_rate_reporter) { + if (auto reporter = refresh_rate_reporter.lock()) { + return reporter->GetRefreshRate(); + } + return 0; +} + +namespace flutter { + +VariableRefreshRateDisplay::VariableRefreshRateDisplay( + DisplayId display_id, + const std::weak_ptr& refresh_rate_reporter, + double width, + double height, + double device_pixel_ratio) + : Display(display_id, + GetInitialRefreshRate(refresh_rate_reporter), + width, + height, + device_pixel_ratio), + refresh_rate_reporter_(refresh_rate_reporter) {} + +double VariableRefreshRateDisplay::GetRefreshRate() const { + return GetInitialRefreshRate(refresh_rate_reporter_); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/variable_refresh_rate_display.h b/flutter/engine/src/flutter/shell/common/variable_refresh_rate_display.h new file mode 100644 index 0000000000000000000000000000000000000000..e0dcd681bf5717fe5d329873de71a2bea55c75f9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/variable_refresh_rate_display.h @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_DISPLAY_H_ +#define FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_DISPLAY_H_ + +#include + +#include "display.h" +#include "flutter/fml/macros.h" +#include "variable_refresh_rate_reporter.h" + +namespace flutter { + +/// A Display where the refresh rate can change over time. +class VariableRefreshRateDisplay : public Display { + public: + explicit VariableRefreshRateDisplay( + DisplayId display_id, + const std::weak_ptr& refresh_rate_reporter, + double width, + double height, + double device_pixel_ratio); + ~VariableRefreshRateDisplay() = default; + + // |Display| + double GetRefreshRate() const override; + + private: + const std::weak_ptr refresh_rate_reporter_; + + FML_DISALLOW_COPY_AND_ASSIGN(VariableRefreshRateDisplay); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_DISPLAY_H_ diff --git a/flutter/engine/src/flutter/shell/common/variable_refresh_rate_display_unittests.cc b/flutter/engine/src/flutter/shell/common/variable_refresh_rate_display_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..d9725cf815dafdd3a59ade6965e36d7cdab4e7d3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/variable_refresh_rate_display_unittests.cc @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "variable_refresh_rate_display.h" +#include "vsync_waiters_test.h" + +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +TEST(VariableRefreshRateDisplayTest, ReportCorrectInitialRefreshRate) { + auto refresh_rate_reporter = std::make_shared(60); + auto display = flutter::VariableRefreshRateDisplay( + 0, std::weak_ptr(refresh_rate_reporter), 600, + 800, 60); + ASSERT_EQ(display.GetRefreshRate(), 60); +} + +TEST(VariableRefreshRateDisplayTest, ReportCorrectRefreshRateWhenUpdated) { + auto refresh_rate_reporter = std::make_shared(60); + auto display = flutter::VariableRefreshRateDisplay( + 0, std::weak_ptr(refresh_rate_reporter), 600, + 800, 60); + refresh_rate_reporter->UpdateRefreshRate(30); + ASSERT_EQ(display.GetRefreshRate(), 30); +} + +TEST(VariableRefreshRateDisplayTest, + Report0IfReporterSharedPointerIsDestroyedAfterDisplayCreation) { + auto refresh_rate_reporter = std::make_shared(60); + auto display = flutter::VariableRefreshRateDisplay( + 0, std::weak_ptr(refresh_rate_reporter), 600, + 800, 60); + refresh_rate_reporter.reset(); + ASSERT_EQ(display.GetRefreshRate(), 0); +} + +TEST(VariableRefreshRateDisplayTest, + Report0IfReporterSharedPointerIsDestroyedBeforeDisplayCreation) { + auto refresh_rate_reporter = std::make_shared(60); + refresh_rate_reporter.reset(); + auto display = flutter::VariableRefreshRateDisplay( + 0, std::weak_ptr(refresh_rate_reporter), 600, + 800, 60); + ASSERT_EQ(display.GetRefreshRate(), 0); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/variable_refresh_rate_reporter.h b/flutter/engine/src/flutter/shell/common/variable_refresh_rate_reporter.h new file mode 100644 index 0000000000000000000000000000000000000000..882eea227974962828464fa1701abc5cf54d1181 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/variable_refresh_rate_reporter.h @@ -0,0 +1,28 @@ +// 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_COMMON_VARIABLE_REFRESH_RATE_REPORTER_H_ +#define FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_REPORTER_H_ + +#include +#include +#include +#include + +namespace flutter { + +/// Abstract class that reprents a platform specific mechanism to report current +/// refresh rates. +class VariableRefreshRateReporter { + public: + VariableRefreshRateReporter() = default; + + virtual double GetRefreshRate() const = 0; + + FML_DISALLOW_COPY_AND_ASSIGN(VariableRefreshRateReporter); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_REPORTER_H_ diff --git a/flutter/engine/src/flutter/shell/common/vsync_waiter.cc b/flutter/engine/src/flutter/shell/common/vsync_waiter.cc new file mode 100644 index 0000000000000000000000000000000000000000..5aa60e92fce3531f2e6cad4785f662801766490b --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/vsync_waiter.cc @@ -0,0 +1,169 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/vsync_waiter.h" + +#include "flow/frame_timings.h" +#include "flutter/fml/task_runner.h" +#include "flutter/fml/trace_event.h" +#include "fml/logging.h" +#include "fml/message_loop_task_queues.h" +#include "fml/task_queue_id.h" +#include "fml/time/time_point.h" + +namespace flutter { + +static constexpr const char* kVsyncFlowName = "VsyncFlow"; + +static constexpr const char* kVsyncTraceName = "VsyncProcessCallback"; + +VsyncWaiter::VsyncWaiter(const TaskRunners& task_runners) + : task_runners_(task_runners) {} + +VsyncWaiter::~VsyncWaiter() = default; + +// Public method invoked by the animator. +void VsyncWaiter::AsyncWaitForVsync(const Callback& callback) { + if (!callback) { + return; + } + + TRACE_EVENT0("flutter", "AsyncWaitForVsync"); + + { + std::scoped_lock lock(callback_mutex_); + if (callback_) { + // The animator may request a frame more than once within a frame + // interval. Multiple calls to request frame must result in a single + // callback per frame interval. + TRACE_EVENT_INSTANT0("flutter", "MultipleCallsToVsyncInFrameInterval"); + return; + } + callback_ = callback; + if (!secondary_callbacks_.empty()) { + // Return directly as `AwaitVSync` is already called by + // `ScheduleSecondaryCallback`. + return; + } + } + AwaitVSync(); +} + +void VsyncWaiter::ScheduleSecondaryCallback(uintptr_t id, + const fml::closure& callback) { + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + + if (!callback) { + return; + } + + TRACE_EVENT0("flutter", "ScheduleSecondaryCallback"); + + { + std::scoped_lock lock(callback_mutex_); + bool secondary_callbacks_originally_empty = secondary_callbacks_.empty(); + auto [_, inserted] = secondary_callbacks_.emplace(id, callback); + if (!inserted) { + // Multiple schedules must result in a single callback per frame interval. + TRACE_EVENT_INSTANT0("flutter", + "MultipleCallsToSecondaryVsyncInFrameInterval"); + return; + } + if (callback_) { + // Return directly as `AwaitVSync` is already called by + // `AsyncWaitForVsync`. + return; + } + if (!secondary_callbacks_originally_empty) { + // Return directly as `AwaitVSync` is already called by + // `ScheduleSecondaryCallback`. + return; + } + } + AwaitVSyncForSecondaryCallback(); +} + +void VsyncWaiter::FireCallback(fml::TimePoint frame_start_time, + fml::TimePoint frame_target_time, + bool pause_secondary_tasks) { + FML_DCHECK(fml::TimePoint::Now() >= frame_start_time); + + Callback callback; + std::vector secondary_callbacks; + + { + std::scoped_lock lock(callback_mutex_); + callback = std::move(callback_); + for (auto& pair : secondary_callbacks_) { + secondary_callbacks.push_back(std::move(pair.second)); + } + secondary_callbacks_.clear(); + } + + if (!callback && secondary_callbacks.empty()) { + // This means that the vsync waiter implementation fired a callback for a + // request we did not make. This is a paranoid check but we still want to + // make sure we catch misbehaving vsync implementations. + TRACE_EVENT_INSTANT0("flutter", "MismatchedFrameCallback"); + return; + } + + if (callback) { + const uint64_t flow_identifier = fml::tracing::TraceNonce(); + if (pause_secondary_tasks) { + PauseDartEventLoopTasks(); + } + + // The base trace ensures that flows have a root to begin from if one does + // not exist. The trace viewer will ignore traces that have no base event + // trace. While all our message loops insert a base trace trace + // (MessageLoop::RunExpiredTasks), embedders may not. + TRACE_EVENT0_WITH_FLOW_IDS("flutter", "VsyncFireCallback", + /*flow_id_count=*/1, + /*flow_ids=*/&flow_identifier); + + TRACE_FLOW_BEGIN("flutter", kVsyncFlowName, flow_identifier); + + fml::TaskQueueId ui_task_queue_id = + task_runners_.GetUITaskRunner()->GetTaskQueueId(); + task_runners_.GetUITaskRunner()->PostTask( + [ui_task_queue_id, callback, flow_identifier, frame_start_time, + frame_target_time, pause_secondary_tasks]() { + FML_TRACE_EVENT_WITH_FLOW_IDS( + "flutter", kVsyncTraceName, /*flow_id_count=*/1, + /*flow_ids=*/&flow_identifier, "StartTime", frame_start_time, + "TargetTime", frame_target_time); + std::unique_ptr frame_timings_recorder = + std::make_unique(); + frame_timings_recorder->RecordVsync(frame_start_time, + frame_target_time); + callback(std::move(frame_timings_recorder)); + TRACE_FLOW_END("flutter", kVsyncFlowName, flow_identifier); + if (pause_secondary_tasks) { + ResumeDartEventLoopTasks(ui_task_queue_id); + } + }); + } + + for (auto& secondary_callback : secondary_callbacks) { + task_runners_.GetUITaskRunner()->PostTask(secondary_callback); + } +} + +void VsyncWaiter::PauseDartEventLoopTasks() { + auto ui_task_queue_id = task_runners_.GetUITaskRunner()->GetTaskQueueId(); + auto task_queues = fml::MessageLoopTaskQueues::GetInstance(); + if (ui_task_queue_id.is_valid()) { + task_queues->PauseSecondarySource(ui_task_queue_id); + } +} + +void VsyncWaiter::ResumeDartEventLoopTasks(fml::TaskQueueId ui_task_queue_id) { + auto task_queues = fml::MessageLoopTaskQueues::GetInstance(); + if (ui_task_queue_id.is_valid()) { + task_queues->ResumeSecondarySource(ui_task_queue_id); + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/vsync_waiter.h b/flutter/engine/src/flutter/shell/common/vsync_waiter.h new file mode 100644 index 0000000000000000000000000000000000000000..fa644f63bb0ac896b7b26937165269dea4225922 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/vsync_waiter.h @@ -0,0 +1,90 @@ +// 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_COMMON_VSYNC_WAITER_H_ +#define FLUTTER_SHELL_COMMON_VSYNC_WAITER_H_ + +#include +#include +#include +#include + +#include "flutter/common/task_runners.h" +#include "flutter/flow/frame_timings.h" +#include "flutter/fml/time/time_point.h" + +namespace flutter { + +/// Abstract Base Class that represents a platform specific mechanism for +/// getting callbacks when a vsync event happens. +/// +/// @see VsyncWaiterAndroid +/// @see VsyncWaiterEmbedder +class VsyncWaiter : public std::enable_shared_from_this { + public: + using Callback = std::function)>; + + virtual ~VsyncWaiter(); + + void AsyncWaitForVsync(const Callback& callback); + + /// Add a secondary callback for key |id| for the next vsync. + /// + /// See also |PointerDataDispatcher::ScheduleSecondaryVsyncCallback| and + /// |Animator::ScheduleMaybeClearTraceFlowIds|. + void ScheduleSecondaryCallback(uintptr_t id, const fml::closure& callback); + + protected: + // On some backends, the |FireCallback| needs to be made from a static C + // method. + friend class VsyncWaiterAndroid; + friend class VsyncWaiterEmbedder; + + const TaskRunners task_runners_; + + explicit VsyncWaiter(const TaskRunners& task_runners); + + // There are two distinct situations where VsyncWaiter wishes to awaken at + // the next vsync. Although the functionality can be the same, the intent is + // different, therefore it makes sense to have a method for each intent. + + // The intent of AwaitVSync() is that the Animator wishes to produce a frame. + // The underlying implementation can choose to be aware of this intent when + // it comes to implementing backpressure and other scheduling invariants. + // + // Implementations are meant to override this method and arm their vsync + // latches when in response to this invocation. On vsync, they are meant to + // invoke the |FireCallback| method once (and only once) with the appropriate + // arguments. This method should not block the current thread. + virtual void AwaitVSync() = 0; + + // The intent of AwaitVSyncForSecondaryCallback() is simply to wake up at the + // next vsync. + // + // Because there is no association with frame scheduling, underlying + // implementations do not need to worry about maintaining invariants or + // backpressure. The default implementation is to simply follow the same logic + // as AwaitVSync(). + virtual void AwaitVSyncForSecondaryCallback() { AwaitVSync(); } + + // Schedules the callback on the UI task runner. Needs to be invoked as close + // to the `frame_start_time` as possible. + void FireCallback(fml::TimePoint frame_start_time, + fml::TimePoint frame_target_time, + bool pause_secondary_tasks = true); + + private: + std::mutex callback_mutex_; + Callback callback_; + std::unordered_map secondary_callbacks_; + + void PauseDartEventLoopTasks(); + static void ResumeDartEventLoopTasks(fml::TaskQueueId ui_task_queue_id); + + FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiter); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_VSYNC_WAITER_H_ diff --git a/flutter/engine/src/flutter/shell/common/vsync_waiter_fallback.cc b/flutter/engine/src/flutter/shell/common/vsync_waiter_fallback.cc new file mode 100644 index 0000000000000000000000000000000000000000..bad751e4afd89c85b6559003ddc363de6bd51bad --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/vsync_waiter_fallback.cc @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/common/vsync_waiter_fallback.h" + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/trace_event.h" + +namespace flutter { +namespace { + +static fml::TimePoint SnapToNextTick(fml::TimePoint value, + fml::TimePoint tick_phase, + fml::TimeDelta tick_interval) { + fml::TimeDelta offset = (tick_phase - value) % tick_interval; + if (offset != fml::TimeDelta::Zero()) { + offset = offset + tick_interval; + } + return value + offset; +} + +} // namespace + +VsyncWaiterFallback::VsyncWaiterFallback(const TaskRunners& task_runners, + bool for_testing) + : VsyncWaiter(task_runners), + phase_(fml::TimePoint::Now()), + for_testing_(for_testing) {} + +VsyncWaiterFallback::~VsyncWaiterFallback() = default; + +// |VsyncWaiter| +void VsyncWaiterFallback::AwaitVSync() { + constexpr fml::TimeDelta kSingleFrameInterval = + fml::TimeDelta::FromSecondsF(1.0 / 60.0); + auto frame_start_time = + SnapToNextTick(fml::TimePoint::Now(), phase_, kSingleFrameInterval); + auto frame_target_time = frame_start_time + kSingleFrameInterval; + + TRACE_EVENT2_INT("flutter", "PlatformVsync", "frame_start_time", + frame_start_time.ToEpochDelta().ToMicroseconds(), + "frame_target_time", + frame_target_time.ToEpochDelta().ToMicroseconds()); + + std::weak_ptr weak_this = + std::static_pointer_cast(shared_from_this()); + + task_runners_.GetUITaskRunner()->PostTaskForTime( + [frame_start_time, frame_target_time, weak_this]() { + if (auto vsync_waiter = weak_this.lock()) { + vsync_waiter->FireCallback(frame_start_time, frame_target_time, + !vsync_waiter->for_testing_); + } + }, + frame_start_time); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/vsync_waiter_fallback.h b/flutter/engine/src/flutter/shell/common/vsync_waiter_fallback.h new file mode 100644 index 0000000000000000000000000000000000000000..b2a6ccfed05bf76e47ff29d9cf61e3ffe28c1992 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/vsync_waiter_fallback.h @@ -0,0 +1,35 @@ +// 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_COMMON_VSYNC_WAITER_FALLBACK_H_ +#define FLUTTER_SHELL_COMMON_VSYNC_WAITER_FALLBACK_H_ + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/shell/common/vsync_waiter.h" + +namespace flutter { + +/// A |VsyncWaiter| that will fire at 60 fps irrespective of the vsync. +class VsyncWaiterFallback final : public VsyncWaiter { + public: + explicit VsyncWaiterFallback(const TaskRunners& task_runners, + bool for_testing = false); + + ~VsyncWaiterFallback() override; + + private: + fml::TimePoint phase_; + const bool for_testing_; + + // |VsyncWaiter| + void AwaitVSync() override; + + FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiterFallback); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_VSYNC_WAITER_FALLBACK_H_ diff --git a/flutter/engine/src/flutter/shell/common/vsync_waiter_unittests.cc b/flutter/engine/src/flutter/shell/common/vsync_waiter_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..997f4a1f5756f20dbecfce267592ff7c4856bc99 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/vsync_waiter_unittests.cc @@ -0,0 +1,47 @@ +#define FML_USED_ON_EMBEDDER + +#include + +#include "flutter/common/settings.h" +#include "flutter/common/task_runners.h" +#include "flutter/shell/common/switches.h" + +#include "gtest/gtest.h" +#include "thread_host.h" +#include "vsync_waiter.h" + +namespace flutter { +namespace testing { + +class TestVsyncWaiter : public VsyncWaiter { + public: + explicit TestVsyncWaiter(const TaskRunners& task_runners) + : VsyncWaiter(task_runners) {} + + int await_vsync_call_count_ = 0; + + protected: + void AwaitVSync() override { await_vsync_call_count_++; } +}; + +TEST(VsyncWaiterTest, NoUnneededAwaitVsync) { + using flutter::ThreadHost; + std::string prefix = "vsync_waiter_test"; + + fml::MessageLoop::EnsureInitializedForCurrentThread(); + auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); + + const flutter::TaskRunners task_runners(prefix, task_runner, task_runner, + task_runner, task_runner); + + TestVsyncWaiter vsync_waiter(task_runners); + + vsync_waiter.ScheduleSecondaryCallback(1, [] {}); + EXPECT_EQ(vsync_waiter.await_vsync_call_count_, 1); + + vsync_waiter.ScheduleSecondaryCallback(2, [] {}); + EXPECT_EQ(vsync_waiter.await_vsync_call_count_, 1); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/vsync_waiters_test.cc b/flutter/engine/src/flutter/shell/common/vsync_waiters_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..3c237959df54776c3fe93ac0764a314eeca96a6a --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/vsync_waiters_test.cc @@ -0,0 +1,79 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#define FML_USED_ON_EMBEDDER + +#include "flutter/shell/common/shell_test.h" + +#include "flutter/flow/layers/layer_tree.h" +#include "flutter/flow/layers/transform_layer.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/mapping.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/testing/testing.h" + +namespace flutter { +namespace testing { + +void ShellTestVsyncClock::SimulateVSync() { + std::scoped_lock lock(mutex_); + if (vsync_issued_ >= vsync_promised_.size()) { + vsync_promised_.emplace_back(); + } + FML_CHECK(vsync_issued_ < vsync_promised_.size()); + vsync_promised_[vsync_issued_].set_value(vsync_issued_); + vsync_issued_ += 1; +} + +std::future ShellTestVsyncClock::NextVSync() { + std::scoped_lock lock(mutex_); + vsync_promised_.emplace_back(); + return vsync_promised_.back().get_future(); +} + +void ShellTestVsyncWaiter::AwaitVSync() { + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + auto vsync_future = clock_->NextVSync(); + + auto async_wait = std::async([&vsync_future, this]() { + vsync_future.wait(); + + // Post the `FireCallback` to the Platform thread so earlier Platform tasks + // (specifically, the `VSyncFlush` call) will be finished before + // `FireCallback` is executed. This is only needed for our unit tests. + // + // Without this, the repeated VSYNC signals in `VSyncFlush` may start both + // the current frame in the UI thread and the next frame in the secondary + // callback (both of them are waiting for VSYNCs). That breaks the unit + // test's assumption that each frame's VSYNC must be issued by different + // `VSyncFlush` call (which resets the `will_draw_new_frame` bit). + // + // For example, HandlesActualIphoneXsInputEvents will fail without this. + task_runners_.GetPlatformTaskRunner()->PostTask([this]() { + FireCallback(fml::TimePoint::Now(), fml::TimePoint::Now()); + }); + }); +} + +void ConstantFiringVsyncWaiter::AwaitVSync() { + FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); + auto async_wait = std::async([this]() { + task_runners_.GetPlatformTaskRunner()->PostTask( + [this]() { FireCallback(kFrameBeginTime, kFrameTargetTime); }); + }); +} + +TestRefreshRateReporter::TestRefreshRateReporter(double refresh_rate) + : refresh_rate_(refresh_rate) {} + +void TestRefreshRateReporter::UpdateRefreshRate(double refresh_rate) { + refresh_rate_ = refresh_rate; +} + +double TestRefreshRateReporter::GetRefreshRate() const { + return refresh_rate_; +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/common/vsync_waiters_test.h b/flutter/engine/src/flutter/shell/common/vsync_waiters_test.h new file mode 100644 index 0000000000000000000000000000000000000000..fad0bb34948846a4b1e9d81765acea92070b5493 --- /dev/null +++ b/flutter/engine/src/flutter/shell/common/vsync_waiters_test.h @@ -0,0 +1,76 @@ +// 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_COMMON_VSYNC_WAITERS_TEST_H_ +#define FLUTTER_SHELL_COMMON_VSYNC_WAITERS_TEST_H_ + +#define FML_USED_ON_EMBEDDER + +#include + +#include "flutter/shell/common/shell.h" + +namespace flutter { +namespace testing { + +using CreateVsyncWaiter = std::function()>; + +class ShellTestVsyncClock { + public: + /// Simulate that a vsync signal is triggered. + void SimulateVSync(); + + /// A future that will return the index the next vsync signal. + std::future NextVSync(); + + private: + std::mutex mutex_; + std::vector> vsync_promised_; + size_t vsync_issued_ = 0; +}; + +class ShellTestVsyncWaiter : public VsyncWaiter { + public: + ShellTestVsyncWaiter(const TaskRunners& task_runners, + std::shared_ptr clock) + : VsyncWaiter(task_runners), clock_(std::move(clock)) {} + + protected: + void AwaitVSync() override; + + private: + std::shared_ptr clock_; +}; + +class ConstantFiringVsyncWaiter : public VsyncWaiter { + public: + // both of these are set in the past so as to fire immediately. + static constexpr fml::TimePoint kFrameBeginTime = + fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromSeconds(0)); + static constexpr fml::TimePoint kFrameTargetTime = + fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromSeconds(100)); + + explicit ConstantFiringVsyncWaiter(const TaskRunners& task_runners) + : VsyncWaiter(task_runners) {} + + protected: + void AwaitVSync() override; +}; + +class TestRefreshRateReporter final : public VariableRefreshRateReporter { + public: + explicit TestRefreshRateReporter(double refresh_rate); + void UpdateRefreshRate(double refresh_rate); + + // |RefreshRateReporter| + double GetRefreshRate() const override; + + private: + double refresh_rate_; +}; + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_SHELL_COMMON_VSYNC_WAITERS_TEST_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/BUILD.gn b/flutter/engine/src/flutter/shell/gpu/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ddbdcc0029364fbc3c9faed64e56e4e250d5053b --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/BUILD.gn @@ -0,0 +1,125 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/common/config.gni") +import("//flutter/impeller/tools/impeller.gni") +import("//flutter/shell/config.gni") + +gpu_common_deps = [ + "//flutter/common", + "//flutter/common/graphics", + "//flutter/flow", + "//flutter/fml", + "//flutter/shell/common", + "//flutter/skia", +] + +source_set("gpu_surface_software") { + sources = [ + "gpu_surface_software.cc", + "gpu_surface_software.h", + "gpu_surface_software_delegate.cc", + "gpu_surface_software_delegate.h", + ] + + public_deps = gpu_common_deps +} + +source_set("gpu_surface_gl") { + sources = [ + "gpu_surface_gl_delegate.cc", + "gpu_surface_gl_delegate.h", + "gpu_surface_gl_skia.cc", + "gpu_surface_gl_skia.h", + ] + + public_deps = gpu_common_deps + + if (impeller_enable_opengles) { + sources += [ + "gpu_surface_gl_impeller.cc", + "gpu_surface_gl_impeller.h", + ] + + public_deps += [ "//flutter/impeller" ] + } +} + +source_set("gpu_surface_vulkan") { + sources = [ + "gpu_surface_vulkan.cc", + "gpu_surface_vulkan.h", + "gpu_surface_vulkan_delegate.cc", + "gpu_surface_vulkan_delegate.h", + ] + public_deps = gpu_common_deps + [ + "//flutter/shell/platform/embedder:embedder_headers", + "//flutter/vulkan", + "//flutter/vulkan/procs", + ] + + if (impeller_enable_vulkan) { + sources += [ + "gpu_surface_vulkan_impeller.cc", + "gpu_surface_vulkan_impeller.h", + ] + + public_deps += [ "//flutter/impeller" ] + } +} + +if (shell_enable_metal) { + source_set("gpu_surface_metal") { + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + + sources = [ + "gpu_surface_metal_delegate.cc", + "gpu_surface_metal_delegate.h", + "gpu_surface_metal_skia.h", + "gpu_surface_metal_skia.mm", + "gpu_surface_noop.h", + "gpu_surface_noop.mm", + ] + + public_deps = gpu_common_deps + + if (impeller_enable_metal) { + sources += [ + "gpu_surface_metal_impeller.h", + "gpu_surface_metal_impeller.mm", + ] + + public_deps += [ "//flutter/impeller" ] + } + } +} + +if (is_mac) { + impeller_component("gpu_surface_metal_unittests") { + testonly = true + cflags_objc = flutter_cflags_objc + cflags_objcc = flutter_cflags_objcc + + target_type = "executable" + sources = [ + "gpu_surface_metal_impeller_unittests.mm", + "gpu_surface_noop_unittests.mm", + ] + + frameworks = [ + "AppKit.framework", + "QuartzCore.framework", + ] + + deps = [ + ":gpu_surface_metal", + "//flutter/fml", + "//flutter/impeller/fixtures", + "//flutter/runtime", + "//flutter/runtime:libdart", + "//flutter/testing", + ] + gpu_common_deps + } +} diff --git a/flutter/engine/src/flutter/shell/gpu/gpu.gni b/flutter/engine/src/flutter/shell/gpu/gpu.gni new file mode 100644 index 0000000000000000000000000000000000000000..8e09b4f465783f6761cd695605cf1d1b40a2a345 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu.gni @@ -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. + +import("//flutter/shell/config.gni") + +template("shell_gpu_configuration") { + assert(defined(invoker.enable_software), + "Caller must declare if the Software backend must be enabled.") + assert(defined(invoker.enable_vulkan), + "Caller must declare if the Vulkan backend must be enabled.") + assert(defined(invoker.enable_gl), + "Caller must declare if the Open GL backend must be enabled.") + assert(defined(invoker.enable_metal), + "Caller must declare if the Metal backend must be enabled.") + + group(target_name) { + public_deps = [] + + if (invoker.enable_software) { + public_deps += [ "//flutter/shell/gpu:gpu_surface_software" ] + } + + if (invoker.enable_gl) { + public_deps += [ "//flutter/shell/gpu:gpu_surface_gl" ] + } + + if (invoker.enable_vulkan) { + public_deps += [ "//flutter/shell/gpu:gpu_surface_vulkan" ] + } + + if (invoker.enable_metal) { + public_deps += [ "//flutter/shell/gpu:gpu_surface_metal" ] + } + } + + config("${target_name}_config") { + defines = [] + + if (invoker.enable_software) { + defines += [ "SHELL_ENABLE_SOFTWARE" ] + } + if (invoker.enable_gl) { + defines += [ "SHELL_ENABLE_GL" ] + } + if (invoker.enable_vulkan) { + defines += [ "SHELL_ENABLE_VULKAN" ] + } + if (invoker.enable_metal) { + defines += [ "SHELL_ENABLE_METAL" ] + } + } +} diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_delegate.cc b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e655d1755a96486d827e987e51f1642e47ebe33 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_delegate.cc @@ -0,0 +1,147 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_gl_delegate.h" + +#include "flutter/fml/build_config.h" + +#include + +#include "third_party/skia/include/gpu/ganesh/gl/GrGLAssembleInterface.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLInterface.h" + +#if defined(FML_OS_ANDROID) +#include "third_party/skia/include/gpu/ganesh/gl/egl/GrGLMakeEGLInterface.h" +#endif + +#if defined(FML_OS_LINUX) && defined(SK_GLX) +#include "third_party/skia/include/gpu/ganesh/gl/glx/GrGLMakeGLXInterface.h" +#endif + +#if defined(FML_OS_MACOSX) +#include "third_party/skia/include/gpu/ganesh/gl/mac/GrGLMakeMacInterface.h" +#endif + +#if defined(FML_OS_IOS) +#include "third_party/skia/include/gpu/ganesh/gl/ios/GrGLMakeIOSInterface.h" +#endif + +namespace flutter { + +GPUSurfaceGLDelegate::~GPUSurfaceGLDelegate() = default; + +bool GPUSurfaceGLDelegate::GLContextFBOResetAfterPresent() const { + return false; +} + +SurfaceFrame::FramebufferInfo GPUSurfaceGLDelegate::GLContextFramebufferInfo() + const { + SurfaceFrame::FramebufferInfo res; + res.supports_readback = true; + return res; +} + +SkMatrix GPUSurfaceGLDelegate::GLContextSurfaceTransformation() const { + SkMatrix matrix; + matrix.setIdentity(); + return matrix; +} + +GPUSurfaceGLDelegate::GLProcResolver GPUSurfaceGLDelegate::GetGLProcResolver() + const { + return nullptr; +} + +static bool IsProcResolverOpenGLES( + const GPUSurfaceGLDelegate::GLProcResolver& proc_resolver) { + // Version string prefix that identifies an OpenGL ES implementation. +#define GPU_GL_VERSION 0x1F02 + constexpr char kGLESVersionPrefix[] = "OpenGL ES"; + +#ifdef WIN32 + using GLGetStringProc = const char*(__stdcall*)(uint32_t); +#else + using GLGetStringProc = const char* (*)(uint32_t); +#endif + + GLGetStringProc gl_get_string = + reinterpret_cast(proc_resolver("glGetString")); + + FML_CHECK(gl_get_string) + << "The GL proc resolver could not resolve glGetString"; + + const char* gl_version_string = gl_get_string(GPU_GL_VERSION); + + FML_CHECK(gl_version_string) + << "The GL proc resolver's glGetString(GL_VERSION) failed"; + + return strncmp(gl_version_string, kGLESVersionPrefix, + strlen(kGLESVersionPrefix)) == 0; +} + +static sk_sp CreateGLInterface( + const GPUSurfaceGLDelegate::GLProcResolver& proc_resolver) { + if (proc_resolver == nullptr) { +#if defined(FML_OS_ANDROID) + return GrGLInterfaces::MakeEGL(); +#elif defined(FML_OS_LINUX) +#if defined(SK_GLX) + return GrGLInterfaces::MakeGLX(); +#else + return nullptr; +#endif // defined(SK_GLX) +#elif defined(FML_OS_IOS) + return GrGLInterfaces::MakeIOS(); +#elif defined(FML_OS_MACOSX) + return GrGLInterfaces::MakeMac(); +#else + // TODO(kjlubick) update this when Skia has a Windows target for making GL + // interfaces. For now, ask Skia to guess the native + // interface. This often leads to interesting results on most platforms. + return GrGLMakeNativeInterface(); +#endif + } + + struct ProcResolverContext { + GPUSurfaceGLDelegate::GLProcResolver resolver; + }; + + ProcResolverContext context = {proc_resolver}; + + GrGLGetProc gl_get_proc = [](void* context, + const char gl_proc_name[]) -> GrGLFuncPtr { + auto proc_resolver_context = + reinterpret_cast(context); + return reinterpret_cast( + proc_resolver_context->resolver(gl_proc_name)); + }; + + // glGetString indicates an OpenGL ES interface. + if (IsProcResolverOpenGLES(proc_resolver)) { + return GrGLMakeAssembledGLESInterface(&context, gl_get_proc); + } + + // Fallback to OpenGL. + if (auto interface = GrGLMakeAssembledGLInterface(&context, gl_get_proc)) { + return interface; + } + + FML_LOG(ERROR) << "Could not create a valid GL interface."; + return nullptr; +} + +sk_sp GPUSurfaceGLDelegate::GetGLInterface() const { + return CreateGLInterface(GetGLProcResolver()); +} + +sk_sp +GPUSurfaceGLDelegate::GetDefaultPlatformGLInterface() { + return CreateGLInterface(nullptr); +} + +bool GPUSurfaceGLDelegate::AllowsDrawingWhenGpuDisabled() const { + return true; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_delegate.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..8a894107d7028abebeb0f32d281e55e6326b1d6c --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_delegate.h @@ -0,0 +1,111 @@ +// 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_GPU_GPU_SURFACE_GL_DELEGATE_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_GL_DELEGATE_H_ + +#include + +#include "flutter/common/graphics/gl_context_switch.h" +#include "flutter/flow/embedded_views.h" +#include "flutter/fml/macros.h" +#include "third_party/skia/include/core/SkMatrix.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLInterface.h" + +namespace flutter { + +// A structure to represent the frame information which is passed to the +// embedder when requesting a frame buffer object. +struct GLFrameInfo { + uint32_t width; + uint32_t height; +}; + +// A structure to represent the frame buffer information which is returned to +// the rendering backend after requesting a frame buffer object. +struct GLFBOInfo { + // The frame buffer's ID. + uint32_t fbo_id; + // The frame buffer's existing damage (i.e. damage since it was last used). + const std::optional existing_damage; +}; + +// Information passed during presentation of a frame. +struct GLPresentInfo { + uint32_t fbo_id; + + // The frame damage is a hint to compositor telling it which parts of front + // buffer need to be updated. + const std::optional& frame_damage; + + // Time at which this frame is scheduled to be presented. This is a hint + // that can be passed to the platform to drop queued frames. + std::optional presentation_time = std::nullopt; + + // The buffer damage refers to the region that needs to be set as damaged + // within the frame buffer. + const std::optional& buffer_damage; +}; + +class GPUSurfaceGLDelegate { + public: + ~GPUSurfaceGLDelegate(); + + // Called to make the main GL context current on the current thread. + virtual std::unique_ptr GLContextMakeCurrent() = 0; + + // Called to clear the current GL context on the thread. This may be called on + // either the Raster or IO threads. + virtual bool GLContextClearCurrent() = 0; + + // Inform the GL Context that there's going to be no writing beyond + // the specified region + virtual void GLContextSetDamageRegion(const std::optional& region) {} + + // Called to present the main GL surface. This is only called for the main GL + // context and not any of the contexts dedicated for IO. + virtual bool GLContextPresent(const GLPresentInfo& present_info) = 0; + + // The information about the main window bound framebuffer. ID is Typically + // FBO0. + virtual GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const = 0; + + // The rendering subsystem assumes that the ID of the main window bound + // framebuffer remains constant throughout. If this assumption in incorrect, + // embedders are required to return true from this method. In such cases, + // GLContextFBO(frame_info) will be called again to acquire the new FBO ID for + // rendering subsequent frames. + virtual bool GLContextFBOResetAfterPresent() const; + + // Returns framebuffer info for current backbuffer + virtual SurfaceFrame::FramebufferInfo GLContextFramebufferInfo() const; + + // A transformation applied to the onscreen surface before the canvas is + // flushed. + virtual SkMatrix GLContextSurfaceTransformation() const; + + virtual sk_sp GetGLInterface() const; + + // TODO(chinmaygarde): The presence of this method is to work around the fact + // that not all platforms can accept a custom GL proc table. Migrate all + // platforms to move GL proc resolution to the embedder and remove this + // method. + static sk_sp GetDefaultPlatformGLInterface(); + + using GLProcResolver = + std::function; + // Provide a custom GL proc resolver. If no such resolver is present, Skia + // will attempt to do GL proc address resolution on its own. Embedders that + // have specific opinions on GL API selection or need to add their own + // instrumentation to specific GL calls can specify custom GL functions + // here. + virtual GLProcResolver GetGLProcResolver() const; + + // Whether to allow drawing to the surface when the GPU is disabled + virtual bool AllowsDrawingWhenGpuDisabled() const; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_GL_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_impeller.cc b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..18938f41ce83cc773a874163c5e575dd895d1009 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_impeller.cc @@ -0,0 +1,180 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_gl_impeller.h" + +#include "flow/surface_frame.h" +#include "flutter/fml/make_copyable.h" +#include "impeller/display_list/dl_dispatcher.h" +#include "impeller/renderer/backend/gles/surface_gles.h" +#include "impeller/typographer/backends/skia/typographer_context_skia.h" + +namespace flutter { + +GPUSurfaceGLImpeller::GPUSurfaceGLImpeller( + GPUSurfaceGLDelegate* delegate, + std::shared_ptr context, + bool render_to_surface) + : weak_factory_(this) { + if (delegate == nullptr) { + return; + } + + if (!context || !context->IsValid()) { + return; + } + + auto aiks_context = std::make_shared( + context, impeller::TypographerContextSkia::Make()); + + if (!aiks_context->IsValid()) { + return; + } + + delegate_ = delegate; + impeller_context_ = std::move(context); + render_to_surface_ = render_to_surface; + aiks_context_ = std::move(aiks_context); + is_valid_ = true; +} + +// |Surface| +GPUSurfaceGLImpeller::~GPUSurfaceGLImpeller() = default; + +// |Surface| +bool GPUSurfaceGLImpeller::IsValid() { + return is_valid_; +} + +// |Surface| +std::unique_ptr GPUSurfaceGLImpeller::AcquireFrame( + const SkISize& size) { + if (!IsValid()) { + FML_LOG(ERROR) << "OpenGL surface was invalid."; + return nullptr; + } + + auto swap_callback = [weak = weak_factory_.GetWeakPtr(), + delegate = delegate_]() -> bool { + if (weak) { + GLPresentInfo present_info = { + .fbo_id = 0u, + .frame_damage = std::nullopt, + // TODO (https://github.com/flutter/flutter/issues/105597): wire-up + // presentation time to impeller backend. + .presentation_time = std::nullopt, + .buffer_damage = std::nullopt, + }; + delegate->GLContextPresent(present_info); + } + return true; + }; + + auto context_switch = delegate_->GLContextMakeCurrent(); + if (!context_switch->GetResult()) { + FML_LOG(ERROR) + << "Could not make the context current to acquire the frame."; + return nullptr; + } + + if (!render_to_surface_) { + return std::make_unique( + nullptr, SurfaceFrame::FramebufferInfo{.supports_readback = true}, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, size); + } + + GLFrameInfo frame_info = {static_cast(size.width()), + static_cast(size.height())}; + const GLFBOInfo fbo_info = delegate_->GLContextFBO(frame_info); + auto surface = impeller::SurfaceGLES::WrapFBO( + impeller_context_, // context + swap_callback, // swap_callback + fbo_info.fbo_id, // fbo + impeller::PixelFormat::kR8G8B8A8UNormInt, // color_format + impeller::ISize{size.width(), size.height()} // fbo_size + ); + + impeller::RenderTarget render_target = surface->GetRenderTarget(); + + SurfaceFrame::EncodeCallback encode_calback = + [aiks_context = aiks_context_, // + render_target](SurfaceFrame& surface_frame, + DlCanvas* canvas) mutable -> bool { + if (!aiks_context) { + return false; + } + + auto display_list = surface_frame.BuildDisplayList(); + if (!display_list) { + FML_LOG(ERROR) << "Could not build display list for surface frame."; + return false; + } + + auto cull_rect = render_target.GetRenderTargetSize(); + SkIRect sk_cull_rect = SkIRect::MakeWH(cull_rect.width, cull_rect.height); + return impeller::RenderToTarget(aiks_context->GetContentContext(), // + render_target, // + display_list, // + sk_cull_rect, // + /*reset_host_buffer=*/true // + ); + return true; + }; + + return std::make_unique( + nullptr, // surface + delegate_->GLContextFramebufferInfo(), // framebuffer info + encode_calback, // encode callback + fml::MakeCopyable([surface = std::move(surface)](const SurfaceFrame&) { + return surface->Present(); + }), // submit callback + size, // frame size + std::move(context_switch), // context result + true // display list fallback + ); +} + +// |Surface| +SkMatrix GPUSurfaceGLImpeller::GetRootTransformation() const { + // This backend does not currently support root surface transformations. Just + // return identity. + return {}; +} + +// |Surface| +GrDirectContext* GPUSurfaceGLImpeller::GetContext() { + // Impeller != Skia. + return nullptr; +} + +// |Surface| +std::unique_ptr +GPUSurfaceGLImpeller::MakeRenderContextCurrent() { + return delegate_->GLContextMakeCurrent(); +} + +// |Surface| +bool GPUSurfaceGLImpeller::ClearRenderContext() { + return delegate_->GLContextClearCurrent(); +} + +bool GPUSurfaceGLImpeller::AllowsDrawingWhenGpuDisabled() const { + return delegate_->AllowsDrawingWhenGpuDisabled(); +} + +// |Surface| +bool GPUSurfaceGLImpeller::EnableRasterCache() const { + return false; +} + +// |Surface| +std::shared_ptr GPUSurfaceGLImpeller::GetAiksContext() + const { + return aiks_context_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_impeller.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..4ef97425f99df0f3f9112df06076cdae28c0a89b --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_impeller.h @@ -0,0 +1,67 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_GL_IMPELLER_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_GL_IMPELLER_H_ + +#include "flutter/common/graphics/gl_context_switch.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/impeller/display_list/aiks_context.h" +#include "flutter/impeller/renderer/context.h" +#include "flutter/shell/gpu/gpu_surface_gl_delegate.h" + +namespace flutter { + +class GPUSurfaceGLImpeller final : public Surface { + public: + explicit GPUSurfaceGLImpeller(GPUSurfaceGLDelegate* delegate, + std::shared_ptr context, + bool render_to_surface); + + // |Surface| + ~GPUSurfaceGLImpeller() override; + + // |Surface| + bool IsValid() override; + + private: + GPUSurfaceGLDelegate* delegate_ = nullptr; + std::shared_ptr impeller_context_; + bool render_to_surface_ = true; + std::shared_ptr aiks_context_; + bool is_valid_ = false; + fml::TaskRunnerAffineWeakPtrFactory weak_factory_; + + // |Surface| + std::unique_ptr AcquireFrame(const SkISize& size) override; + + // |Surface| + SkMatrix GetRootTransformation() const override; + + // |Surface| + GrDirectContext* GetContext() override; + + // |Surface| + std::unique_ptr MakeRenderContextCurrent() override; + + // |Surface| + bool ClearRenderContext() override; + + // |Surface| + bool AllowsDrawingWhenGpuDisabled() const override; + + // |Surface| + bool EnableRasterCache() const override; + + // |Surface| + std::shared_ptr GetAiksContext() const override; + + FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceGLImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_GL_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_skia.cc b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..eff40d2751ce72b98e8b9943ac7687d2625ace5b --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_skia.cc @@ -0,0 +1,356 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_gl_skia.h" + +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/fml/base32.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" +#include "flutter/shell/common/context_options.h" +#include "flutter/shell/gpu/gpu_surface_gl_delegate.h" +#include "third_party/skia/include/core/SkAlphaType.h" +#include "third_party/skia/include/core/SkColorFilter.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkColorType.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrContextOptions.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLTypes.h" + +// These are common defines present on all OpenGL headers. However, we don't +// want to perform GL header resolution on each platform we support. So just +// define these upfront. It is unlikely we will need more. But, if we do, we can +// add the same here. +#define GPU_GL_RGBA8 0x8058 +#define GPU_GL_RGBA4 0x8056 +#define GPU_GL_RGB565 0x8D62 + +namespace flutter { + +// Default maximum number of bytes of GPU memory of budgeted resources in the +// cache. +// The shell will dynamically increase or decrease this cache based on the +// viewport size, unless a user has specifically requested a size on the Skia +// system channel. +static const size_t kGrCacheMaxByteSize = 24 * (1 << 20); + +sk_sp GPUSurfaceGLSkia::MakeGLContext( + GPUSurfaceGLDelegate* delegate) { + auto context_switch = delegate->GLContextMakeCurrent(); + if (!context_switch->GetResult()) { + FML_LOG(ERROR) + << "Could not make the context current to set up the Gr context."; + return nullptr; + } + + const auto options = + MakeDefaultContextOptions(ContextType::kRender, GrBackendApi::kOpenGL); + + auto context = GrDirectContexts::MakeGL(delegate->GetGLInterface(), options); + + if (!context) { + FML_LOG(ERROR) << "Failed to set up Skia Gr context."; + return nullptr; + } + + context->setResourceCacheLimit(kGrCacheMaxByteSize); + + PersistentCache::GetCacheForProcess()->PrecompileKnownSkSLs(context.get()); + + return context; +} + +GPUSurfaceGLSkia::GPUSurfaceGLSkia(GPUSurfaceGLDelegate* delegate, + bool render_to_surface) + : GPUSurfaceGLSkia(MakeGLContext(delegate), delegate, render_to_surface) { + context_owner_ = true; +} + +GPUSurfaceGLSkia::GPUSurfaceGLSkia(const sk_sp& gr_context, + GPUSurfaceGLDelegate* delegate, + bool render_to_surface) + : delegate_(delegate), + context_(gr_context), + + render_to_surface_(render_to_surface), + weak_factory_(this) { + auto context_switch = delegate_->GLContextMakeCurrent(); + if (!context_switch->GetResult()) { + FML_LOG(ERROR) + << "Could not make the context current to set up the Gr context."; + return; + } + + delegate_->GLContextClearCurrent(); + + valid_ = gr_context != nullptr; +} + +GPUSurfaceGLSkia::~GPUSurfaceGLSkia() { + if (!valid_) { + return; + } + auto context_switch = delegate_->GLContextMakeCurrent(); + if (!context_switch->GetResult()) { + FML_LOG(ERROR) << "Could not make the context current to destroy the " + "GrDirectContext resources."; + return; + } + + onscreen_surface_ = nullptr; + fbo_id_ = 0; + if (context_owner_) { + context_->releaseResourcesAndAbandonContext(); + } + context_ = nullptr; + + delegate_->GLContextClearCurrent(); +} + +// |Surface| +bool GPUSurfaceGLSkia::IsValid() { + return valid_; +} + +static SkColorType FirstSupportedColorType(GrDirectContext* context, + GrGLenum* format) { +#define RETURN_IF_RENDERABLE(x, y) \ + if (context->colorTypeSupportedAsSurface((x))) { \ + *format = (y); \ + return (x); \ + } + RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GPU_GL_RGBA8); + RETURN_IF_RENDERABLE(kARGB_4444_SkColorType, GPU_GL_RGBA4); + RETURN_IF_RENDERABLE(kRGB_565_SkColorType, GPU_GL_RGB565); + return kUnknown_SkColorType; +} + +static sk_sp WrapOnscreenSurface(GrDirectContext* context, + const SkISize& size, + intptr_t fbo) { + GrGLenum format = kUnknown_SkColorType; + const SkColorType color_type = FirstSupportedColorType(context, &format); + + GrGLFramebufferInfo framebuffer_info = {}; + framebuffer_info.fFBOID = static_cast(fbo); + framebuffer_info.fFormat = format; + + auto render_target = + GrBackendRenderTargets::MakeGL(size.width(), // width + size.height(), // height + 0, // sample count + 0, // stencil bits + framebuffer_info // framebuffer info + ); + + sk_sp colorspace = SkColorSpace::MakeSRGB(); + SkSurfaceProps surface_props(0, kUnknown_SkPixelGeometry); + + return SkSurfaces::WrapBackendRenderTarget( + context, // Gr context + render_target, // render target + GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin, // origin + color_type, // color type + colorspace, // colorspace + &surface_props // surface properties + ); +} + +bool GPUSurfaceGLSkia::CreateOrUpdateSurfaces(const SkISize& size) { + if (onscreen_surface_ != nullptr && + size == SkISize::Make(onscreen_surface_->width(), + onscreen_surface_->height())) { + // Surface size appears unchanged. So bail. + return true; + } + + // We need to do some updates. + TRACE_EVENT0("flutter", "UpdateSurfacesSize"); + + // Either way, we need to get rid of previous surface. + onscreen_surface_ = nullptr; + fbo_id_ = 0; + + if (size.isEmpty()) { + FML_LOG(ERROR) << "Cannot create surfaces of empty size."; + return false; + } + + sk_sp onscreen_surface; + + GLFrameInfo frame_info = {static_cast(size.width()), + static_cast(size.height())}; + const GLFBOInfo fbo_info = delegate_->GLContextFBO(frame_info); + onscreen_surface = WrapOnscreenSurface(context_.get(), // GL context + size, // root surface size + fbo_info.fbo_id // window FBO ID + ); + + if (onscreen_surface == nullptr) { + // If the onscreen surface could not be wrapped. There is absolutely no + // point in moving forward. + FML_LOG(ERROR) << "Could not wrap onscreen surface."; + return false; + } + + onscreen_surface_ = std::move(onscreen_surface); + fbo_id_ = fbo_info.fbo_id; + existing_damage_ = fbo_info.existing_damage; + + return true; +} + +// |Surface| +SkMatrix GPUSurfaceGLSkia::GetRootTransformation() const { + return delegate_->GLContextSurfaceTransformation(); +} + +// |Surface| +std::unique_ptr GPUSurfaceGLSkia::AcquireFrame( + const SkISize& size) { + if (delegate_ == nullptr) { + return nullptr; + } + auto context_switch = delegate_->GLContextMakeCurrent(); + if (!context_switch->GetResult()) { + FML_LOG(ERROR) + << "Could not make the context current to acquire the frame."; + return nullptr; + } + + SurfaceFrame::FramebufferInfo framebuffer_info; + + // TODO(38466): Refactor GPU surface APIs take into account the fact that an + // external view embedder may want to render to the root surface. + if (!render_to_surface_) { + framebuffer_info.supports_readback = true; + return std::make_unique( + nullptr, framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, size); + } + + const auto root_surface_transformation = GetRootTransformation(); + + sk_sp surface = + AcquireRenderSurface(size, root_surface_transformation); + + if (surface == nullptr) { + return nullptr; + } + + surface->getCanvas()->setMatrix(root_surface_transformation); + + SurfaceFrame::EncodeCallback encode_callback = + [weak = weak_factory_.GetWeakPtr()](const SurfaceFrame& surface_frame, + DlCanvas* canvas) { + TRACE_EVENT0("flutter", "GrDirectContext::flushAndSubmit"); + if (weak) { + weak->context_->flushAndSubmit(); + return true; + } + return false; + }; + SurfaceFrame::SubmitCallback submit_callback = + [weak = weak_factory_.GetWeakPtr()](const SurfaceFrame& surface_frame) { + return weak ? weak->PresentSurface(surface_frame) : false; + }; + + framebuffer_info = delegate_->GLContextFramebufferInfo(); + if (!framebuffer_info.existing_damage.has_value()) { + framebuffer_info.existing_damage = existing_damage_; + } + return std::make_unique(surface, framebuffer_info, + encode_callback, submit_callback, size, + std::move(context_switch)); +} + +bool GPUSurfaceGLSkia::PresentSurface(const SurfaceFrame& frame) { + if (delegate_ == nullptr || context_ == nullptr) { + return false; + } + + delegate_->GLContextSetDamageRegion(frame.submit_info().buffer_damage); + + GLPresentInfo present_info = { + .fbo_id = fbo_id_, + .frame_damage = frame.submit_info().frame_damage, + .presentation_time = frame.submit_info().presentation_time, + .buffer_damage = frame.submit_info().buffer_damage, + }; + if (!delegate_->GLContextPresent(present_info)) { + return false; + } + + if (delegate_->GLContextFBOResetAfterPresent()) { + auto current_size = + SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height()); + + GLFrameInfo frame_info = {static_cast(current_size.width()), + static_cast(current_size.height())}; + + // The FBO has changed, ask the delegate for the new FBO and do a surface + // re-wrap. + const GLFBOInfo fbo_info = delegate_->GLContextFBO(frame_info); + auto new_onscreen_surface = + WrapOnscreenSurface(context_.get(), // GL context + current_size, // root surface size + fbo_info.fbo_id // window FBO ID + ); + + if (!new_onscreen_surface) { + return false; + } + + onscreen_surface_ = std::move(new_onscreen_surface); + fbo_id_ = fbo_info.fbo_id; + existing_damage_ = fbo_info.existing_damage; + } + + return true; +} + +sk_sp GPUSurfaceGLSkia::AcquireRenderSurface( + const SkISize& untransformed_size, + const SkMatrix& root_surface_transformation) { + const auto transformed_rect = root_surface_transformation.mapRect( + SkRect::MakeWH(untransformed_size.width(), untransformed_size.height())); + + const auto transformed_size = + SkISize::Make(transformed_rect.width(), transformed_rect.height()); + + if (!CreateOrUpdateSurfaces(transformed_size)) { + return nullptr; + } + + return onscreen_surface_; +} + +// |Surface| +GrDirectContext* GPUSurfaceGLSkia::GetContext() { + return context_.get(); +} + +// |Surface| +std::unique_ptr GPUSurfaceGLSkia::MakeRenderContextCurrent() { + return delegate_->GLContextMakeCurrent(); +} + +// |Surface| +bool GPUSurfaceGLSkia::ClearRenderContext() { + return delegate_->GLContextClearCurrent(); +} + +// |Surface| +bool GPUSurfaceGLSkia::AllowsDrawingWhenGpuDisabled() const { + return delegate_->AllowsDrawingWhenGpuDisabled(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_skia.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..91d227838f8afe48cc30c821771f47fea34b1d86 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_gl_skia.h @@ -0,0 +1,91 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_GL_SKIA_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_GL_SKIA_H_ + +#include +#include + +#include "flutter/common/graphics/gl_context_switch.h" +#include "flutter/flow/embedded_views.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/shell/gpu/gpu_surface_gl_delegate.h" + +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace flutter { + +class GPUSurfaceGLSkia : public Surface { + public: + static sk_sp MakeGLContext(GPUSurfaceGLDelegate* delegate); + + GPUSurfaceGLSkia(GPUSurfaceGLDelegate* delegate, bool render_to_surface); + + // Creates a new GL surface reusing an existing GrDirectContext. + GPUSurfaceGLSkia(const sk_sp& gr_context, + GPUSurfaceGLDelegate* delegate, + bool render_to_surface); + + // |Surface| + ~GPUSurfaceGLSkia() override; + + // |Surface| + bool IsValid() override; + + // |Surface| + std::unique_ptr AcquireFrame(const SkISize& size) override; + + // |Surface| + SkMatrix GetRootTransformation() const override; + + // |Surface| + GrDirectContext* GetContext() override; + + // |Surface| + std::unique_ptr MakeRenderContextCurrent() override; + + // |Surface| + bool ClearRenderContext() override; + + // |Surface| + bool AllowsDrawingWhenGpuDisabled() const override; + + private: + bool CreateOrUpdateSurfaces(const SkISize& size); + + sk_sp AcquireRenderSurface( + const SkISize& untransformed_size, + const SkMatrix& root_surface_transformation); + + bool PresentSurface(const SurfaceFrame& frame); + + GPUSurfaceGLDelegate* delegate_; + sk_sp context_; + sk_sp onscreen_surface_; + /// FBO backing the current `onscreen_surface_`. + uint32_t fbo_id_ = 0; + // The current FBO's existing damage, as tracked by the GPU surface, delegates + // still have an option of overriding this damage with their own in + // `GLContextFrameBufferInfo`. + std::optional existing_damage_ = std::nullopt; + bool context_owner_ = false; + // TODO(38466): Refactor GPU surface APIs take into account the fact that an + // external view embedder may want to render to the root surface. This is a + // hack to make avoid allocating resources for the root surface when an + // external view embedder is present. + const bool render_to_surface_ = true; + bool valid_ = false; + + // WeakPtrFactory must be the last member. + fml::TaskRunnerAffineWeakPtrFactory weak_factory_; + FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceGLSkia); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_GL_SKIA_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_delegate.cc b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..7a22d8de88a89a90b52a52ce73b9f6b460ebe46b --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_delegate.cc @@ -0,0 +1,23 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_metal_delegate.h" + +namespace flutter { + +GPUSurfaceMetalDelegate::GPUSurfaceMetalDelegate( + MTLRenderTargetType render_target_type) + : render_target_type_(render_target_type) {} + +GPUSurfaceMetalDelegate::~GPUSurfaceMetalDelegate() = default; + +MTLRenderTargetType GPUSurfaceMetalDelegate::GetRenderTargetType() { + return render_target_type_; +} + +bool GPUSurfaceMetalDelegate::AllowsDrawingWhenGpuDisabled() const { + return true; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_delegate.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..54a86c28556237d6d0361ac8987e7275822c6ee4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_delegate.h @@ -0,0 +1,111 @@ +// 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_GPU_GPU_SURFACE_METAL_DELEGATE_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_DELEGATE_H_ + +#include + +#include "flutter/fml/macros.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlTypes.h" + +namespace flutter { + +// expected to be id +typedef void* GPUMTLDeviceHandle; + +// expected to be id +typedef void* GPUMTLCommandQueueHandle; + +// expected to be CAMetalLayer* +typedef void* GPUCAMetalLayerHandle; + +// expected to be id +typedef const void* GPUMTLTextureHandle; + +typedef void (*GPUMTLDestructionCallback)(void* /* destruction_context */); + +struct GPUMTLTextureInfo { + int64_t texture_id; + GPUMTLTextureHandle texture; + GPUMTLDestructionCallback destruction_callback; + void* destruction_context; +}; + +enum class MTLRenderTargetType { kMTLTexture, kCAMetalLayer }; + +//------------------------------------------------------------------------------ +/// @brief Interface implemented by all platform surfaces that can present +/// a metal backing store to the "screen". The GPU surface +/// abstraction (which abstracts the client rendering API) uses this +/// delegation pattern to tell the platform surface (which abstracts +/// how backing stores fulfilled by the selected client rendering +/// API end up on the "screen" on a particular platform) when the +/// rasterizer needs to allocate and present the software backing +/// store. +/// +/// @see |IOSurfaceMetal| and |EmbedderSurfaceMetal|. +/// +class GPUSurfaceMetalDelegate { + public: + //------------------------------------------------------------------------------ + /// @brief Construct a new GPUSurfaceMetalDelegate object with the specified + /// render_target type. + /// + /// @see |MTLRenderTargetType| + /// + explicit GPUSurfaceMetalDelegate(MTLRenderTargetType render_target); + + virtual ~GPUSurfaceMetalDelegate(); + + //------------------------------------------------------------------------------ + /// @brief Returns the handle to the CAMetalLayer to render to. This is only + /// called when the specified render target type is `kCAMetalLayer`. + /// + virtual GPUCAMetalLayerHandle GetCAMetalLayer( + const SkISize& frame_info) const = 0; + + //------------------------------------------------------------------------------ + /// @brief Presents the drawable to the "screen". The drawable is obtained + /// from the CAMetalLayer that given by `GetCAMetalLayer` call. This is only + /// called when the specified render target type in `kCAMetalLayer`. + /// + /// @see |GPUSurfaceMetalDelegate::GetCAMetalLayer| + /// + virtual bool PresentDrawable(GrMTLHandle drawable) const = 0; + + virtual bool PreparePresent(GrMTLHandle drawable) const { return true; } + + //------------------------------------------------------------------------------ + /// @brief Returns the handle to the MTLTexture to render to. This is only + /// called when the specified render target type is `kMTLTexture`. + /// + virtual GPUMTLTextureInfo GetMTLTexture(const SkISize& frame_info) const = 0; + + //------------------------------------------------------------------------------ + /// @brief Presents the texture with `texture_id` to the "screen". + /// `texture_id` corresponds to a texture that has been obtained by an earlier + /// call to `GetMTLTexture`. This is only called when the specified render + /// target type is `kMTLTexture`. + /// + /// @see |GPUSurfaceMetalDelegate::GetMTLTexture| + /// + virtual bool PresentTexture(GPUMTLTextureInfo texture) const = 0; + + //------------------------------------------------------------------------------ + /// @brief Whether to allow drawing to the surface when the GPU is disabled + /// + virtual bool AllowsDrawingWhenGpuDisabled() const; + + MTLRenderTargetType GetRenderTargetType(); + + private: + const MTLRenderTargetType render_target_type_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..36d40207d07cd95f1a4965877b2302f47ee73987 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.h @@ -0,0 +1,85 @@ +// 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_GPU_GPU_SURFACE_METAL_IMPELLER_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_IMPELLER_H_ + +#include + +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/impeller/display_list/aiks_context.h" +#include "flutter/impeller/renderer/backend/metal/context_mtl.h" +#include "flutter/impeller/renderer/backend/metal/swapchain_transients_mtl.h" +#include "flutter/shell/gpu/gpu_surface_metal_delegate.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlTypes.h" + +namespace flutter { + +class IMPELLER_CA_METAL_LAYER_AVAILABLE GPUSurfaceMetalImpeller + : public Surface { + public: + GPUSurfaceMetalImpeller(GPUSurfaceMetalDelegate* delegate, + const std::shared_ptr& context, + bool render_to_surface = true); + + // |Surface| + ~GPUSurfaceMetalImpeller(); + + // |Surface| + bool IsValid() override; + + virtual Surface::SurfaceData GetSurfaceData() const override; + + private: + const GPUSurfaceMetalDelegate* delegate_; + const MTLRenderTargetType render_target_type_; + std::shared_ptr aiks_context_; + id last_texture_; + // TODO(38466): Refactor GPU surface APIs take into account the fact that an + // external view embedder may want to render to the root surface. This is a + // hack to make avoid allocating resources for the root surface when an + // external view embedder is present. + bool render_to_surface_ = true; + bool disable_partial_repaint_ = false; + // Accumulated damage for each framebuffer; Key is address of underlying + // MTLTexture for each drawable + std::shared_ptr> damage_ = + std::make_shared>(); + std::shared_ptr swapchain_transients_; + + // |Surface| + std::unique_ptr AcquireFrame( + const SkISize& frame_size) override; + + std::unique_ptr AcquireFrameFromCAMetalLayer( + const SkISize& frame_size); + + std::unique_ptr AcquireFrameFromMTLTexture( + const SkISize& frame_size); + + // |Surface| + SkMatrix GetRootTransformation() const override; + + // |Surface| + GrDirectContext* GetContext() override; + + // |Surface| + std::unique_ptr MakeRenderContextCurrent() override; + + // |Surface| + bool AllowsDrawingWhenGpuDisabled() const override; + + // |Surface| + bool EnableRasterCache() const override; + + // |Surface| + std::shared_ptr GetAiksContext() const override; + + FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceMetalImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.mm b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.mm new file mode 100644 index 0000000000000000000000000000000000000000..953db1762788dd24bd8150a863e5bda42368588b --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.mm @@ -0,0 +1,412 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_metal_impeller.h" + +#import +#import +#include "flow/surface.h" +#include "flow/surface_frame.h" +#include "impeller/display_list/aiks_context.h" +#include "impeller/renderer/backend/metal/swapchain_transients_mtl.h" + +#include "flutter/common/settings.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/trace_event.h" +#include "impeller/display_list/dl_dispatcher.h" +#include "impeller/renderer/backend/metal/surface_mtl.h" +#include "impeller/typographer/backends/skia/typographer_context_skia.h" + +static_assert(__has_feature(objc_arc), "ARC must be enabled."); + +namespace flutter { + +GPUSurfaceMetalImpeller::GPUSurfaceMetalImpeller( + GPUSurfaceMetalDelegate* delegate, + const std::shared_ptr& context, + bool render_to_surface) + : delegate_(delegate), + render_target_type_(delegate->GetRenderTargetType()), + aiks_context_(context), + render_to_surface_(render_to_surface) { + // If this preference is explicitly set, we allow for disabling partial repaint. + NSNumber* disablePartialRepaint = + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTDisablePartialRepaint"]; + if (disablePartialRepaint != nil) { + disable_partial_repaint_ = disablePartialRepaint.boolValue; + } + if (aiks_context_) { + swapchain_transients_ = std::make_shared( + aiks_context_->GetContext()->GetResourceAllocator()); + } +} + +GPUSurfaceMetalImpeller::~GPUSurfaceMetalImpeller() = default; + +// |Surface| +bool GPUSurfaceMetalImpeller::IsValid() { + return !!aiks_context_ && aiks_context_->IsValid(); +} + +// |Surface| +std::unique_ptr GPUSurfaceMetalImpeller::AcquireFrame(const SkISize& frame_size) { + TRACE_EVENT0("impeller", "GPUSurfaceMetalImpeller::AcquireFrame"); + + if (!IsValid()) { + FML_LOG(ERROR) << "Metal surface was invalid."; + return nullptr; + } + + if (frame_size.isEmpty()) { + FML_LOG(ERROR) << "Metal surface was asked for an empty frame."; + return nullptr; + } + + if (!render_to_surface_) { + return std::make_unique( + nullptr, SurfaceFrame::FramebufferInfo(), + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { return true; }, + [](const SurfaceFrame& surface_frame) { return true; }, frame_size); + } + + switch (render_target_type_) { + case MTLRenderTargetType::kCAMetalLayer: + return AcquireFrameFromCAMetalLayer(frame_size); + case MTLRenderTargetType::kMTLTexture: + return AcquireFrameFromMTLTexture(frame_size); + default: + FML_CHECK(false) << "Unknown MTLRenderTargetType type."; + } + + return nullptr; +} + +std::unique_ptr GPUSurfaceMetalImpeller::AcquireFrameFromCAMetalLayer( + const SkISize& frame_size) { + CAMetalLayer* layer = (__bridge CAMetalLayer*)delegate_->GetCAMetalLayer(frame_size); + if (!layer) { + FML_LOG(ERROR) << "Invalid CAMetalLayer given by the embedder."; + return nullptr; + } + + id drawable = + impeller::SurfaceMTL::GetMetalDrawableAndValidate(aiks_context_->GetContext(), layer); + if (!drawable) { + return nullptr; + } + if (Settings::kSurfaceDataAccessible) { + last_texture_ = drawable.texture; + } + +#ifdef IMPELLER_DEBUG + impeller::ContextMTL::Cast(*aiks_context_->GetContext()).GetCaptureManager()->StartCapture(); +#endif // IMPELLER_DEBUG + + __weak id weak_last_texture = last_texture_; + __weak CAMetalLayer* weak_layer = layer; + SurfaceFrame::EncodeCallback encode_callback = + fml::MakeCopyable([damage = damage_, + disable_partial_repaint = disable_partial_repaint_, // + aiks_context = aiks_context_, // + drawable, // + weak_last_texture, // + weak_layer, // + swapchain_transients = swapchain_transients_ // + ](SurfaceFrame& surface_frame, DlCanvas* canvas) mutable -> bool { + id strong_last_texture = weak_last_texture; + CAMetalLayer* strong_layer = weak_layer; + if (!strong_last_texture || !strong_layer) { + return false; + } + strong_layer.presentsWithTransaction = surface_frame.submit_info().present_with_transaction; + if (!aiks_context) { + return false; + } + + auto display_list = surface_frame.BuildDisplayList(); + if (!display_list) { + FML_LOG(ERROR) << "Could not build display list for surface frame."; + return false; + } + + if (!disable_partial_repaint && damage) { + void* texture = (__bridge void*)strong_last_texture; + for (auto& entry : *damage) { + if (entry.first != texture) { + // Accumulate damage for other framebuffers + if (surface_frame.submit_info().frame_damage) { + entry.second.join(*surface_frame.submit_info().frame_damage); + } + } + } + // Reset accumulated damage for current framebuffer + (*damage)[texture] = SkIRect::MakeEmpty(); + } + + std::optional clip_rect; + if (surface_frame.submit_info().buffer_damage.has_value()) { + auto buffer_damage = surface_frame.submit_info().buffer_damage; + clip_rect = impeller::IRect::MakeXYWH(buffer_damage->x(), buffer_damage->y(), + buffer_damage->width(), buffer_damage->height()); + } + + auto surface = impeller::SurfaceMTL::MakeFromMetalLayerDrawable( + aiks_context->GetContext(), drawable, swapchain_transients, clip_rect); + + // The surface may be null if we failed to allocate the onscreen render target + // due to running out of memory. + if (!surface) { + return false; + } + surface->PresentWithTransaction(surface_frame.submit_info().present_with_transaction); + + if (clip_rect && clip_rect->IsEmpty()) { + if (!surface->PreparePresent()) { + return false; + } + surface_frame.set_user_data(std::move(surface)); + return true; + } + + impeller::IRect cull_rect = surface->coverage(); + SkIRect sk_cull_rect = SkIRect::MakeWH(cull_rect.GetWidth(), cull_rect.GetHeight()); + surface->SetFrameBoundary(surface_frame.submit_info().frame_boundary); + + const bool reset_host_buffer = surface_frame.submit_info().frame_boundary; + auto render_result = impeller::RenderToTarget(aiks_context->GetContentContext(), // + surface->GetRenderTarget(), // + display_list, // + sk_cull_rect, // + /*reset_host_buffer=*/reset_host_buffer // + ); + if (!render_result) { + return false; + } + + if (!surface->PreparePresent()) { + return false; + } + surface_frame.set_user_data(std::move(surface)); + return true; + }); + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + if (!disable_partial_repaint_) { + // Provide accumulated damage to rasterizer (area in current framebuffer that lags behind + // front buffer) + void* texture = (__bridge void*)drawable.texture; + auto i = damage_->find(texture); + if (i != damage_->end()) { + framebuffer_info.existing_damage = i->second; + } + framebuffer_info.supports_partial_repaint = true; + } + + return std::make_unique( + nullptr, // surface + framebuffer_info, // framebuffer info + encode_callback, // submit callback + [](SurfaceFrame& surface_frame) { return surface_frame.take_user_data()->Present(); }, + frame_size, // frame size + nullptr, // context result + true // display list fallback + ); +} + +std::unique_ptr GPUSurfaceMetalImpeller::AcquireFrameFromMTLTexture( + const SkISize& frame_size) { + GPUMTLTextureInfo texture_info = delegate_->GetMTLTexture(frame_size); + id mtl_texture = (__bridge id)texture_info.texture; + if (!mtl_texture) { + FML_LOG(ERROR) << "Invalid MTLTexture given by the embedder."; + return nullptr; + } + + if (Settings::kSurfaceDataAccessible) { + last_texture_ = mtl_texture; + } + +#ifdef IMPELLER_DEBUG + impeller::ContextMTL::Cast(*aiks_context_->GetContext()).GetCaptureManager()->StartCapture(); +#endif // IMPELLER_DEBUG + + __weak id weak_texture = mtl_texture; + SurfaceFrame::EncodeCallback encode_callback = + fml::MakeCopyable([disable_partial_repaint = disable_partial_repaint_, // + damage = damage_, + aiks_context = aiks_context_, // + weak_texture, // + swapchain_transients = swapchain_transients_ // + ](SurfaceFrame& surface_frame, DlCanvas* canvas) mutable -> bool { + id strong_texture = weak_texture; + if (!strong_texture) { + return false; + } + if (!aiks_context) { + return false; + } + auto display_list = surface_frame.BuildDisplayList(); + if (!display_list) { + FML_LOG(ERROR) << "Could not build display list for surface frame."; + return false; + } + + if (!disable_partial_repaint && damage) { + void* texture_ptr = (__bridge void*)strong_texture; + for (auto& entry : *damage) { + if (entry.first != texture_ptr) { + // Accumulate damage for other framebuffers + if (surface_frame.submit_info().frame_damage) { + entry.second.join(*surface_frame.submit_info().frame_damage); + } + } + } + // Reset accumulated damage for current framebuffer + (*damage)[texture_ptr] = SkIRect::MakeEmpty(); + } + + std::optional clip_rect; + if (surface_frame.submit_info().buffer_damage.has_value()) { + auto buffer_damage = surface_frame.submit_info().buffer_damage; + clip_rect = impeller::IRect::MakeXYWH(buffer_damage->x(), buffer_damage->y(), + buffer_damage->width(), buffer_damage->height()); + } + + auto surface = impeller::SurfaceMTL::MakeFromTexture( + aiks_context->GetContext(), strong_texture, swapchain_transients, clip_rect); + + surface->PresentWithTransaction(surface_frame.submit_info().present_with_transaction); + + if (clip_rect && clip_rect->IsEmpty()) { + if (!surface->PreparePresent()) { + return false; + } + return surface->Present(); + } + + impeller::IRect cull_rect = surface->coverage(); + SkIRect sk_cull_rect = SkIRect::MakeWH(cull_rect.GetWidth(), cull_rect.GetHeight()); + auto render_result = impeller::RenderToTarget(aiks_context->GetContentContext(), // + surface->GetRenderTarget(), // + display_list, // + sk_cull_rect, // + /*reset_host_buffer=*/true // + ); + if (!render_result) { + FML_LOG(ERROR) << "Failed to render Impeller frame"; + return false; + } + if (!surface->PreparePresent()) { + return false; + } + return surface->PreparePresent(); + }); + + SurfaceFrame::SubmitCallback submit_callback = + [texture_info, delegate = delegate_](const SurfaceFrame& surface_frame) { + return delegate->PresentTexture(texture_info); + }; + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + if (!disable_partial_repaint_) { + // Provide accumulated damage to rasterizer (area in current framebuffer that lags behind + // front buffer) + void* texture = (__bridge void*)mtl_texture; + auto i = damage_->find(texture); + if (i != damage_->end()) { + framebuffer_info.existing_damage = i->second; + } + framebuffer_info.supports_partial_repaint = true; + } + + return std::make_unique(nullptr, // surface + framebuffer_info, // framebuffer info + encode_callback, + submit_callback, // submit callback + frame_size, // frame size + nullptr, // context result + true // display list fallback + ); +} + +// |Surface| +SkMatrix GPUSurfaceMetalImpeller::GetRootTransformation() const { + // This backend does not currently support root surface transformations. Just + // return identity. + return {}; +} + +// |Surface| +GrDirectContext* GPUSurfaceMetalImpeller::GetContext() { + return nullptr; +} + +// |Surface| +std::unique_ptr GPUSurfaceMetalImpeller::MakeRenderContextCurrent() { + // This backend has no such concept. + return std::make_unique(true); +} + +bool GPUSurfaceMetalImpeller::AllowsDrawingWhenGpuDisabled() const { + return delegate_->AllowsDrawingWhenGpuDisabled(); +} + +// |Surface| +bool GPUSurfaceMetalImpeller::EnableRasterCache() const { + return false; +} + +// |Surface| +std::shared_ptr GPUSurfaceMetalImpeller::GetAiksContext() const { + return aiks_context_; +} + +Surface::SurfaceData GPUSurfaceMetalImpeller::GetSurfaceData() const { + if (!(last_texture_ && [last_texture_ conformsToProtocol:@protocol(MTLTexture)])) { + return {}; + } + id texture = last_texture_; + int bytesPerPixel = 0; + std::string pixel_format; + switch (texture.pixelFormat) { + case MTLPixelFormatBGR10_XR: + bytesPerPixel = 4; + pixel_format = "MTLPixelFormatBGR10_XR"; + break; + case MTLPixelFormatBGRA10_XR: + bytesPerPixel = 8; + pixel_format = "MTLPixelFormatBGRA10_XR"; + break; + case MTLPixelFormatBGRA8Unorm: + bytesPerPixel = 4; + pixel_format = "MTLPixelFormatBGRA8Unorm"; + break; + case MTLPixelFormatRGBA16Float: + bytesPerPixel = 8; + pixel_format = "MTLPixelFormatRGBA16Float"; + break; + default: + return {}; + } + + // Zero initialized so that errors are easier to find at the cost of + // performance. + sk_sp result = + SkData::MakeZeroInitialized(texture.width * texture.height * bytesPerPixel); + [texture getBytes:result->writable_data() + bytesPerRow:texture.width * bytesPerPixel + fromRegion:MTLRegionMake2D(0, 0, texture.width, texture.height) + mipmapLevel:0]; + return { + .pixel_format = pixel_format, + .data = result, + }; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller_unittests.mm b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller_unittests.mm new file mode 100644 index 0000000000000000000000000000000000000000..6ea124644344ca11117bbcd5b0fd09314e3a576d --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller_unittests.mm @@ -0,0 +1,163 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "flutter/shell/gpu/gpu_surface_metal_impeller.h" +#include "gtest/gtest.h" +#include "impeller/display_list/aiks_context.h" +#include "impeller/entity/mtl/entity_shaders.h" +#include "impeller/entity/mtl/framebuffer_blend_shaders.h" +#include "impeller/entity/mtl/modern_shaders.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/typographer/typographer_context.h" + +namespace flutter { +namespace testing { + +class TestGPUSurfaceMetalDelegate : public GPUSurfaceMetalDelegate { + public: + TestGPUSurfaceMetalDelegate() : GPUSurfaceMetalDelegate(MTLRenderTargetType::kCAMetalLayer) { + layer_ = [[CAMetalLayer alloc] init]; + } + + ~TestGPUSurfaceMetalDelegate() = default; + + GPUCAMetalLayerHandle GetCAMetalLayer(const SkISize& frame_info) const override { + layer_.drawableSize = CGSizeMake(frame_info.width(), frame_info.height()); + return (__bridge GPUCAMetalLayerHandle)(layer_); + } + + bool PresentDrawable(GrMTLHandle drawable) const override { return true; } + + GPUMTLTextureInfo GetMTLTexture(const SkISize& frame_info) const override { return {}; } + + bool PresentTexture(GPUMTLTextureInfo texture) const override { return true; } + + bool AllowsDrawingWhenGpuDisabled() const override { return true; } + + void SetDevice() { layer_.device = ::MTLCreateSystemDefaultDevice(); } + + private: + CAMetalLayer* layer_ = nil; +}; + +static std::shared_ptr CreateImpellerContext() { + std::vector> shader_mappings = { + std::make_shared(impeller_entity_shaders_data, + impeller_entity_shaders_length), + std::make_shared(impeller_modern_shaders_data, + impeller_modern_shaders_length), + std::make_shared(impeller_framebuffer_blend_shaders_data, + impeller_framebuffer_blend_shaders_length), + }; + auto sync_switch = std::make_shared(false); + return impeller::ContextMTL::Create(impeller::Flags{}, shader_mappings, sync_switch, + "Impeller Library"); +} + +TEST(GPUSurfaceMetalImpeller, InvalidImpellerContextCreatesCausesSurfaceToBeInvalid) { + auto delegate = std::make_shared(); + auto surface = std::make_shared(delegate.get(), nullptr); + + ASSERT_FALSE(surface->IsValid()); +} + +TEST(GPUSurfaceMetalImpeller, CanCreateValidSurface) { + auto delegate = std::make_shared(); + auto surface = std::make_shared( + delegate.get(), std::make_shared(CreateImpellerContext(), nullptr)); + + ASSERT_TRUE(surface->IsValid()); +} + +TEST(GPUSurfaceMetalImpeller, AcquireFrameFromCAMetalLayerNullChecksDrawable) { + auto delegate = std::make_shared(); + std::shared_ptr surface = std::make_shared( + delegate.get(), std::make_shared(CreateImpellerContext(), nullptr)); + + ASSERT_TRUE(surface->IsValid()); + + auto frame = surface->AcquireFrame(SkISize::Make(100, 100)); + ASSERT_EQ(frame, nullptr); +} + +TEST(GPUSurfaceMetalImpeller, AcquireFrameFromCAMetalLayerDoesNotRetainThis) { + auto delegate = std::make_shared(); + delegate->SetDevice(); + std::unique_ptr surface = std::make_unique( + delegate.get(), std::make_shared(CreateImpellerContext(), nullptr)); + + ASSERT_TRUE(surface->IsValid()); + + auto frame = surface->AcquireFrame(SkISize::Make(100, 100)); + ASSERT_TRUE(frame); + + // Simulate a rasterizer teardown, e.g. due to going to the background. + surface.reset(); + + ASSERT_TRUE(frame->Submit()); +} + +TEST(GPUSurfaceMetalImpeller, ResetHostBufferBasedOnFrameBoundary) { + auto delegate = std::make_shared(); + delegate->SetDevice(); + + auto context = CreateImpellerContext(); + std::unique_ptr surface = std::make_unique( + delegate.get(), std::make_shared(context, nullptr)); + + ASSERT_TRUE(surface->IsValid()); + + auto& host_buffer = surface->GetAiksContext()->GetContentContext().GetTransientsBuffer(); + + EXPECT_EQ(host_buffer.GetStateForTest().current_frame, 0u); + + auto frame = surface->AcquireFrame(SkISize::Make(100, 100)); + frame->set_submit_info({.frame_boundary = false}); + + ASSERT_TRUE(frame->Submit()); + EXPECT_EQ(host_buffer.GetStateForTest().current_frame, 0u); + + frame = surface->AcquireFrame(SkISize::Make(100, 100)); + frame->set_submit_info({.frame_boundary = true}); + + ASSERT_TRUE(frame->Submit()); + EXPECT_EQ(host_buffer.GetStateForTest().current_frame, 1u); +} + +#ifdef IMPELLER_DEBUG +TEST(GPUSurfaceMetalImpeller, CreatesImpellerCaptureScope) { + auto delegate = std::make_shared(); + delegate->SetDevice(); + + auto context = CreateImpellerContext(); + auto aiks_context = std::make_shared(context, nullptr); + + EXPECT_FALSE(context->GetCaptureManager()->CaptureScopeActive()); + + std::unique_ptr surface = + std::make_unique(delegate.get(), aiks_context); + auto frame_1 = surface->AcquireFrame(SkISize::Make(100, 100)); + frame_1->set_submit_info({.frame_boundary = false}); + + EXPECT_TRUE(context->GetCaptureManager()->CaptureScopeActive()); + + std::unique_ptr surface_2 = + std::make_unique(delegate.get(), aiks_context); + auto frame_2 = surface->AcquireFrame(SkISize::Make(100, 100)); + frame_2->set_submit_info({.frame_boundary = true}); + + EXPECT_TRUE(context->GetCaptureManager()->CaptureScopeActive()); + + ASSERT_TRUE(frame_1->Submit()); + EXPECT_TRUE(context->GetCaptureManager()->CaptureScopeActive()); + ASSERT_TRUE(frame_2->Submit()); + EXPECT_FALSE(context->GetCaptureManager()->CaptureScopeActive()); +} +#endif // IMPELLER_DEBUG + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_skia.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..e4fb83127cd87e77b954aad02892d6ff8d506801 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_skia.h @@ -0,0 +1,75 @@ +// 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_GPU_GPU_SURFACE_METAL_SKIA_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_SKIA_H_ + +#if !SLIMPELLER + +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/shell/gpu/gpu_surface_metal_delegate.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" + +namespace flutter { + +class SK_API_AVAILABLE_CA_METAL_LAYER GPUSurfaceMetalSkia : public Surface { + public: + GPUSurfaceMetalSkia(GPUSurfaceMetalDelegate* delegate, + sk_sp context, + bool render_to_surface = true); + + // |Surface| + ~GPUSurfaceMetalSkia(); + + // |Surface| + bool IsValid() override; + + private: + const GPUSurfaceMetalDelegate* delegate_; + const MTLRenderTargetType render_target_type_; + sk_sp context_; + GrDirectContext* precompiled_sksl_context_ = nullptr; + // TODO(38466): Refactor GPU surface APIs take into account the fact that an + // external view embedder may want to render to the root surface. This is a + // hack to make avoid allocating resources for the root surface when an + // external view embedder is present. + bool render_to_surface_ = true; + bool disable_partial_repaint_ = false; + + // Accumulated damage for each framebuffer; Key is address of underlying + // MTLTexture for each drawable + std::map damage_; + + // |Surface| + std::unique_ptr AcquireFrame(const SkISize& size) override; + + // |Surface| + SkMatrix GetRootTransformation() const override; + + // |Surface| + GrDirectContext* GetContext() override; + + // |Surface| + std::unique_ptr MakeRenderContextCurrent() override; + + // |Surface| + bool AllowsDrawingWhenGpuDisabled() const override; + + std::unique_ptr AcquireFrameFromCAMetalLayer( + const SkISize& frame_info); + + std::unique_ptr AcquireFrameFromMTLTexture( + const SkISize& frame_info); + + void PrecompileKnownSkSLsIfNecessary(); + + FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceMetalSkia); +}; + +} // namespace flutter + +#endif // !SLIMPELLER + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_SKIA_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_skia.mm b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_skia.mm new file mode 100644 index 0000000000000000000000000000000000000000..111c5b244d10214f399956b81a62e41b22fe9d6e --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_metal_skia.mm @@ -0,0 +1,286 @@ +// 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 "flow/surface_frame.h" +#if !SLIMPELLER + +#include "flutter/shell/gpu/gpu_surface_metal_skia.h" + +#import +#import + +#include + +#include "flutter/common/graphics/persistent_cache.h" +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/platform/darwin/cf_utils.h" +#include "flutter/fml/trace_event.h" +#include "flutter/shell/gpu/gpu_surface_metal_delegate.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkColorType.h" +#include "third_party/skia/include/core/SkMatrix.h" +#include "third_party/skia/include/core/SkRect.h" +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/core/SkSurfaceProps.h" +#include "third_party/skia/include/gpu/GpuTypes.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlTypes.h" +#include "third_party/skia/include/ports/SkCFObject.h" + +static_assert(__has_feature(objc_arc), "ARC must be enabled."); + +namespace flutter { + +namespace { +sk_sp CreateSurfaceFromMetalTexture(GrDirectContext* context, + id texture, + GrSurfaceOrigin origin, + SkColorType color_type, + sk_sp color_space, + const SkSurfaceProps* props, + SkSurfaces::TextureReleaseProc release_proc, + SkSurface::ReleaseContext release_context) { + GrMtlTextureInfo info; + info.fTexture.retain((__bridge GrMTLHandle)texture); + GrBackendTexture backend_texture = + GrBackendTextures::MakeMtl(texture.width, texture.height, skgpu::Mipmapped::kNo, info); + return SkSurfaces::WrapBackendTexture(context, backend_texture, origin, 1, color_type, + std::move(color_space), props, release_proc, + release_context); +} +} // namespace + +GPUSurfaceMetalSkia::GPUSurfaceMetalSkia(GPUSurfaceMetalDelegate* delegate, + sk_sp context, + bool render_to_surface) + : delegate_(delegate), + render_target_type_(delegate->GetRenderTargetType()), + context_(std::move(context)), + render_to_surface_(render_to_surface) { + // If this preference is explicitly set, we allow for disabling partial repaint. + NSNumber* disablePartialRepaint = + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTDisablePartialRepaint"]; + if (disablePartialRepaint != nil) { + disable_partial_repaint_ = disablePartialRepaint.boolValue; + } +} + +GPUSurfaceMetalSkia::~GPUSurfaceMetalSkia() = default; + +// |Surface| +bool GPUSurfaceMetalSkia::IsValid() { + return context_ != nullptr; +} + +void GPUSurfaceMetalSkia::PrecompileKnownSkSLsIfNecessary() { + auto* current_context = GetContext(); + if (current_context == precompiled_sksl_context_) { + // Known SkSLs have already been prepared in this context. + return; + } + precompiled_sksl_context_ = current_context; + flutter::PersistentCache::GetCacheForProcess()->PrecompileKnownSkSLs(precompiled_sksl_context_); +} + +// |Surface| +std::unique_ptr GPUSurfaceMetalSkia::AcquireFrame(const SkISize& frame_size) { + if (!IsValid()) { + FML_LOG(ERROR) << "Metal surface was invalid."; + return nullptr; + } + + if (frame_size.isEmpty()) { + FML_LOG(ERROR) << "Metal surface was asked for an empty frame."; + return nullptr; + } + + if (!render_to_surface_) { + return std::make_unique( + nullptr, // + SurfaceFrame::FramebufferInfo(), // + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { return true; }, // + [](const SurfaceFrame& surface_frame) { return true; }, // + frame_size // + ); + } + + PrecompileKnownSkSLsIfNecessary(); + + switch (render_target_type_) { + case MTLRenderTargetType::kCAMetalLayer: + return AcquireFrameFromCAMetalLayer(frame_size); + case MTLRenderTargetType::kMTLTexture: + return AcquireFrameFromMTLTexture(frame_size); + default: + FML_CHECK(false) << "Unknown MTLRenderTargetType type."; + } + + return nullptr; +} + +std::unique_ptr GPUSurfaceMetalSkia::AcquireFrameFromCAMetalLayer( + const SkISize& frame_info) { + CAMetalLayer* layer = (__bridge CAMetalLayer*)delegate_->GetCAMetalLayer(frame_info); + if (!layer) { + FML_LOG(ERROR) << "Invalid CAMetalLayer given by the embedder."; + return nullptr; + } + + // Get the drawable eagerly, we will need texture object to identify target framebuffer + id drawable = [layer nextDrawable]; + if (!drawable) { + FML_LOG(ERROR) << "Could not obtain drawable from the metal layer."; + return nullptr; + } + + auto surface = CreateSurfaceFromMetalTexture(context_.get(), drawable.texture, + kTopLeft_GrSurfaceOrigin, // origin + kBGRA_8888_SkColorType, // color type + nullptr, // colorspace + nullptr, // surface properties + nullptr, // release proc + nullptr // release context + ); + + if (!surface) { + FML_LOG(ERROR) << "Could not create the SkSurface from the CAMetalLayer."; + return nullptr; + } + + // drawable is a local and needs to be strongly-captured. + SurfaceFrame::EncodeCallback encode_callback = + [this, drawable, layer](const SurfaceFrame& surface_frame, DlCanvas* canvas) -> bool { + layer.presentsWithTransaction = surface_frame.submit_info().present_with_transaction; + if (canvas == nullptr) { + FML_DLOG(ERROR) << "Canvas not available."; + return false; + } + + { + TRACE_EVENT0("flutter", "SkCanvas::Flush"); + canvas->Flush(); + } + + if (!disable_partial_repaint_) { + void* texture = (__bridge void*)drawable.texture; + for (auto& entry : damage_) { + if (entry.first != texture) { + // Accumulate damage for other framebuffers + if (surface_frame.submit_info().frame_damage) { + entry.second.join(*surface_frame.submit_info().frame_damage); + } + } + } + // Reset accumulated damage for current framebuffer + damage_[texture] = SkIRect::MakeEmpty(); + } + + return true; + }; + + // drawable is a local and needs to be strongly-captured. + SurfaceFrame::SubmitCallback submit_callback = + [this, drawable](const SurfaceFrame& surface_frame) -> bool { + TRACE_EVENT0("flutter", "GPUSurfaceMetal::Submit"); + return delegate_->PresentDrawable((__bridge GrMTLHandle)drawable); + }; + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + if (!disable_partial_repaint_) { + // Provide accumulated damage to rasterizer (area in current framebuffer that lags behind + // front buffer) + void* texture = (__bridge void*)drawable.texture; + auto i = damage_.find(texture); + if (i != damage_.end()) { + framebuffer_info.existing_damage = i->second; + } + framebuffer_info.supports_partial_repaint = true; + } + + return std::make_unique(std::move(surface), framebuffer_info, encode_callback, + submit_callback, frame_info); +} + +std::unique_ptr GPUSurfaceMetalSkia::AcquireFrameFromMTLTexture( + const SkISize& frame_info) { + GPUMTLTextureInfo texture = delegate_->GetMTLTexture(frame_info); + id mtl_texture = (__bridge id)texture.texture; + + if (!mtl_texture) { + FML_LOG(ERROR) << "Invalid MTLTexture given by the embedder."; + return nullptr; + } + + sk_sp surface = CreateSurfaceFromMetalTexture( + context_.get(), mtl_texture, kTopLeft_GrSurfaceOrigin, kBGRA_8888_SkColorType, nullptr, + nullptr, static_cast(texture.destruction_callback), + texture.destruction_context); + + if (!surface) { + FML_LOG(ERROR) << "Could not create the SkSurface from the metal texture."; + return nullptr; + } + + auto encode_callback = [](const SurfaceFrame& surface_frame, DlCanvas* canvas) -> bool { + if (canvas == nullptr) { + FML_DLOG(ERROR) << "Canvas not available."; + return false; + } + + { + TRACE_EVENT0("flutter", "SkCanvas::Flush"); + canvas->Flush(); + } + + return true; + }; + auto submit_callback = [texture = texture, + delegate = delegate_](const SurfaceFrame& surface_frame) { + TRACE_EVENT0("flutter", "GPUSurfaceMetal::PresentTexture"); + return delegate->PresentTexture(texture); + }; + + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + return std::make_unique(std::move(surface), framebuffer_info, encode_callback, + submit_callback, frame_info); +} + +// |Surface| +SkMatrix GPUSurfaceMetalSkia::GetRootTransformation() const { + // This backend does not currently support root surface transformations. Just + // return identity. + return {}; +} + +// |Surface| +GrDirectContext* GPUSurfaceMetalSkia::GetContext() { + return context_.get(); +} + +// |Surface| +std::unique_ptr GPUSurfaceMetalSkia::MakeRenderContextCurrent() { + // A context may either be necessary to render to the surface or to snapshot an offscreen + // surface. Either way, SkSL precompilation must be attempted. + PrecompileKnownSkSLsIfNecessary(); + + // This backend has no such concept. + return std::make_unique(true); +} + +bool GPUSurfaceMetalSkia::AllowsDrawingWhenGpuDisabled() const { + return delegate_->AllowsDrawingWhenGpuDisabled(); +} + +} // namespace flutter + +#endif // !SLIMPELLER diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_noop.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_noop.h new file mode 100644 index 0000000000000000000000000000000000000000..e1a5498ee480cae0db3abfe6167c0a6511f998e5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_noop.h @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_NOOP_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_NOOP_H_ + +#include + +#include "flutter/flow/surface.h" + +namespace flutter { + +/// @brief A rendering surface that accepts rendering intent but does not render +/// anything. +/// +/// This is useful for running on platforms that need an engine instance and +/// don't have the required drivers. +class GPUSurfaceNoop : public Surface { + public: + explicit GPUSurfaceNoop(); + + // |Surface| + ~GPUSurfaceNoop(); + + // |Surface| + bool IsValid() override; + + // |Surface| + Surface::SurfaceData GetSurfaceData() const override; + + private: + // |Surface| + std::unique_ptr AcquireFrame( + const SkISize& frame_size) override; + + std::unique_ptr AcquireFrameFromCAMetalLayer( + const SkISize& frame_size); + + std::unique_ptr AcquireFrameFromMTLTexture( + const SkISize& frame_size); + + // |Surface| + SkMatrix GetRootTransformation() const override; + + // |Surface| + GrDirectContext* GetContext() override; + + // |Surface| + std::unique_ptr MakeRenderContextCurrent() override; + + // |Surface| + bool AllowsDrawingWhenGpuDisabled() const override; + + // |Surface| + bool EnableRasterCache() const override; + + // |Surface| + std::shared_ptr GetAiksContext() const override; + + GPUSurfaceNoop(const GPUSurfaceNoop&) = delete; + + GPUSurfaceNoop& operator=(const GPUSurfaceNoop&) = delete; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_NOOP_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_noop.mm b/flutter/engine/src/flutter/shell/gpu/gpu_surface_noop.mm new file mode 100644 index 0000000000000000000000000000000000000000..1b40d51eec8581dbda1f10498a3f25404a955d11 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_noop.mm @@ -0,0 +1,97 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_noop.h" + +#import +#import + +#include "flow/surface.h" +#include "flow/surface_frame.h" +#include "flutter/common/settings.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/trace_event.h" + +static_assert(__has_feature(objc_arc), "ARC must be enabled."); + +namespace flutter { + +GPUSurfaceNoop::GPUSurfaceNoop() = default; + +GPUSurfaceNoop::~GPUSurfaceNoop() = default; + +// |Surface| +bool GPUSurfaceNoop::IsValid() { + return true; +} + +Surface::SurfaceData GPUSurfaceNoop::GetSurfaceData() const { + return Surface::SurfaceData{}; +} + +// |Surface| +std::unique_ptr GPUSurfaceNoop::AcquireFrame(const SkISize& frame_size) { + auto callback = [](const SurfaceFrame&, DlCanvas*) { return true; }; + auto submit_callback = [](const SurfaceFrame&) { return true; }; + SurfaceFrame::FramebufferInfo framebuffer_info; + + return std::make_unique( + /*surface=*/nullptr, + /*framebuffer_info=*/framebuffer_info, + /*encode_callback=*/callback, + /*submit_callback=*/submit_callback, + /*frame_size=*/frame_size, + /*context_result=*/nullptr, + /*display_list_fallback=*/true); +} + +std::unique_ptr GPUSurfaceNoop::AcquireFrameFromMTLTexture( + const SkISize& frame_size) { + auto callback = [](const SurfaceFrame&, DlCanvas*) { return true; }; + auto submit_callback = [](const SurfaceFrame&) { return true; }; + SurfaceFrame::FramebufferInfo framebuffer_info; + + return std::make_unique( + /*surface=*/nullptr, + /*framebuffer_info=*/framebuffer_info, + /*encode_callback=*/callback, + /*submit_callback=*/submit_callback, + /*frame_size=*/frame_size, + /*context_result=*/nullptr, + /*display_list_fallback=*/true); +} + +// |Surface| +SkMatrix GPUSurfaceNoop::GetRootTransformation() const { + // This backend does not currently support root surface transformations. Just + // return identity. + return {}; +} + +// |Surface| +GrDirectContext* GPUSurfaceNoop::GetContext() { + return nullptr; +} + +// |Surface| +std::unique_ptr GPUSurfaceNoop::MakeRenderContextCurrent() { + // This backend has no such concept. + return std::make_unique(true); +} + +bool GPUSurfaceNoop::AllowsDrawingWhenGpuDisabled() const { + return true; +} + +// |Surface| +bool GPUSurfaceNoop::EnableRasterCache() const { + return false; +} + +// |Surface| +std::shared_ptr GPUSurfaceNoop::GetAiksContext() const { + return nullptr; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_noop_unittests.mm b/flutter/engine/src/flutter/shell/gpu/gpu_surface_noop_unittests.mm new file mode 100644 index 0000000000000000000000000000000000000000..ec462a400cb36ba85e0e0910bf1de44c0f3495c0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_noop_unittests.mm @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "flutter/shell/gpu/gpu_surface_noop.h" +#include "gtest/gtest.h" +#include "impeller/entity/mtl/entity_shaders.h" +#include "impeller/entity/mtl/framebuffer_blend_shaders.h" +#include "impeller/entity/mtl/modern_shaders.h" +#include "impeller/renderer/backend/metal/context_mtl.h" + +namespace flutter { +namespace testing { + +TEST(GPUSurfaceNoop, InvalidImpellerContextCreatesCausesSurfaceToBeInvalid) { + auto surface = std::make_shared(); + + EXPECT_TRUE(surface->IsValid()); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_software.cc b/flutter/engine/src/flutter/shell/gpu/gpu_surface_software.cc new file mode 100644 index 0000000000000000000000000000000000000000..8a2998d180996e7654614ac4de01376d0d82716d --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_software.cc @@ -0,0 +1,109 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_software.h" + +#include + +#include "flow/surface_frame.h" +#include "flutter/fml/logging.h" + +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { + +GPUSurfaceSoftware::GPUSurfaceSoftware(GPUSurfaceSoftwareDelegate* delegate, + bool render_to_surface) + : delegate_(delegate), + render_to_surface_(render_to_surface), + weak_factory_(this) {} + +GPUSurfaceSoftware::~GPUSurfaceSoftware() = default; + +// |Surface| +bool GPUSurfaceSoftware::IsValid() { + return delegate_ != nullptr; +} + +// |Surface| +std::unique_ptr GPUSurfaceSoftware::AcquireFrame( + const SkISize& logical_size) { + SurfaceFrame::FramebufferInfo framebuffer_info; + framebuffer_info.supports_readback = true; + + // TODO(38466): Refactor GPU surface APIs take into account the fact that an + // external view embedder may want to render to the root surface. + if (!render_to_surface_) { + return std::make_unique( + nullptr, framebuffer_info, + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, logical_size); + } + + if (!IsValid()) { + return nullptr; + } + + const auto size = SkISize::Make(logical_size.width(), logical_size.height()); + + sk_sp backing_store = delegate_->AcquireBackingStore(size); + + if (backing_store == nullptr) { + return nullptr; + } + + if (size != SkISize::Make(backing_store->width(), backing_store->height())) { + return nullptr; + } + + // If the surface has been scaled, we need to apply the inverse scaling to the + // underlying canvas so that coordinates are mapped to the same spot + // irrespective of surface scaling. + SkCanvas* canvas = backing_store->getCanvas(); + canvas->resetMatrix(); + + SurfaceFrame::EncodeCallback encode_callback = + [self = weak_factory_.GetWeakPtr()](const SurfaceFrame& surface_frame, + DlCanvas* canvas) -> bool { + // If the surface itself went away, there is nothing more to do. + if (!self || !self->IsValid() || canvas == nullptr) { + return false; + } + + canvas->Flush(); + return true; + }; + SurfaceFrame::SubmitCallback submit_callback = + [self = weak_factory_.GetWeakPtr()](const SurfaceFrame& surface_frame) { + // If the surface itself went away, there is nothing more to do. + if (!self || !self->IsValid()) { + return false; + } + return self->delegate_->PresentBackingStore( + surface_frame.SkiaSurface()); + }; + + return std::make_unique(backing_store, framebuffer_info, + encode_callback, submit_callback, + logical_size); +} + +// |Surface| +SkMatrix GPUSurfaceSoftware::GetRootTransformation() const { + // This backend does not currently support root surface transformations. Just + // return identity. + SkMatrix matrix; + matrix.reset(); + return matrix; +} + +// |Surface| +GrDirectContext* GPUSurfaceSoftware::GetContext() { + // There is no GrContext associated with a software surface. + return nullptr; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_software.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_software.h new file mode 100644 index 0000000000000000000000000000000000000000..18bc8d5b4144644e6602c271543745731d2e840d --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_software.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_SOFTWARE_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_SOFTWARE_H_ + +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/shell/gpu/gpu_surface_software_delegate.h" + +namespace flutter { + +class GPUSurfaceSoftware : public Surface { + public: + GPUSurfaceSoftware(GPUSurfaceSoftwareDelegate* delegate, + bool render_to_surface); + + ~GPUSurfaceSoftware() override; + + // |Surface| + bool IsValid() override; + + // |Surface| + std::unique_ptr AcquireFrame(const SkISize& size) override; + + // |Surface| + SkMatrix GetRootTransformation() const override; + + // |Surface| + GrDirectContext* GetContext() override; + + private: + GPUSurfaceSoftwareDelegate* delegate_; + // TODO(38466): Refactor GPU surface APIs take into account the fact that an + // external view embedder may want to render to the root surface. This is a + // hack to make avoid allocating resources for the root surface when an + // external view embedder is present. + const bool render_to_surface_; + fml::TaskRunnerAffineWeakPtrFactory weak_factory_; + FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceSoftware); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_SOFTWARE_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_software_delegate.cc b/flutter/engine/src/flutter/shell/gpu/gpu_surface_software_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..9bc6d8b98fea7adb7774c3582b45c24e665db54c --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_software_delegate.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_software_delegate.h" + +namespace flutter { + +GPUSurfaceSoftwareDelegate::~GPUSurfaceSoftwareDelegate() = default; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_software_delegate.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_software_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..e46f4ec0f1f13d2a0493cd8b1c36ca5218b8915e --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_software_delegate.h @@ -0,0 +1,55 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_SOFTWARE_DELEGATE_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_SOFTWARE_DELEGATE_H_ + +#include "flutter/flow/embedded_views.h" +#include "flutter/fml/macros.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Interface implemented by all platform surfaces that can present +/// a software backing store to the "screen". The GPU surface +/// abstraction (which abstracts the client rendering API) uses this +/// delegation pattern to tell the platform surface (which abstracts +/// how backing stores fulfilled by the selected client rendering +/// API end up on the "screen" on a particular platform) when the +/// rasterizer needs to allocate and present the software backing +/// store. +/// +/// @see |IOSSurfaceSoftware|, |AndroidSurfaceSoftware|, +/// |EmbedderSurfaceSoftware|. +/// +class GPUSurfaceSoftwareDelegate { + public: + ~GPUSurfaceSoftwareDelegate(); + + //---------------------------------------------------------------------------- + /// @brief Called when the GPU surface needs a new buffer to render a new + /// frame into. + /// + /// @param[in] size The size of the frame. + /// + /// @return A raster surface returned by the platform. + /// + virtual sk_sp AcquireBackingStore(const SkISize& size) = 0; + + //---------------------------------------------------------------------------- + /// @brief Called by the platform when a frame has been rendered into the + /// backing store and the platform must display it on-screen. + /// + /// @param[in] backing_store The software backing store to present. + /// + /// @return Returns if the platform could present the backing store onto + /// the screen. + /// + virtual bool PresentBackingStore(sk_sp backing_store) = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_SOFTWARE_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan.cc b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan.cc new file mode 100644 index 0000000000000000000000000000000000000000..9207bfa50688364b2d5bfa7b99421ad18ccecb95 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan.cc @@ -0,0 +1,156 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_vulkan.h" + +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" + +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" +#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/vk/GrVkTypes.h" +#include "vulkan/vulkan_core.h" + +namespace flutter { + +GPUSurfaceVulkan::GPUSurfaceVulkan(GPUSurfaceVulkanDelegate* delegate, + const sk_sp& skia_context, + bool render_to_surface) + : delegate_(delegate), + skia_context_(skia_context), + render_to_surface_(render_to_surface), + weak_factory_(this) {} + +GPUSurfaceVulkan::~GPUSurfaceVulkan() = default; + +bool GPUSurfaceVulkan::IsValid() { + return skia_context_ != nullptr; +} + +std::unique_ptr GPUSurfaceVulkan::AcquireFrame( + const SkISize& frame_size) { + if (!IsValid()) { + FML_LOG(ERROR) << "Vulkan surface was invalid."; + return nullptr; + } + + if (frame_size.isEmpty()) { + FML_LOG(ERROR) << "Vulkan surface was asked for an empty frame."; + return nullptr; + } + + if (!render_to_surface_) { + return std::make_unique( + nullptr, SurfaceFrame::FramebufferInfo(), + [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { + return true; + }, + [](const SurfaceFrame& surface_frame) { return true; }, frame_size); + } + + FlutterVulkanImage image = delegate_->AcquireImage(frame_size); + if (!image.image) { + FML_LOG(ERROR) << "Invalid VkImage given by the embedder."; + return nullptr; + } + + sk_sp surface = CreateSurfaceFromVulkanImage( + reinterpret_cast(image.image), + static_cast(image.format), frame_size); + if (!surface) { + FML_LOG(ERROR) << "Could not create the SkSurface from the Vulkan image."; + return nullptr; + } + + SurfaceFrame::EncodeCallback encode_callback = [](const SurfaceFrame&, + DlCanvas* canvas) -> bool { + if (canvas == nullptr) { + FML_DLOG(ERROR) << "Canvas not available."; + return false; + } + canvas->Flush(); + return true; + }; + + SurfaceFrame::SubmitCallback submit_callback = + [image = image, delegate = delegate_](const SurfaceFrame&) -> bool { + TRACE_EVENT0("flutter", "GPUSurfaceVulkan::PresentImage"); + return delegate->PresentImage(reinterpret_cast(image.image), + static_cast(image.format)); + }; + + SurfaceFrame::FramebufferInfo framebuffer_info{.supports_readback = true}; + + return std::make_unique(std::move(surface), framebuffer_info, + std::move(encode_callback), + std::move(submit_callback), frame_size); +} + +SkMatrix GPUSurfaceVulkan::GetRootTransformation() const { + // This backend does not support delegating to the underlying platform to + // query for root surface transformations. Just return identity. + SkMatrix matrix; + matrix.reset(); + return matrix; +} + +GrDirectContext* GPUSurfaceVulkan::GetContext() { + return skia_context_.get(); +} + +sk_sp GPUSurfaceVulkan::CreateSurfaceFromVulkanImage( + const VkImage image, + const VkFormat format, + const SkISize& size) { +#ifdef SK_VULKAN + GrVkImageInfo image_info = { + .fImage = image, + .fImageTiling = VK_IMAGE_TILING_OPTIMAL, + .fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .fFormat = format, + .fImageUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT | + VK_IMAGE_USAGE_SAMPLED_BIT, + .fSampleCount = 1, + .fLevelCount = 1, + }; + auto backend_texture = + GrBackendTextures::MakeVk(size.width(), size.height(), image_info); + + SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry); + + return SkSurfaces::WrapBackendTexture( + skia_context_.get(), // context + backend_texture, // back-end texture + kTopLeft_GrSurfaceOrigin, // surface origin + 1, // sample count + ColorTypeFromFormat(format), // color type + SkColorSpace::MakeSRGB(), // color space + &surface_properties // surface properties + ); +#else + return nullptr; +#endif // SK_VULKAN +} + +SkColorType GPUSurfaceVulkan::ColorTypeFromFormat(const VkFormat format) { + switch (format) { + case VK_FORMAT_R8G8B8A8_UNORM: + case VK_FORMAT_R8G8B8A8_SRGB: + return SkColorType::kRGBA_8888_SkColorType; + case VK_FORMAT_B8G8R8A8_UNORM: + case VK_FORMAT_B8G8R8A8_SRGB: + return SkColorType::kBGRA_8888_SkColorType; + default: + return SkColorType::kUnknown_SkColorType; + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan.h new file mode 100644 index 0000000000000000000000000000000000000000..69da9500393d15048d25b9c5d93ab1dbc23567ea --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan.h @@ -0,0 +1,69 @@ +// 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_GPU_GPU_SURFACE_VULKAN_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_H_ + +#include + +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/shell/gpu/gpu_surface_vulkan_delegate.h" +#include "flutter/vulkan/vulkan_backbuffer.h" +#include "flutter/vulkan/vulkan_native_surface.h" +#include "flutter/vulkan/vulkan_window.h" + +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief A GPU surface backed by VkImages provided by a +/// GPUSurfaceVulkanDelegate. +/// +class GPUSurfaceVulkan : public Surface { + public: + //------------------------------------------------------------------------------ + /// @brief Create a GPUSurfaceVulkan while letting it reuse an existing + /// GrDirectContext. + /// + GPUSurfaceVulkan(GPUSurfaceVulkanDelegate* delegate, + const sk_sp& context, + bool render_to_surface); + + ~GPUSurfaceVulkan() override; + + // |Surface| + bool IsValid() override; + + // |Surface| + std::unique_ptr AcquireFrame(const SkISize& size) override; + + // |Surface| + SkMatrix GetRootTransformation() const override; + + // |Surface| + GrDirectContext* GetContext() override; + + static SkColorType ColorTypeFromFormat(const VkFormat format); + + private: + GPUSurfaceVulkanDelegate* delegate_; + sk_sp skia_context_; + bool render_to_surface_; + + fml::WeakPtrFactory weak_factory_; + + sk_sp CreateSurfaceFromVulkanImage(const VkImage image, + const VkFormat format, + const SkISize& size); + + FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceVulkan); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_delegate.cc b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..3e64ad702279c67d3fbbf620644ac06cb1ffceb9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_delegate.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_vulkan_delegate.h" + +namespace flutter { + +GPUSurfaceVulkanDelegate::~GPUSurfaceVulkanDelegate() = default; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_delegate.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..2a95f0a613b51db87eb67fa1648d055bcb04d275 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_delegate.h @@ -0,0 +1,50 @@ +// 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_GPU_GPU_SURFACE_VULKAN_DELEGATE_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_DELEGATE_H_ + +#include "flutter/fml/memory/ref_ptr.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/vulkan/procs/vulkan_proc_table.h" +#include "flutter/vulkan/vulkan_device.h" +#include "flutter/vulkan/vulkan_image.h" +#include "third_party/skia/include/core/SkSize.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Interface implemented by all platform surfaces that can present +/// a Vulkan backing store to the "screen". The GPU surface +/// abstraction (which abstracts the client rendering API) uses this +/// delegation pattern to tell the platform surface (which abstracts +/// how backing stores fulfilled by the selected client rendering +/// API end up on the "screen" on a particular platform) when the +/// rasterizer needs to allocate and present the Vulkan backing +/// store. +/// +/// @see |EmbedderSurfaceVulkan|. +/// +class GPUSurfaceVulkanDelegate { + public: + virtual ~GPUSurfaceVulkanDelegate(); + + /// @brief Obtain a reference to the Vulkan implementation's proc table. + /// + virtual const vulkan::VulkanProcTable& vk() = 0; + + /// @brief Called by the engine to fetch a VkImage for writing the next + /// frame. + /// + virtual FlutterVulkanImage AcquireImage(const SkISize& size) = 0; + + /// @brief Called by the engine once a frame has been rendered to the image + /// and it's ready to be bound for further reading/writing. + /// + virtual bool PresentImage(VkImage image, VkFormat format) = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.cc b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..0685018e3a01d1be5aedf2ff8e08fba2cf3b975b --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.cc @@ -0,0 +1,310 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/gpu/gpu_surface_vulkan_impeller.h" + +#include + +#include "flow/surface_frame.h" +#include "flutter/fml/make_copyable.h" +#include "fml/trace_event.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/display_list/dl_dispatcher.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/surface_context_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/surface_vk.h" +#include "impeller/renderer/render_target.h" +#include "impeller/renderer/surface.h" +#include "impeller/typographer/backends/skia/typographer_context_skia.h" + +namespace flutter { + +class WrappedTextureSourceVK : public impeller::TextureSourceVK { + public: + explicit WrappedTextureSourceVK(impeller::vk::Image image, + impeller::vk::ImageView image_view, + impeller::TextureDescriptor desc) + : TextureSourceVK(desc), image_(image), image_view_(image_view) {} + + ~WrappedTextureSourceVK() {} + + private: + impeller::vk::Image GetImage() const override { return image_; } + + impeller::vk::ImageView GetImageView() const override { return image_view_; } + + impeller::vk::ImageView GetRenderTargetView() const override { + return image_view_; + } + + bool IsSwapchainImage() const override { return true; } + + impeller::vk::Image image_; + impeller::vk::ImageView image_view_; +}; + +GPUSurfaceVulkanImpeller::GPUSurfaceVulkanImpeller( + GPUSurfaceVulkanDelegate* delegate, + std::shared_ptr context) + : delegate_(delegate) { + if (!context || !context->IsValid()) { + return; + } + + auto aiks_context = std::make_shared( + context, impeller::TypographerContextSkia::Make()); + if (!aiks_context->IsValid()) { + return; + } + + impeller_context_ = std::move(context); + aiks_context_ = std::move(aiks_context); + is_valid_ = !!aiks_context_; +} + +// |Surface| +GPUSurfaceVulkanImpeller::~GPUSurfaceVulkanImpeller() = default; + +// |Surface| +bool GPUSurfaceVulkanImpeller::IsValid() { + return is_valid_; +} + +// |Surface| +std::unique_ptr GPUSurfaceVulkanImpeller::AcquireFrame( + const SkISize& size) { + if (!IsValid()) { + FML_LOG(ERROR) << "Vulkan surface was invalid."; + return nullptr; + } + + if (size.isEmpty()) { + FML_LOG(ERROR) << "Vulkan surface was asked for an empty frame."; + return nullptr; + } + + if (delegate_ == nullptr) { + auto& context_vk = impeller::SurfaceContextVK::Cast(*impeller_context_); + std::unique_ptr surface = + context_vk.AcquireNextSurface(); + + if (!surface) { + FML_LOG(ERROR) << "No surface available."; + return nullptr; + } + + impeller::RenderTarget render_target = surface->GetRenderTarget(); + auto cull_rect = render_target.GetRenderTargetSize(); + + SurfaceFrame::EncodeCallback encode_callback = [aiks_context = + aiks_context_, // + render_target, + cull_rect // + ](SurfaceFrame& surface_frame, DlCanvas* canvas) mutable -> bool { + if (!aiks_context) { + return false; + } + + auto display_list = surface_frame.BuildDisplayList(); + if (!display_list) { + FML_LOG(ERROR) << "Could not build display list for surface frame."; + return false; + } + + SkIRect sk_cull_rect = SkIRect::MakeWH(cull_rect.width, cull_rect.height); + return impeller::RenderToTarget( + aiks_context->GetContentContext(), // + render_target, // + display_list, // + sk_cull_rect, // + /*reset_host_buffer=*/surface_frame.submit_info().frame_boundary // + ); + }; + + return std::make_unique( + nullptr, // surface + SurfaceFrame::FramebufferInfo{}, // framebuffer info + encode_callback, // encode callback + fml::MakeCopyable([surface = std::move(surface)](const SurfaceFrame&) { + return surface->Present(); + }), // submit callback + size, // frame size + nullptr, // context result + true // display list fallback + ); + } else { + FlutterVulkanImage flutter_image = delegate_->AcquireImage(size); + if (!flutter_image.image) { + FML_LOG(ERROR) << "Invalid VkImage given by the embedder."; + return nullptr; + } + impeller::vk::Format vk_format = + static_cast(flutter_image.format); + std::optional format = + impeller::VkFormatToImpellerFormat(vk_format); + if (!format.has_value()) { + FML_LOG(ERROR) << "Unsupported pixel format: " + << impeller::vk::to_string(vk_format); + return nullptr; + } + + impeller::vk::Image vk_image = + impeller::vk::Image(reinterpret_cast(flutter_image.image)); + + impeller::TextureDescriptor desc; + desc.format = format.value(); + desc.size = impeller::ISize{size.width(), size.height()}; + desc.storage_mode = impeller::StorageMode::kDevicePrivate; + desc.mip_count = 1; + desc.compression_type = impeller::CompressionType::kLossless; + desc.usage = impeller::TextureUsage::kRenderTarget; + + impeller::ContextVK& context_vk = + impeller::ContextVK::Cast(*impeller_context_); + + impeller::vk::ImageViewCreateInfo view_info = {}; + view_info.viewType = impeller::vk::ImageViewType::e2D; + view_info.format = ToVKImageFormat(desc.format); + view_info.subresourceRange.aspectMask = + impeller::vk::ImageAspectFlagBits::eColor; + view_info.subresourceRange.baseMipLevel = 0u; + view_info.subresourceRange.baseArrayLayer = 0u; + view_info.subresourceRange.levelCount = 1; + view_info.subresourceRange.layerCount = 1; + view_info.image = vk_image; + + auto [result, image_view] = + context_vk.GetDevice().createImageView(view_info); + if (result != impeller::vk::Result::eSuccess) { + FML_LOG(ERROR) << "Failed to create image view for provided image: " + << impeller::vk::to_string(result); + return nullptr; + } + + if (transients_ == nullptr) { + transients_ = std::make_shared( + impeller_context_, desc, + /*enable_msaa=*/true); + } + + auto wrapped_onscreen = + std::make_shared(vk_image, image_view, desc); + auto surface = impeller::SurfaceVK::WrapSwapchainImage( + transients_, wrapped_onscreen, [&]() -> bool { return true; }); + impeller::RenderTarget render_target = surface->GetRenderTarget(); + auto cull_rect = render_target.GetRenderTargetSize(); + + SurfaceFrame::EncodeCallback encode_callback = [aiks_context = + aiks_context_, // + render_target, + cull_rect // + ](SurfaceFrame& surface_frame, DlCanvas* canvas) mutable -> bool { + if (!aiks_context) { + return false; + } + + auto display_list = surface_frame.BuildDisplayList(); + if (!display_list) { + FML_LOG(ERROR) << "Could not build display list for surface frame."; + return false; + } + + SkIRect sk_cull_rect = SkIRect::MakeWH(cull_rect.width, cull_rect.height); + return impeller::RenderToTarget(aiks_context->GetContentContext(), // + render_target, // + display_list, // + sk_cull_rect, // + /*reset_host_buffer=*/true // + ); + }; + + SurfaceFrame::SubmitCallback submit_callback = + [image = flutter_image, delegate = delegate_, + impeller_context = impeller_context_, + wrapped_onscreen](const SurfaceFrame&) -> bool { + TRACE_EVENT0("flutter", "GPUSurfaceVulkan::PresentImage"); + + { + const auto& context = impeller::ContextVK::Cast(*impeller_context); + + //---------------------------------------------------------------------------- + /// Transition the image to color-attachment-optimal. + /// + auto cmd_buffer = context.CreateCommandBuffer(); + + auto vk_final_cmd_buffer = + impeller::CommandBufferVK::Cast(*cmd_buffer).GetCommandBuffer(); + { + impeller::BarrierVK barrier; + barrier.new_layout = + impeller::vk::ImageLayout::eColorAttachmentOptimal; + barrier.cmd_buffer = vk_final_cmd_buffer; + barrier.src_access = + impeller::vk::AccessFlagBits::eColorAttachmentWrite; + barrier.src_stage = + impeller::vk::PipelineStageFlagBits::eColorAttachmentOutput; + barrier.dst_access = {}; + barrier.dst_stage = + impeller::vk::PipelineStageFlagBits::eBottomOfPipe; + + if (!wrapped_onscreen->SetLayout(barrier).ok()) { + return false; + } + } + if (!context.GetCommandQueue()->Submit({cmd_buffer}).ok()) { + return false; + } + } + + return delegate->PresentImage(reinterpret_cast(image.image), + static_cast(image.format)); + }; + + SurfaceFrame::FramebufferInfo framebuffer_info{.supports_readback = true}; + + return std::make_unique(nullptr, // surface + framebuffer_info, // framebuffer info + encode_callback, // encode callback + submit_callback, + size, // frame size + nullptr, // context result + true // display list fallback + ); + } +} + +// |Surface| +SkMatrix GPUSurfaceVulkanImpeller::GetRootTransformation() const { + // This backend does not currently support root surface transformations. Just + // return identity. + return {}; +} + +// |Surface| +GrDirectContext* GPUSurfaceVulkanImpeller::GetContext() { + // Impeller != Skia. + return nullptr; +} + +// |Surface| +std::unique_ptr +GPUSurfaceVulkanImpeller::MakeRenderContextCurrent() { + // This backend has no such concept. + return std::make_unique(true); +} + +// |Surface| +bool GPUSurfaceVulkanImpeller::EnableRasterCache() const { + return false; +} + +// |Surface| +std::shared_ptr +GPUSurfaceVulkanImpeller::GetAiksContext() const { + return aiks_context_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.h b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..602761db0cfceb90dd8ce0759058738a4f85ac29 --- /dev/null +++ b/flutter/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.h @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_IMPELLER_H_ +#define FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_IMPELLER_H_ + +#include "flutter/common/graphics/gl_context_switch.h" +#include "flutter/flow/surface.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/weak_ptr.h" +#include "flutter/impeller/display_list/aiks_context.h" +#include "flutter/impeller/renderer/context.h" +#include "flutter/shell/gpu/gpu_surface_vulkan_delegate.h" +#include "impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.h" + +namespace flutter { + +class GPUSurfaceVulkanImpeller final : public Surface { + public: + explicit GPUSurfaceVulkanImpeller(GPUSurfaceVulkanDelegate* delegate, + std::shared_ptr context); + + // |Surface| + ~GPUSurfaceVulkanImpeller() override; + + // |Surface| + bool IsValid() override; + + private: + GPUSurfaceVulkanDelegate* delegate_; + std::shared_ptr impeller_context_; + std::shared_ptr aiks_context_; + std::shared_ptr transients_; + bool is_valid_ = false; + + // |Surface| + std::unique_ptr AcquireFrame(const SkISize& size) override; + + // |Surface| + SkMatrix GetRootTransformation() const override; + + // |Surface| + GrDirectContext* GetContext() override; + + // |Surface| + std::unique_ptr MakeRenderContextCurrent() override; + + // |Surface| + bool EnableRasterCache() const override; + + // |Surface| + std::shared_ptr GetAiksContext() const override; + + FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceVulkanImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/BUILD.gn b/flutter/engine/src/flutter/shell/platform/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..63e9901643614de3de5711d7adbad33d5e3e2d9d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/BUILD.gn @@ -0,0 +1,28 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/shell/platform/config.gni") + +group("platform") { + if (is_mac || is_ios) { + deps = [ "darwin" ] + } else if (is_android) { + deps = [ "android" ] + } else if (is_linux) { + deps = [] + if (enable_desktop_embeddings) { + deps += [ "linux" ] + } + } else if (is_win) { + deps = [] + if (enable_desktop_embeddings) { + deps += [ "windows" ] + } + } else if (is_fuchsia) { + import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") + deps = [ "fuchsia" ] + } else { + assert(false, "Unknown/Unsupported platform.") + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/AndroidManifest.xml b/flutter/engine/src/flutter/shell/platform/android/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..1f8e23631865bb9767f4de8a7301ee201df6f03f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/AndroidManifest.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + diff --git a/flutter/engine/src/flutter/shell/platform/android/BUILD.gn b/flutter/engine/src/flutter/shell/platform/android/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..59a7609b59ed33e4568cb947726e28569ddb19a1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/BUILD.gn @@ -0,0 +1,848 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/android/config.gni") +import("//build/toolchain/clang.gni") +import("//flutter/build/bin_to_obj.gni") +import("//flutter/build/zip_bundle.gni") +import("//flutter/common/config.gni") +import("//flutter/impeller/tools/impeller.gni") +import("//flutter/lib/snapshot/gen_snapshot.gni") +import("//flutter/shell/config.gni") +import("//flutter/shell/gpu/gpu.gni") +import("//flutter/shell/version/version.gni") +import("//flutter/vulkan/config.gni") + +shell_gpu_configuration("android_gpu_configuration") { + enable_software = true + enable_gl = true + enable_vulkan = true + enable_metal = false +} + +source_set("image_generator") { + sources = [ + "android_image_generator.cc", + "android_image_generator.h", + ] + + deps = [ + "//flutter/fml", + "//flutter/lib/ui:ui", + "//flutter/skia", + ] + + libs = [ + "android", + "jnigraphics", + ] +} + +executable("flutter_shell_native_unittests") { + visibility = [ "*" ] + testonly = true + sources = [ + "android_context_gl_impeller_unittests.cc", + "android_context_gl_unittests.cc", + "android_shell_holder_unittests.cc", + "apk_asset_provider_unittests.cc", + "flutter_shell_native_unittests.cc", + "image_lru_unittests.cc", + "platform_view_android_unittests.cc", + ] + public_configs = [ "//flutter:config" ] + deps = [ + ":flutter_shell_native_src", + "//flutter/fml", + "//flutter/shell/platform/android/jni:jni_mock", + "//flutter/third_party/googletest:gmock", + "//flutter/third_party/googletest:gtest", + ] +} + +shared_library("flutter_shell_native") { + inputs = [ "android_exports.lst" ] + output_name = "flutter" + deps = [ ":flutter_shell_native_src" ] + ldflags = [ "-Wl,--version-script=" + + rebase_path("android_exports.lst", root_build_dir) ] +} + +bin_to_assembly("icudtl_asm") { + deps = [] + input = "//flutter/third_party/icu/flutter/icudtl.dat" + symbol = "_binary_icudtl_dat_start" + size_symbol = "_binary_icudtl_dat_size" + executable = false +} + +source_set("flutter_shell_native_src") { + visibility = [ ":*" ] + + sources = [ + "android_context_gl_impeller.cc", + "android_context_gl_impeller.h", + "android_context_gl_skia.cc", + "android_context_gl_skia.h", + "android_context_vk_impeller.cc", + "android_context_vk_impeller.h", + "android_display.cc", + "android_display.h", + "android_egl_surface.cc", + "android_egl_surface.h", + "android_environment_gl.cc", + "android_environment_gl.h", + "android_shell_holder.cc", + "android_shell_holder.h", + "android_surface_gl_impeller.cc", + "android_surface_gl_impeller.h", + "android_surface_gl_skia.cc", + "android_surface_gl_skia.h", + "android_surface_software.cc", + "android_surface_software.h", + "android_surface_vk_impeller.cc", + "android_surface_vk_impeller.h", + "apk_asset_provider.cc", + "apk_asset_provider.h", + "flutter_main.cc", + "flutter_main.h", + "image_external_texture.cc", + "image_external_texture.h", + "image_external_texture_gl.cc", + "image_external_texture_gl.h", + "image_external_texture_gl_impeller.cc", + "image_external_texture_gl_impeller.h", + "image_external_texture_gl_skia.cc", + "image_external_texture_gl_skia.h", + "image_external_texture_vk_impeller.cc", + "image_external_texture_vk_impeller.h", + "image_lru.cc", + "image_lru.h", + "library_loader.cc", + "platform_message_handler_android.cc", + "platform_message_handler_android.h", + "platform_message_response_android.cc", + "platform_message_response_android.h", + "platform_view_android.cc", + "platform_view_android.h", + "platform_view_android_jni_impl.cc", + "platform_view_android_jni_impl.h", + "surface_texture_external_texture.cc", + "surface_texture_external_texture.h", + "surface_texture_external_texture_gl_impeller.cc", + "surface_texture_external_texture_gl_impeller.h", + "surface_texture_external_texture_gl_skia.cc", + "surface_texture_external_texture_gl_skia.h", + "surface_texture_external_texture_vk_impeller.cc", + "surface_texture_external_texture_vk_impeller.h", + "vsync_waiter_android.cc", + "vsync_waiter_android.h", + ] + + sources += get_target_outputs(":icudtl_asm") + + public_deps = [ + ":android_gpu_configuration", + ":icudtl_asm", + ":image_generator", + "//flutter/assets", + "//flutter/common", + "//flutter/common/graphics", + "//flutter/flow", + "//flutter/fml", + "//flutter/impeller", + "//flutter/impeller/toolkit/android", + "//flutter/impeller/toolkit/egl", + "//flutter/impeller/toolkit/gles", + "//flutter/impeller/toolkit/glvk", + "//flutter/lib/ui", + "//flutter/runtime", + "//flutter/runtime:libdart", + "//flutter/shell/common", + "//flutter/shell/platform/android/context", + "//flutter/shell/platform/android/external_view_embedder", + "//flutter/shell/platform/android/jni", + "//flutter/shell/platform/android/platform_view_android_delegate", + "//flutter/shell/platform/android/surface", + "//flutter/shell/platform/android/surface:native_window", + "//flutter/skia", + "//flutter/txt", + "//flutter/vulkan", + ] + + public_configs = [ "//flutter:config" ] + + defines = [] + + libs = [ + "android", + "EGL", + "GLESv2", + ] +} + +action("gen_android_build_config_java") { + script = "//flutter/tools/gen_android_buildconfig.py" + + build_config_java = "$target_gen_dir/io/flutter/BuildConfig.java" + + outputs = [ build_config_java ] + + args = [ + "--out", + rebase_path(build_config_java), + "--runtime-mode", + flutter_runtime_mode, + ] +} + +embedding_artifact_id = "flutter_embedding_$flutter_runtime_mode" +embedding_jar_filename = "$embedding_artifact_id.jar" +embedding_jar_path = "$root_out_dir/$embedding_jar_filename" + +embedding_sources_jar_filename = "$embedding_artifact_id-sources.jar" +embedding_source_jar_path = "$root_out_dir/$embedding_sources_jar_filename" + +android_java_sources = [ + "io/flutter/Build.java", + "io/flutter/FlutterInjector.java", + "io/flutter/Log.java", + "io/flutter/app/FlutterApplication.java", + "io/flutter/embedding/android/AndroidTouchProcessor.java", + "io/flutter/embedding/android/ExclusiveAppComponent.java", + "io/flutter/embedding/android/FlutterActivity.java", + "io/flutter/embedding/android/FlutterActivityAndFragmentDelegate.java", + "io/flutter/embedding/android/FlutterActivityLaunchConfigs.java", + "io/flutter/embedding/android/FlutterEngineConfigurator.java", + "io/flutter/embedding/android/FlutterEngineProvider.java", + "io/flutter/embedding/android/FlutterFragment.java", + "io/flutter/embedding/android/FlutterFragmentActivity.java", + "io/flutter/embedding/android/FlutterImageView.java", + "io/flutter/embedding/android/FlutterPlayStoreSplitApplication.java", + "io/flutter/embedding/android/FlutterSurfaceView.java", + "io/flutter/embedding/android/FlutterTextureView.java", + "io/flutter/embedding/android/FlutterView.java", + "io/flutter/embedding/android/FlutterViewDelegate.java", + "io/flutter/embedding/android/KeyChannelResponder.java", + "io/flutter/embedding/android/KeyData.java", + "io/flutter/embedding/android/KeyEmbedderResponder.java", + "io/flutter/embedding/android/KeyboardManager.java", + "io/flutter/embedding/android/KeyboardMap.java", + "io/flutter/embedding/android/MotionEventTracker.java", + "io/flutter/embedding/android/RenderMode.java", + "io/flutter/embedding/android/TransparencyMode.java", + "io/flutter/embedding/android/WindowInfoRepositoryCallbackAdapterWrapper.java", + "io/flutter/embedding/engine/FlutterEngine.java", + "io/flutter/embedding/engine/FlutterEngineCache.java", + "io/flutter/embedding/engine/FlutterEngineConnectionRegistry.java", + "io/flutter/embedding/engine/FlutterEngineGroup.java", + "io/flutter/embedding/engine/FlutterEngineGroupCache.java", + "io/flutter/embedding/engine/FlutterJNI.java", + "io/flutter/embedding/engine/FlutterOverlaySurface.java", + "io/flutter/embedding/engine/FlutterShellArgs.java", + "io/flutter/embedding/engine/dart/DartExecutor.java", + "io/flutter/embedding/engine/dart/DartMessenger.java", + "io/flutter/embedding/engine/dart/PlatformMessageHandler.java", + "io/flutter/embedding/engine/dart/PlatformTaskQueue.java", + "io/flutter/embedding/engine/deferredcomponents/DeferredComponentManager.java", + "io/flutter/embedding/engine/deferredcomponents/PlayStoreDeferredComponentManager.java", + "io/flutter/embedding/engine/loader/ApplicationInfoLoader.java", + "io/flutter/embedding/engine/loader/FlutterApplicationInfo.java", + "io/flutter/embedding/engine/loader/FlutterLoader.java", + "io/flutter/embedding/engine/loader/ResourceExtractor.java", + "io/flutter/embedding/engine/mutatorsstack/FlutterMutatorView.java", + "io/flutter/embedding/engine/mutatorsstack/FlutterMutatorsStack.java", + "io/flutter/embedding/engine/plugins/FlutterPlugin.java", + "io/flutter/embedding/engine/plugins/PluginRegistry.java", + "io/flutter/embedding/engine/plugins/activity/ActivityAware.java", + "io/flutter/embedding/engine/plugins/activity/ActivityControlSurface.java", + "io/flutter/embedding/engine/plugins/activity/ActivityPluginBinding.java", + "io/flutter/embedding/engine/plugins/broadcastreceiver/BroadcastReceiverAware.java", + "io/flutter/embedding/engine/plugins/broadcastreceiver/BroadcastReceiverControlSurface.java", + "io/flutter/embedding/engine/plugins/broadcastreceiver/BroadcastReceiverPluginBinding.java", + "io/flutter/embedding/engine/plugins/contentprovider/ContentProviderAware.java", + "io/flutter/embedding/engine/plugins/contentprovider/ContentProviderControlSurface.java", + "io/flutter/embedding/engine/plugins/contentprovider/ContentProviderPluginBinding.java", + "io/flutter/embedding/engine/plugins/lifecycle/HiddenLifecycleReference.java", + "io/flutter/embedding/engine/plugins/service/ServiceAware.java", + "io/flutter/embedding/engine/plugins/service/ServiceControlSurface.java", + "io/flutter/embedding/engine/plugins/service/ServicePluginBinding.java", + "io/flutter/embedding/engine/plugins/util/GeneratedPluginRegister.java", + "io/flutter/embedding/engine/renderer/FlutterRenderer.java", + "io/flutter/embedding/engine/renderer/FlutterUiDisplayListener.java", + "io/flutter/embedding/engine/renderer/RenderSurface.java", + "io/flutter/embedding/engine/renderer/SurfaceTextureSurfaceProducer.java", + "io/flutter/embedding/engine/renderer/SurfaceTextureWrapper.java", + "io/flutter/embedding/engine/systemchannels/AccessibilityChannel.java", + "io/flutter/embedding/engine/systemchannels/BackGestureChannel.java", + "io/flutter/embedding/engine/systemchannels/DeferredComponentChannel.java", + "io/flutter/embedding/engine/systemchannels/KeyEventChannel.java", + "io/flutter/embedding/engine/systemchannels/KeyboardChannel.java", + "io/flutter/embedding/engine/systemchannels/LifecycleChannel.java", + "io/flutter/embedding/engine/systemchannels/LocalizationChannel.java", + "io/flutter/embedding/engine/systemchannels/MouseCursorChannel.java", + "io/flutter/embedding/engine/systemchannels/NavigationChannel.java", + "io/flutter/embedding/engine/systemchannels/PlatformChannel.java", + "io/flutter/embedding/engine/systemchannels/PlatformViewsChannel.java", + "io/flutter/embedding/engine/systemchannels/PlatformViewsChannel2.java", + "io/flutter/embedding/engine/systemchannels/ProcessTextChannel.java", + "io/flutter/embedding/engine/systemchannels/RestorationChannel.java", + "io/flutter/embedding/engine/systemchannels/ScribeChannel.java", + "io/flutter/embedding/engine/systemchannels/SettingsChannel.java", + "io/flutter/embedding/engine/systemchannels/SpellCheckChannel.java", + "io/flutter/embedding/engine/systemchannels/SystemChannel.java", + "io/flutter/embedding/engine/systemchannels/TextInputChannel.java", + "io/flutter/plugin/common/ActivityLifecycleListener.java", + "io/flutter/plugin/common/BasicMessageChannel.java", + "io/flutter/plugin/common/BinaryCodec.java", + "io/flutter/plugin/common/BinaryMessenger.java", + "io/flutter/plugin/common/ErrorLogResult.java", + "io/flutter/plugin/common/EventChannel.java", + "io/flutter/plugin/common/FlutterException.java", + "io/flutter/plugin/common/JSONMessageCodec.java", + "io/flutter/plugin/common/JSONMethodCodec.java", + "io/flutter/plugin/common/JSONUtil.java", + "io/flutter/plugin/common/MessageCodec.java", + "io/flutter/plugin/common/MethodCall.java", + "io/flutter/plugin/common/MethodChannel.java", + "io/flutter/plugin/common/MethodCodec.java", + "io/flutter/plugin/common/PluginRegistry.java", + "io/flutter/plugin/common/StandardMessageCodec.java", + "io/flutter/plugin/common/StandardMethodCodec.java", + "io/flutter/plugin/common/StringCodec.java", + "io/flutter/plugin/editing/FlutterTextUtils.java", + "io/flutter/plugin/editing/ImeSyncDeferringInsetsCallback.java", + "io/flutter/plugin/editing/InputConnectionAdaptor.java", + "io/flutter/plugin/editing/ListenableEditingState.java", + "io/flutter/plugin/editing/ScribePlugin.java", + "io/flutter/plugin/editing/SpellCheckPlugin.java", + "io/flutter/plugin/editing/TextEditingDelta.java", + "io/flutter/plugin/editing/TextInputPlugin.java", + "io/flutter/plugin/localization/LocalizationPlugin.java", + "io/flutter/plugin/mouse/MouseCursorPlugin.java", + "io/flutter/plugin/platform/AccessibilityEventsDelegate.java", + "io/flutter/plugin/platform/ImageReaderPlatformViewRenderTarget.java", + "io/flutter/plugin/platform/PlatformOverlayView.java", + "io/flutter/plugin/platform/PlatformPlugin.java", + "io/flutter/plugin/platform/PlatformView.java", + "io/flutter/plugin/platform/PlatformViewFactory.java", + "io/flutter/plugin/platform/PlatformViewRegistry.java", + "io/flutter/plugin/platform/PlatformViewRegistryImpl.java", + "io/flutter/plugin/platform/PlatformViewRenderTarget.java", + "io/flutter/plugin/platform/PlatformViewWrapper.java", + "io/flutter/plugin/platform/PlatformViewsAccessibilityDelegate.java", + "io/flutter/plugin/platform/PlatformViewsController.java", + "io/flutter/plugin/platform/PlatformViewsController2.java", + "io/flutter/plugin/platform/SingleViewFakeWindowViewGroup.java", + "io/flutter/plugin/platform/SingleViewPresentation.java", + "io/flutter/plugin/platform/SingleViewWindowManager.java", + "io/flutter/plugin/platform/SurfaceProducerPlatformViewRenderTarget.java", + "io/flutter/plugin/platform/SurfaceTexturePlatformViewRenderTarget.java", + "io/flutter/plugin/platform/VirtualDisplayController.java", + "io/flutter/plugin/platform/WindowManagerHandler.java", + "io/flutter/plugin/text/ProcessTextPlugin.java", + "io/flutter/util/HandlerCompat.java", + "io/flutter/util/PathUtils.java", + "io/flutter/util/Preconditions.java", + "io/flutter/util/Predicate.java", + "io/flutter/util/TraceSection.java", + "io/flutter/util/ViewUtils.java", + "io/flutter/view/AccessibilityBridge.java", + "io/flutter/view/AccessibilityViewEmbedder.java", + "io/flutter/view/FlutterCallbackInformation.java", + "io/flutter/view/FlutterRunArguments.java", + "io/flutter/view/TextureRegistry.java", + "io/flutter/view/VsyncWaiter.java", +] + +embedding_dependencies_jars = [ + "//flutter/third_party/android_embedding_dependencies/lib/activity-1.8.1.jar", + "//flutter/third_party/android_embedding_dependencies/lib/annotation-jvm-1.8.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/annotation-experimental-1.4.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/annotations-23.0.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/collection-1.1.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/core-1.13.1.jar", + "//flutter/third_party/android_embedding_dependencies/lib/core-1.10.3.jar", + "//flutter/third_party/android_embedding_dependencies/lib/core-common-2.2.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/core-runtime-2.2.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/customview-1.0.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/fragment-1.7.1.jar", + "//flutter/third_party/android_embedding_dependencies/lib/kotlin-stdlib-1.8.22.jar", + "//flutter/third_party/android_embedding_dependencies/lib/kotlin-stdlib-common-1.8.22.jar", + "//flutter/third_party/android_embedding_dependencies/lib/kotlin-stdlib-jdk7-1.8.20.jar", + "//flutter/third_party/android_embedding_dependencies/lib/kotlin-stdlib-jdk8-1.8.20.jar", + "//flutter/third_party/android_embedding_dependencies/lib/kotlinx-coroutines-android-1.7.1.jar", + "//flutter/third_party/android_embedding_dependencies/lib/kotlinx-coroutines-core-jvm-1.7.1.jar", + "//flutter/third_party/android_embedding_dependencies/lib/lifecycle-common-2.7.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/lifecycle-common-java8-2.7.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/lifecycle-livedata-2.7.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/lifecycle-livedata-core-2.7.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/lifecycle-process-2.7.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/lifecycle-runtime-2.7.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/lifecycle-viewmodel-2.7.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/loader-1.0.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/savedstate-1.2.1.jar", + "//flutter/third_party/android_embedding_dependencies/lib/tracing-1.2.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/versionedparcelable-1.1.1.jar", + "//flutter/third_party/android_embedding_dependencies/lib/viewpager-1.0.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/window-1.2.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/window-java-1.2.0.jar", + "//flutter/third_party/android_embedding_dependencies/lib/relinker-1.4.5.jar", +] + +action("check_imports") { + script = "//flutter/tools/android_illegal_imports.py" + + sources = android_java_sources + + stamp_file = "$root_out_dir/check_android_imports" + + # File does not actually get created, but GN expects us to have an output here. + outputs = [ stamp_file ] + + args = [ + "--stamp", + rebase_path(stamp_file), + "--files", + ] + rebase_path(android_java_sources) +} + +action("flutter_shell_java") { + script = "//build/android/gyp/javac.py" + depfile = "$target_gen_dir/$target_name.d" + + jar_path = embedding_jar_path + source_jar_path = embedding_source_jar_path + + sources = android_java_sources + + sources += get_target_outputs(":gen_android_build_config_java") + + outputs = [ + depfile, + jar_path, + jar_path + ".md5.stamp", + source_jar_path, + source_jar_path + ".md5.stamp", + ] + + lambda_jar = "$android_sdk_build_tools/core-lambda-stubs.jar" + inputs = [ + android_sdk_jar, + lambda_jar, + ] + embedding_dependencies_jars + + _rebased_current_path = rebase_path(".") + _rebased_jar_path = rebase_path(jar_path, root_build_dir) + _rebased_source_jar_path = rebase_path(source_jar_path, root_build_dir) + _rebased_depfile = rebase_path(depfile, root_build_dir) + _rebased_android_sdk_jar = rebase_path(android_sdk_jar, root_build_dir) + _rebased_lambda_jar = rebase_path(lambda_jar, root_build_dir) + _rebased_classpath = + [ + _rebased_android_sdk_jar, + _rebased_lambda_jar, + ] + rebase_path(embedding_dependencies_jars, root_build_dir) + + if (host_os == "mac") { + _javacbin = rebase_path( + "//flutter/third_party/java/openjdk/Contents/Home/bin/javac") + _jarbin = + rebase_path("//flutter/third_party/java/openjdk/Contents/Home/bin/jar") + } else if (host_os == "win") { + _javacbin = rebase_path("//flutter/third_party/java/openjdk/bin/javac.exe") + _jarbin = rebase_path("//flutter/third_party/java/openjdk/bin/jar.exe") + } else { + _javacbin = rebase_path("//flutter/third_party/java/openjdk/bin/javac") + _jarbin = rebase_path("//flutter/third_party/java/openjdk/bin/jar") + } + + args = [ + "--depfile=$_rebased_depfile", + "--jar-path=$_rebased_jar_path", + "--jar-source-path=$_rebased_source_jar_path", + "--jar-source-base-dir=$_rebased_current_path", + "--classpath=$_rebased_classpath", + "--bootclasspath=$_rebased_android_sdk_jar", + "--java-version=1.8", # Java 8 is required for backward compatibility. + "--jar-bin=$_jarbin", + "--javac-bin=$_javacbin", + ] + + args += rebase_path(sources, root_build_dir) + + deps = [ + ":check_imports", + ":gen_android_build_config_java", + ] +} + +action("android_jar") { + script = "//build/android/gyp/create_flutter_jar.py" + + if (stripped_symbols) { + engine_library = "lib.stripped/libflutter.so" + } else { + engine_library = "libflutter.so" + } + + inputs = [ + "$root_build_dir/$embedding_jar_filename", + "$root_build_dir/$engine_library", + ] + + engine_artifact_id = + string_replace(android_app_abi, "-", "_") + "_" + flutter_runtime_mode + + engine_jar_filename = "$engine_artifact_id.jar" + + outputs = [ + "$root_build_dir/flutter.jar", + "$root_build_dir/$engine_jar_filename", + ] + + args = [ + "--output", + rebase_path("flutter.jar", root_build_dir, root_build_dir), + "--output_native_jar", + rebase_path(engine_jar_filename, root_build_dir, root_build_dir), + "--dist_jar", + rebase_path(embedding_jar_filename, root_build_dir, root_build_dir), + "--native_lib", + rebase_path("$engine_library", root_build_dir, root_build_dir), + "--android_abi", + "$android_app_abi", + ] + + deps = [ + ":flutter_shell_java", + ":flutter_shell_native", + ":pom_embedding", + ":pom_libflutter", + ] + + if (impeller_enable_vulkan_validation_layers) { + assert(impeller_enable_vulkan) + + # We use a different toolchain here so that vulkan validation layers are + # built against API level 26, which they require, rather than the default. + # This is safe because the Engine can do a version check before loading the + # .so for the validation layers. + apilevel26_toolchain = "//build/toolchain/android:clang_arm64_apilevel26" + validation_layer_target = + "//third_party/vulkan_validation_layers($apilevel26_toolchain)" + deps += [ validation_layer_target ] + if (stripped_symbols) { + validation_library = "lib.stripped/libVkLayer_khronos_validation.so" + } else { + validation_layer_out_dir = + get_label_info(validation_layer_target, "root_out_dir") + validation_library = rebase_path( + "$validation_layer_out_dir/libVkLayer_khronos_validation.so") + } + + args += [ + "--native_lib", + validation_library, + ] + if (current_cpu != "arm64") { + # This may not be necessarily required anymore. It was kept to maintain + # old behavior. + assert(false, "Validation layers not supported for arch.") + } + } + + if (flutter_runtime_mode == "profile") { + deps += [ "//flutter/shell/vmservice:vmservice_snapshot" ] + args += [ + "--native_lib", + rebase_path( + "$root_gen_dir/flutter/shell/vmservice/android/libs/$android_app_abi/libvmservice_snapshot.so", + root_build_dir, + root_build_dir), + ] + } +} + +action("pom_libflutter") { + script = "//flutter/tools/androidx/generate_pom_file.py" + + inputs = [ "//flutter/tools/androidx/files.json" ] + + artifact_id = + string_replace(android_app_abi, "-", "_") + "_" + flutter_runtime_mode + + outputs = [ + "$root_build_dir/$artifact_id.pom", + "$root_build_dir/$artifact_id.maven-metadata.xml", + ] + + args = [ + "--destination", + rebase_path(root_build_dir), + "--engine-version", + engine_version, + "--engine-artifact-id", + artifact_id, + ] +} + +action("pom_embedding") { + script = "//flutter/tools/androidx/generate_pom_file.py" + + inputs = [ "//flutter/tools/androidx/files.json" ] + + artifact_id = "flutter_embedding_$flutter_runtime_mode" + + outputs = [ + "$root_build_dir/$artifact_id.pom", + "$root_build_dir/$artifact_id.maven-metadata.xml", + ] + + args = [ + "--destination", + rebase_path(root_build_dir), + "--engine-version", + engine_version, + "--engine-artifact-id", + artifact_id, + "--include-embedding-dependencies", + "true", + ] +} + +# TODO(jsimmons): remove this placeholder when it is no longer used by the LUCI recipes +group("robolectric_tests") { + deps = [ ":android_jar" ] +} + +zip_bundle("android_symbols") { + output = "$android_zip_archive_dir/symbols.zip" + files = [ + { + source = "$root_build_dir/libflutter.so" + destination = "libflutter.so" + }, + ] + + deps = [ ":flutter_shell_native" ] +} + +zip_bundle("flutter_jar_zip") { + output = "$android_zip_archive_dir/artifacts.zip" + files = [ + { + source = "$root_build_dir/flutter.jar" + destination = "flutter.jar" + }, + ] + + deps = [ ":android_jar" ] +} + +action("gen_android_javadoc") { + script = "//flutter/tools/javadoc/gen_javadoc.py" + sources = android_java_sources + embedding_dependencies_jars + + outputs = [ "$target_gen_dir/javadocs" ] + args = [ + "--out-dir", + rebase_path(outputs[0]), + "--android-source-root", + rebase_path("."), + "--build-config-path", + rebase_path(target_gen_dir), + "--src-dir", + rebase_path("//"), + "--quiet", + ] + + deps = [ ":gen_android_build_config_java" ] +} + +zip_bundle("android_javadoc") { + output = "android-javadoc.zip" + javadoc_dir = get_target_outputs(":gen_android_javadoc") + + files = [ + { + source = javadoc_dir[0] + destination = "/" + }, + ] + deps = [ ":gen_android_javadoc" ] +} + +generated_file("android_entitlement_config") { + outputs = [ "$target_gen_dir/android_entitlements.txt" ] + contents = [ "gen_snapshot" ] + deps = [] +} + +if (target_cpu != "x86") { + zip_bundle("gen_snapshot") { + gen_snapshot_out_dir = + get_label_info("$dart_src/runtime/bin:gen_snapshot($host_toolchain)", + "root_out_dir") + + # The source gen_snapshot binary from the build outputs. + gen_snapshot_src = rebase_path("$gen_snapshot_out_dir/gen_snapshot") + + # The output gen_snapshot binary name in the archive. + gen_snapshot_dest = "gen_snapshot" + + if (host_os == "mac") { + gen_snapshot_src = rebase_path("$root_out_dir/universal/gen_snapshot") + } else if (host_os == "win") { + gen_snapshot_src = rebase_path("$root_out_dir/gen_snapshot.exe") + gen_snapshot_dest = "gen_snapshot.exe" + } + + if (host_os == "linux") { + output = "$android_zip_archive_dir/linux-x64.zip" + } else if (host_os == "mac") { + output = "$android_zip_archive_dir/darwin-x64.zip" + } else if (host_os == "win") { + output = "$android_zip_archive_dir/windows-x64.zip" + } + + files = [ + { + source = gen_snapshot_src + destination = gen_snapshot_dest + }, + ] + + deps = [ "//flutter/lib/snapshot:generate_snapshot_bins" ] + + if (host_os == "mac") { + deps += [ ":android_entitlement_config" ] + files += [ + { + source = "$target_gen_dir/android_entitlements.txt" + destination = "entitlements.txt" + }, + ] + } + } +} + +if (host_os == "linux" && (target_cpu == "x64" || target_cpu == "arm64")) { + zip_bundle("analyze_snapshot") { + deps = [ "$dart_src/runtime/bin:analyze_snapshot($host_toolchain)" ] + + analyze_snapshot_bin = "analyze_snapshot" + analyze_snapshot_out_dir = + get_label_info( + "$dart_src/runtime/bin:analyze_snapshot($host_toolchain)", + "root_out_dir") + analyze_snapshot_path = + rebase_path("$analyze_snapshot_out_dir/$analyze_snapshot_bin") + + if (host_os == "linux") { + output = "$android_zip_archive_dir/analyze-snapshot-linux-x64.zip" + } else if (host_os == "mac") { + output = "$android_zip_archive_dir/analyze-snapshot-darwin-x64.zip" + } else if (host_os == "win") { + output = "$android_zip_archive_dir/analyze-snapshot-windows-x64.zip" + analyze_snapshot_bin = "analyze-snapshot.exe" + analyze_snapshot_path = rebase_path("$root_out_dir/$analyze_snapshot_bin") + } + + files = [ + { + source = analyze_snapshot_path + destination = analyze_snapshot_bin + }, + ] + } +} + +group("android") { + deps = [ + ":android_javadoc", + ":android_symbols", + ":flutter_jar_zip", + ] + if (target_cpu != "x86") { + deps += [ ":gen_snapshot" ] + } +} + +# Renames embedding android artifacts and places them in the final +# expected folder structure. +action("embedding_jars") { + script = "//flutter/build/android_artifacts.py" + + deps = [ + ":flutter_shell_java", + ":pom_embedding", + ] + sources = [ + "$root_out_dir/flutter_embedding_$flutter_runtime_mode.jar", + "$root_out_dir/flutter_embedding_$flutter_runtime_mode.pom", + ] + outputs = [] + args = [] + base_name = "$root_out_dir/zip_archives/download.flutter.io/io/flutter/" + + "flutter_embedding_$flutter_runtime_mode/1.0.0-$engine_version/" + + "flutter_embedding_$flutter_runtime_mode-1.0.0-${engine_version}" + foreach(source, sources) { + extension = get_path_info(source, "extension") + name = get_path_info(source, "name") + if (extension == "jar") { + outputs += [ + "${base_name}.jar", + "${base_name}-sources.jar", + ] + args += [ + "-i", + "${name}.jar", + rebase_path("${base_name}.jar"), + "-i", + "${name}-sources.jar", + rebase_path("${base_name}-sources.jar"), + ] + } else { + outputs += [ "${base_name}.${extension}" ] + args += [ + "-i", + rebase_path(source), + rebase_path("${base_name}.${extension}"), + ] + } + } +} + +# Renames android artifacts and places them in the final +# expected folder structure. +action("abi_jars") { + script = "//flutter/build/android_artifacts.py" + deps = [ + ":android_jar", + ":pom_libflutter", + ] + + artifact_id = + string_replace(android_app_abi, "-", "_") + "_" + flutter_runtime_mode + sources = [ + "$root_out_dir/${artifact_id}.jar", + "$root_out_dir/${artifact_id}.pom", + ] + outputs = [] + args = [] + base_name = "$root_out_dir/zip_archives/download.flutter.io/io/flutter/" + + "${artifact_id}/1.0.0-$engine_version/" + + "${artifact_id}-1.0.0-${engine_version}" + foreach(source, sources) { + extension = get_path_info(source, "extension") + name = get_path_info(source, "name") + outputs += [ "${base_name}.${extension}" ] + args += [ + "-i", + rebase_path(source), + rebase_path("${base_name}.${extension}"), + ] + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/README.md b/flutter/engine/src/flutter/shell/platform/android/README.md new file mode 100644 index 0000000000000000000000000000000000000000..982d706317eca685f4817119c2e13ee60016c01f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/README.md @@ -0,0 +1,236 @@ +# Android Platform Embedder + +Android embedder for Flutter, including Java [`io.flutter`](io/flutter/) sources +and Android specific engine-side C++. + +This code provides the glue between the Flutter engine and the Android platform, +and is responsible for: + +- Initializing the Flutter engine. +- Providing a platform view for the Flutter engine to render into. +- Dispatching events to the Flutter engine. + +> [!CAUTION] +> This is a best effort attempt to document the Android embedder. It is not +> guaranteed to be up to date or complete. If you find a discrepancy, please +> [send a pull request](https://github.com/flutter/engine/compare)! + +See also: + +- [`../../tools/android_lint/bin/main.dart`](../../../tools/android_lint/bin/main.dart) +- [Android Platform Views](https://github.com/flutter/flutter/wiki/Android-Platform-Views) +- [Hosting native Android views in your Flutter app with Platform Views](https://docs.flutter.dev/platform-integration/android/platform-views) +- [Testing Android Changes in the Devicelab on an Emulator](https://github.com/flutter/flutter/wiki/Testing-Android-Changes-in-the-Devicelab-on-an-Emulator) +- [Texture Layer Hybrid Composition](https://github.com/flutter/flutter/wiki/Texture-Layer-Hybrid-Composition) + +## Testing + +There are two classes of tests for the Android embedder: unit tests that tend +to test _contracts_ within the embedder, and integration tests that test the +engine and embedder together, typically coupled with a Flutter app (that's how +our users interact with the engine and embedder). + +### Unit tests + +Unit tests for the Android embedder are located in: + +- [`test`](test): Java unit tests. +- C++ files that end in `_unittests.cc` in [`shell/platform/android`](./). + +The easiest way (though not the quickest) is to use `run_tests.py`: + +```shell +# Assuming you're at the root of the engine repo where `run_tests.py` is located. +./testing/run_tests.py --type java + +# Confusingly, these are C++ tests for Android. +./testing/run_tests.py --type android + +# If you're using android_debug_unopt_arm64 builds: +./testing/run_tests.py --type android --android-variant android_debug_unopt_arm64 +./testing/run_tests.py --type java --android-variant android_debug_unopt_arm64 +``` + +> [!TIP] +> Trying to debug tests or timeouts/hangs? +> +> Run the tests directly from Android Studio, or [set `maxParallelForks` to `1`](https://github.com/flutter/flutter/blob/1cd3ab16ca1cba35e187ae75063fce0915985b94/engine/src/flutter/shell/platform/android/test_runner/build.gradle#L55): +> +> ```diff +> + maxParallelForks availableProcessors // The CI bot has 8 CPUs. +> - maxParallelForks 1 +> ``` + +### Integration tests + +Integration tests for the Android embedder mostly exist outside of the engine +for dubious historical reasons. + +To run these tests, you'll need to have a Flutter checkout and a working Android +emulator or device: + +```shell +# Build an up-to-date Flutter engine for Android. +cd $ENGINE/src + +# Or, use your favorite arguments and build variant. +ninja -j1000 -C ../out/android_debug_unopt_arm64 android_jar + +# Run the tests. Here is *1* example: +cd $FLUTTER/dev/integration_tests/external_textures +flutter drive \ + --local-engine-host=$ENGINE/out/host_debug_unopt_arm64 \ + --local-engine=$ENGINE/out/android_debug_unopt_arm64 +``` + +Another good source of (unfortunately, manual) testing is `flutter/packages`: + +```shell +cd $PACKAGES/packages/video_player/video_player_android/example +flutter run \ + --local-engine-host=$ENGINE/out/host_debug_unopt_arm64 \ + --local-engine=$ENGINE/out/android_debug_unopt_arm64 +``` + +> [!NOTE] +> External texture rendering on Android is based on the device API level. For +> example to test the OpenGLES branch (which uses `SurfaceTexture`), you'll +> typically need an older device or emulator with an API version 29 or lower. +> +> You can also (locally) "force" the engine to use `SurfaceTextures`: +> +> ```diff +> // shell/platform/android/io/flutter/embedding/engine/renderer/FlutterRenderer.java +> - @VisibleForTesting static boolean debugForceSurfaceProducerGlTextures = false; +> + @VisibleForTesting static boolean debugForceSurfaceProducerGlTextures = true; +> ``` +> +> ... and rebuild the engine. + +See [our wiki](https://github.com/flutter/flutter/wiki/Testing-the-engine#java---android-embedding) also. + +## Developing + +How to edit and contribute to the Android embedder. + +> [!TIP] +> This guide assumes you already have a working Engine development environment: +> +> - [Setting up the Engine development environment](https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment) +> - [Compiling for Android](https://github.com/flutter/flutter/wiki/Compiling-the-engine#compiling-for-android-from-macos-or-linux) +> +> You should also have a working Android development environment: +> +> - [Android Studio](https://developer.android.com/studio) +> - [Install Flutter > Test Drive](https://docs.flutter.dev/get-started/test-drive?tab=androidstudio) +> +> _It is also recommended (but not required) to install +> [Visual Studio Code](https://code.visualstudio.com/)._ + +Depending on what you are trying to do, you may need to edit the Java code in +[`io.flutter`](io/flutter/) or the C++ code in [`shell/platform/android`](./), +sometimes both. Let's start with the C++ code, as it is more similar to +developing for other platforms or platform-agnostic parts of the engine. + +### Editing C++ code + +The C++ code for the Android embedder is located in +[`shell/platform/android`](./) and subdirectories. + +Some notable files include: + +- [`context/android_context.h`](./context/android_context.h): Holds state that + is shared across Android surfaces. +- [`jni/platform_view_android_jni.h`](./jni/platform_view_android_jni.h): Allows + calling Java code running in the JVM. +- [`AndroidManifest.xml`](./AndroidManifest.xml): Used by [`android_lint`](../../../tools/android_lint/). +- [`BUILD.gn`](./BUILD.gn): Used by GN to build the C++-side embedder tests and + the `flutter.jar` file for the engine. +- [`ndk_helpers.h`](./ndk_helpers.h): Helper functions for dynamically loading + and calling Android NDK (C/C++) functions. +- [`platform_view_android.h`](./platform_view_android.h): The main entry point + for the Android embedder. + +See [VSCode with C/C++ Intellisense](https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment#vscode-with-cc-intellisense-cc) +for how to use the [`clangd`](https://marketplace.visualstudio.com/items?itemName=llvm-vs-code-extensions.vscode-clangd) extension to get C++ code +completion: + +![Example](https://github.com/flutter/flutter/assets/168174/8a75dd27-66e1-4c4f-88af-667a73b909b6) + +> [!NOTE] +> +> `--compile-commands-dir` must point to an Android build output: +> +> ```jsonc +> { +> /* ... */ +> "clangd.path": "buildtools/mac-arm64/clang/bin/clangd", +> "clangd.arguments": ["--compile-commands-dir=out/android_debug_unopt_arm64"] +> /* ... */ +> } +> ``` +> +> ... but remember to change it back when editing other parts of the engine. + +### Editing Java code + +The Java code for the Android embedder is located in +[`io/flutter/`](io/flutter/) and subdirectories. + +The tests are located in [`test/io/flutter/`](test/io/flutter/), and the test +runner in [`test_runner`](test_runner/). + +Some notable files include: + +- [`io/flutter/embedding/android/FlutterActivity.java`](io/flutter/embedding/android/FlutterActivity.java): + An activity that displays a full-screen Flutter UI. +- [`io/flutter/embedding/engine/FlutterJNI.java`](io/flutter/embedding/engine/FlutterJNI.java): + The Java interface for the C++ engine. +- [`io/flutter/view/TextureRegistry.java`](io/flutter/view/TextureRegistry.java): + Registry of backend textures used by a Flutter View. + +It is non-trivial to get a working IDE setup for editing Java code in the +Flutter engine. Some developers have had success [using VSCode as an IDE for the Android Embedding](https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment#using-vscode-as-an-ide-for-the-android-embedding-java), +but the following instructions are for if that doesn't work, or you want to use +Android Studio: + +1. Open `shell/platform/android` in Android Studio. +1. Configure the following: + + - [`Preferences | Build, Execution, Deployment | Gradle-Android Compiler`](jetbrains://AndroidStudio/settings?name=Build%2C+Execution%2C+Deployment--Gradle-Android+Compiler) + + Command-line Options: + + ```txt + -Pbuild_dir="/tmp/build_dir" -Pflutter_jar="$ENGINE/src/out/android_debug_unopt_arm64/flutter.jar" + ``` + + - [`Preferences | Build, Execution, Deployment | Build Tools | Gradle`](jetbrains://AndroidStudio/settings?name=Build%2C+Execution%2C+Deployment--Build+Tools--Gradle) + + Distribution of `Local Installation` with: + + ```txt + $ENGINE/src/third_party/gradle + ``` + + Gradle SDK using Android Studio (path depends on your machine): + + ```txt + /Applications/Android Studio.app/Contents/jbr/Contents/Home + ``` + +1. Sync Gradle. + + ![Example](https://github.com/flutter/flutter/assets/168174/02fe0e6f-f0c4-47b2-8dae-9aa0b9520503) + +At this point you should be able to open Java files in Android Studio and get +code completion in the `io/flutter` and `test/io/flutter` folders. For example, `FlutterJNI.java`: + +![Example](https://github.com/flutter/flutter/assets/168174/387550d4-eab7-4097-9da3-7713a6ec4da7) + +To get code coverage displayed in line: go to the test class you wish to run and + +1. Right click > Modify Run Configuration..., +2. In the window that pops up click Modify options > Specify classes + and packages (under "code coverage"). +3. In the new box that appears at the bottom of the window, click the + > Add package, and then add `io.flutter.*`. diff --git a/flutter/engine/src/flutter/shell/platform/android/android_context_gl_impeller.cc b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..f67f5899bc15f6955184ce91df3c2fe12094d7d4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_impeller.cc @@ -0,0 +1,256 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_context_gl_impeller.h" + +#include "flutter/impeller/renderer/backend/gles/context_gles.h" +#include "flutter/impeller/renderer/backend/gles/proc_table_gles.h" +#include "flutter/impeller/renderer/backend/gles/reactor_gles.h" +#include "flutter/impeller/toolkit/egl/context.h" +#include "flutter/impeller/toolkit/egl/surface.h" +#include "impeller/entity/gles/entity_shaders_gles.h" +#include "impeller/entity/gles/framebuffer_blend_shaders_gles.h" +#include "impeller/entity/gles3/entity_shaders_gles.h" +#include "impeller/entity/gles3/framebuffer_blend_shaders_gles.h" + +namespace flutter { + +class AndroidContextGLImpeller::ReactorWorker final + : public impeller::ReactorGLES::Worker { + public: + ReactorWorker() = default; + + // |impeller::ReactorGLES::Worker| + ~ReactorWorker() override = default; + + // |impeller::ReactorGLES::Worker| + bool CanReactorReactOnCurrentThreadNow( + const impeller::ReactorGLES& reactor) const override { + impeller::ReaderLock lock(mutex_); + auto found = reactions_allowed_.find(std::this_thread::get_id()); + if (found == reactions_allowed_.end()) { + return false; + } + return found->second; + } + + void SetReactionsAllowedOnCurrentThread(bool allowed) { + impeller::WriterLock lock(mutex_); + reactions_allowed_[std::this_thread::get_id()] = allowed; + } + + private: + mutable impeller::RWMutex mutex_; + std::map reactions_allowed_ IPLR_GUARDED_BY(mutex_); + + FML_DISALLOW_COPY_AND_ASSIGN(ReactorWorker); +}; + +static std::shared_ptr CreateImpellerContext( + const std::shared_ptr& worker, + bool enable_gpu_tracing) { + auto proc_table = std::make_unique( + impeller::egl::CreateProcAddressResolver()); + + if (!proc_table->IsValid()) { + FML_LOG(ERROR) << "Could not create OpenGL proc table."; + return nullptr; + } + bool is_gles3 = proc_table->GetDescription()->GetGlVersion().IsAtLeast( + impeller::Version{3, 0, 0}); + + std::vector> gles2_shader_mappings = { + std::make_shared( + impeller_entity_shaders_gles_data, + impeller_entity_shaders_gles_length), + std::make_shared( + impeller_framebuffer_blend_shaders_gles_data, + impeller_framebuffer_blend_shaders_gles_length), + }; + + std::vector> gles3_shader_mappings = { + std::make_shared( + impeller_entity_shaders_gles3_data, + impeller_entity_shaders_gles3_length), + std::make_shared( + impeller_framebuffer_blend_shaders_gles3_data, + impeller_framebuffer_blend_shaders_gles3_length), + }; + + auto context = impeller::ContextGLES::Create( + impeller::Flags{}, std::move(proc_table), + is_gles3 ? gles3_shader_mappings : gles2_shader_mappings, + enable_gpu_tracing); + if (!context) { + FML_LOG(ERROR) << "Could not create OpenGLES Impeller Context."; + return nullptr; + } + + if (!context->AddReactorWorker(worker).has_value()) { + FML_LOG(ERROR) << "Could not add reactor worker."; + return nullptr; + } + FML_LOG(IMPORTANT) << "Using the Impeller rendering backend (OpenGLES)."; + return context; +} + +AndroidContextGLImpeller::AndroidContextGLImpeller( + std::unique_ptr display, + bool enable_gpu_tracing) + : AndroidContext(AndroidRenderingAPI::kImpellerOpenGLES), + reactor_worker_(std::shared_ptr(new ReactorWorker())), + display_(std::move(display)) { + if (!display_ || !display_->IsValid()) { + FML_LOG(ERROR) << "Could not create context with invalid EGL display."; + return; + } + + impeller::egl::ConfigDescriptor desc; + desc.api = impeller::egl::API::kOpenGLES3; + desc.color_format = impeller::egl::ColorFormat::kRGBA8888; + desc.depth_bits = impeller::egl::DepthBits::kTwentyFour; + desc.stencil_bits = impeller::egl::StencilBits::kEight; + desc.samples = impeller::egl::Samples::kFour; + + desc.surface_type = impeller::egl::SurfaceType::kWindow; + std::unique_ptr onscreen_config = + display_->ChooseConfig(desc); + + if (!onscreen_config) { + desc.api = impeller::egl::API::kOpenGLES2; + onscreen_config = display_->ChooseConfig(desc); + } + + if (!onscreen_config) { + // Fallback for Android emulator. + desc.samples = impeller::egl::Samples::kOne; + onscreen_config = display_->ChooseConfig(desc); + if (onscreen_config) { + FML_LOG(INFO) << "Warning: This device doesn't support MSAA for onscreen " + "framebuffers. Falling back to a single sample."; + } else { + FML_LOG(ERROR) << "Could not choose onscreen config."; + return; + } + } + + desc.surface_type = impeller::egl::SurfaceType::kPBuffer; + auto offscreen_config = display_->ChooseConfig(desc); + if (!offscreen_config) { + FML_LOG(ERROR) << "Could not choose offscreen config."; + return; + } + + auto onscreen_context = display_->CreateContext(*onscreen_config, nullptr); + if (!onscreen_context) { + FML_LOG(ERROR) << "Could not create onscreen context."; + return; + } + + auto offscreen_context = + display_->CreateContext(*offscreen_config, onscreen_context.get()); + if (!offscreen_context) { + FML_LOG(ERROR) << "Could not create offscreen context."; + return; + } + + // Creating the impeller::Context requires a current context, which requires + // some surface. + auto offscreen_surface = + display_->CreatePixelBufferSurface(*offscreen_config, 1u, 1u); + if (!offscreen_context->MakeCurrent(*offscreen_surface)) { + FML_LOG(ERROR) << "Could not make offscreen context current."; + return; + } + + auto impeller_context = + CreateImpellerContext(reactor_worker_, enable_gpu_tracing); + + if (!impeller_context) { + FML_LOG(ERROR) << "Could not create Impeller context."; + return; + } + + if (!offscreen_context->ClearCurrent()) { + FML_LOG(ERROR) << "Could not clear offscreen context."; + return; + } + // Setup context listeners. + impeller::egl::Context::LifecycleListener listener = + [worker = + reactor_worker_](impeller::egl ::Context::LifecycleEvent event) { + switch (event) { + case impeller::egl::Context::LifecycleEvent::kDidMakeCurrent: + worker->SetReactionsAllowedOnCurrentThread(true); + break; + case impeller::egl::Context::LifecycleEvent::kWillClearCurrent: + worker->SetReactionsAllowedOnCurrentThread(false); + break; + } + }; + if (!onscreen_context->AddLifecycleListener(listener).has_value() || + !offscreen_context->AddLifecycleListener(listener).has_value()) { + FML_LOG(ERROR) << "Could not add lifecycle listeners"; + } + + onscreen_config_ = std::move(onscreen_config); + offscreen_config_ = std::move(offscreen_config); + onscreen_context_ = std::move(onscreen_context); + offscreen_context_ = std::move(offscreen_context); + SetImpellerContext(impeller_context); + + is_valid_ = true; +} + +AndroidContextGLImpeller::~AndroidContextGLImpeller() = default; + +bool AndroidContextGLImpeller::IsValid() const { + return is_valid_; +} + +bool AndroidContextGLImpeller::ResourceContextClearCurrent() { + if (!offscreen_context_) { + return false; + } + + return offscreen_context_->ClearCurrent(); +} + +bool AndroidContextGLImpeller::ResourceContextMakeCurrent( + impeller::egl::Surface* offscreen_surface) { + if (!offscreen_context_ || !offscreen_surface) { + return false; + } + + return offscreen_context_->MakeCurrent(*offscreen_surface); +} + +std::unique_ptr +AndroidContextGLImpeller::CreateOffscreenSurface() { + return display_->CreatePixelBufferSurface(*offscreen_config_, 1u, 1u); +} + +bool AndroidContextGLImpeller::OnscreenContextMakeCurrent( + impeller::egl::Surface* onscreen_surface) { + if (!onscreen_surface || !onscreen_context_) { + return false; + } + + return onscreen_context_->MakeCurrent(*onscreen_surface); +} + +bool AndroidContextGLImpeller::OnscreenContextClearCurrent() { + if (!onscreen_context_) { + return false; + } + + return onscreen_context_->ClearCurrent(); +} + +std::unique_ptr +AndroidContextGLImpeller::CreateOnscreenSurface(EGLNativeWindowType window) { + return display_->CreateWindowSurface(*onscreen_config_, window); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_context_gl_impeller.h b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..234ff58d2c91e2f9646608ac98cf6f2a836783be --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_impeller.h @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_GL_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_GL_IMPELLER_H_ + +#include "flutter/fml/macros.h" +#include "flutter/impeller/toolkit/egl/display.h" +#include "flutter/shell/platform/android/context/android_context.h" + +namespace flutter { + +class AndroidContextGLImpeller : public AndroidContext { + public: + AndroidContextGLImpeller(std::unique_ptr display, + bool enable_gpu_tracing); + + ~AndroidContextGLImpeller(); + + // |AndroidContext| + bool IsValid() const override; + + bool ResourceContextMakeCurrent(impeller::egl::Surface* offscreen_surface); + bool ResourceContextClearCurrent(); + std::unique_ptr CreateOffscreenSurface(); + bool OnscreenContextMakeCurrent(impeller::egl::Surface* onscreen_surface); + bool OnscreenContextClearCurrent(); + std::unique_ptr CreateOnscreenSurface( + EGLNativeWindowType window); + + private: + class ReactorWorker; + + std::shared_ptr reactor_worker_; + std::unique_ptr display_; + std::unique_ptr onscreen_config_; + std::unique_ptr offscreen_config_; + std::unique_ptr onscreen_context_; + std::unique_ptr offscreen_context_; + bool is_valid_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidContextGLImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_GL_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_context_gl_impeller_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_impeller_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..b74c068de093ae78758b5cb795ab1890ae76e511 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_impeller_unittests.cc @@ -0,0 +1,140 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_context_gl_impeller.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +using ::testing::_; +using ::testing::AllOf; +using ::testing::ByMove; +using ::testing::Field; +using ::testing::Matcher; +using ::testing::Return; + +using ::impeller::egl::Config; +using ::impeller::egl::ConfigDescriptor; + +namespace { +class MockDisplay : public impeller::egl::Display { + public: + MOCK_METHOD(bool, IsValid, (), (const, override)); + MOCK_METHOD(std::unique_ptr, + ChooseConfig, + (ConfigDescriptor), + (const, override)); +}; + +bool GetEGLConfigForSurface(EGLint surface_bit, EGLConfig* result) { + EGLint attributes[] = { + // clang-format off + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, + EGL_SURFACE_TYPE, surface_bit, + EGL_RED_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, + EGL_DEPTH_SIZE, 24, + EGL_STENCIL_SIZE, 8, + EGL_NONE, + // clang-format on + }; + EGLint config_count = 0; + return eglChooseConfig(eglGetDisplay(EGL_DEFAULT_DISPLAY), attributes, result, + 1, &config_count); +} + +} // namespace + +class AndroidContextGLImpellerTest : public ::testing::Test { + public: + AndroidContextGLImpellerTest() {} + + void SetUp() override { + EGLDisplay egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); + ASSERT_TRUE(eglInitialize(egl_display, nullptr, nullptr)); + } +}; + +TEST_F(AndroidContextGLImpellerTest, MSAAFirstAttempt) { + EGLConfig window_egl_config, pbuffer_egl_config; + ASSERT_TRUE(GetEGLConfigForSurface(EGL_WINDOW_BIT, &window_egl_config)); + ASSERT_TRUE(GetEGLConfigForSurface(EGL_PBUFFER_BIT, &pbuffer_egl_config)); + + auto display = std::make_unique(); + EXPECT_CALL(*display, IsValid).WillRepeatedly(Return(true)); + auto first_result = + std::make_unique(ConfigDescriptor(), window_egl_config); + auto second_result = + std::make_unique(ConfigDescriptor(), pbuffer_egl_config); + EXPECT_CALL( + *display, + ChooseConfig(Matcher(AllOf( + Field(&ConfigDescriptor::samples, impeller::egl::Samples::kFour), + Field(&ConfigDescriptor::surface_type, + impeller::egl::SurfaceType::kWindow))))) + .WillOnce(Return(ByMove(std::move(first_result)))); + EXPECT_CALL(*display, ChooseConfig(Matcher( + Field(&ConfigDescriptor::surface_type, + impeller::egl::SurfaceType::kPBuffer)))) + .WillOnce(Return(ByMove(std::move(second_result)))); + ON_CALL(*display, ChooseConfig(_)) + .WillByDefault(Return(ByMove(std::unique_ptr()))); + auto context = + std::make_unique(std::move(display), true); + ASSERT_TRUE(context); +} + +TEST_F(AndroidContextGLImpellerTest, FallbackForEmulator) { + EGLConfig window_egl_config, pbuffer_egl_config; + ASSERT_TRUE(GetEGLConfigForSurface(EGL_WINDOW_BIT, &window_egl_config)); + ASSERT_TRUE(GetEGLConfigForSurface(EGL_PBUFFER_BIT, &pbuffer_egl_config)); + + auto display = std::make_unique(); + EXPECT_CALL(*display, IsValid).WillRepeatedly(Return(true)); + std::unique_ptr first_result; + std::unique_ptr second_result; + auto third_result = + std::make_unique(ConfigDescriptor(), window_egl_config); + auto fourth_result = + std::make_unique(ConfigDescriptor(), pbuffer_egl_config); + EXPECT_CALL( + *display, + ChooseConfig(Matcher(AllOf( + Field(&ConfigDescriptor::api, impeller::egl::API::kOpenGLES3), + Field(&ConfigDescriptor::samples, impeller::egl::Samples::kFour), + Field(&ConfigDescriptor::surface_type, + impeller::egl::SurfaceType::kWindow))))) + .WillOnce(Return(ByMove(std::move(first_result)))); + EXPECT_CALL( + *display, + ChooseConfig(Matcher(AllOf( + Field(&ConfigDescriptor::api, impeller::egl::API::kOpenGLES2), + Field(&ConfigDescriptor::samples, impeller::egl::Samples::kFour), + Field(&ConfigDescriptor::surface_type, + impeller::egl::SurfaceType::kWindow))))) + .WillOnce(Return(ByMove(std::move(second_result)))); + EXPECT_CALL( + *display, + ChooseConfig(Matcher( + AllOf(Field(&ConfigDescriptor::samples, impeller::egl::Samples::kOne), + Field(&ConfigDescriptor::surface_type, + impeller::egl::SurfaceType::kWindow))))) + .WillOnce(Return(ByMove(std::move(third_result)))); + EXPECT_CALL(*display, ChooseConfig(Matcher( + Field(&ConfigDescriptor::surface_type, + impeller::egl::SurfaceType::kPBuffer)))) + .WillOnce(Return(ByMove(std::move(fourth_result)))); + ON_CALL(*display, ChooseConfig(_)) + .WillByDefault(Return(ByMove(std::unique_ptr()))); + auto context = + std::make_unique(std::move(display), true); + ASSERT_TRUE(context); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_context_gl_skia.cc b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..652cefc864f7f7e5a093312736363acc3f3496f5 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_skia.cc @@ -0,0 +1,216 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_context_gl_skia.h" + +#include + +#include "flutter/fml/trace_event.h" +#include "flutter/shell/platform/android/android_egl_surface.h" + +namespace flutter { + +template +using EGLResult = std::pair; + +static EGLResult CreateContext(EGLDisplay display, + EGLConfig config, + EGLContext share = EGL_NO_CONTEXT) { + EGLint attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; + + EGLContext context = eglCreateContext(display, config, share, attributes); + + return {context != EGL_NO_CONTEXT, context}; +} + +static EGLResult ChooseEGLConfiguration(EGLDisplay display) { + EGLint attributes[] = { + // clang-format off + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_RED_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, + EGL_DEPTH_SIZE, 0, + EGL_STENCIL_SIZE, 0, + EGL_NONE, // termination sentinel + // clang-format on + }; + + EGLint config_count = 0; + EGLConfig egl_config = nullptr; + + if (eglChooseConfig(display, attributes, &egl_config, 1, &config_count) != + EGL_TRUE) { + return {false, nullptr}; + } + + bool success = config_count > 0 && egl_config != nullptr; + + return {success, success ? egl_config : nullptr}; +} + +static bool TeardownContext(EGLDisplay display, EGLContext context) { + if (context != EGL_NO_CONTEXT) { + return eglDestroyContext(display, context) == EGL_TRUE; + } + + return true; +} + +AndroidContextGLSkia::AndroidContextGLSkia( + fml::RefPtr environment, + const TaskRunners& task_runners) + : AndroidContext(AndroidRenderingAPI::kSkiaOpenGLES), + environment_(std::move(environment)), + task_runners_(task_runners) { + if (!environment_->IsValid()) { + FML_LOG(ERROR) << "Could not create an Android GL environment."; + return; + } + + bool success = false; + + // Choose a valid configuration. + std::tie(success, config_) = ChooseEGLConfiguration(environment_->Display()); + if (!success) { + FML_LOG(ERROR) << "Could not choose an EGL configuration."; + LogLastEGLError(); + return; + } + + // Create a context for the configuration. + std::tie(success, context_) = + CreateContext(environment_->Display(), config_, EGL_NO_CONTEXT); + if (!success) { + FML_LOG(ERROR) << "Could not create an EGL context"; + LogLastEGLError(); + return; + } + + std::tie(success, resource_context_) = + CreateContext(environment_->Display(), config_, context_); + if (!success) { + FML_LOG(ERROR) << "Could not create an EGL resource context"; + LogLastEGLError(); + return; + } + + // All done! + valid_ = true; +} + +AndroidContextGLSkia::~AndroidContextGLSkia() { + FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); + sk_sp main_context = GetMainSkiaContext(); + SetMainSkiaContext(nullptr); + fml::AutoResetWaitableEvent latch; + // This context needs to be deallocated from the raster thread in order to + // keep a coherent usage of egl from a single thread. + fml::TaskRunner::RunNowOrPostTask(task_runners_.GetRasterTaskRunner(), [&] { + if (main_context) { + std::unique_ptr pbuffer_surface = + CreatePbufferSurface(); + auto status = pbuffer_surface->MakeCurrent(); + if (status != AndroidEGLSurfaceMakeCurrentStatus::kFailure) { + main_context->releaseResourcesAndAbandonContext(); + main_context.reset(); + ClearCurrent(); + } + } + latch.Signal(); + }); + latch.Wait(); + + if (!TeardownContext(environment_->Display(), context_)) { + FML_LOG(ERROR) + << "Could not tear down the EGL context. Possible resource leak."; + LogLastEGLError(); + } + + if (!TeardownContext(environment_->Display(), resource_context_)) { + FML_LOG(ERROR) << "Could not tear down the EGL resource context. Possible " + "resource leak."; + LogLastEGLError(); + } +} + +std::unique_ptr AndroidContextGLSkia::CreateOnscreenSurface( + const fml::RefPtr& window) const { + if (window->IsFakeWindow()) { + return CreatePbufferSurface(); + } else { + EGLDisplay display = environment_->Display(); + + const EGLint attribs[] = {EGL_NONE}; + + EGLSurface surface = eglCreateWindowSurface( + display, config_, + reinterpret_cast(window->handle()), attribs); + return std::make_unique(surface, display, context_); + } +} + +std::unique_ptr +AndroidContextGLSkia::CreateOffscreenSurface() const { + // We only ever create pbuffer surfaces for background resource loading + // contexts. We never bind the pbuffer to anything. + EGLDisplay display = environment_->Display(); + + const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; + + EGLSurface surface = eglCreatePbufferSurface(display, config_, attribs); + return std::make_unique(surface, display, + resource_context_); +} + +std::unique_ptr AndroidContextGLSkia::CreatePbufferSurface() + const { + EGLDisplay display = environment_->Display(); + + const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; + + EGLSurface surface = eglCreatePbufferSurface(display, config_, attribs); + return std::make_unique(surface, display, context_); +} + +fml::RefPtr AndroidContextGLSkia::Environment() const { + return environment_; +} + +bool AndroidContextGLSkia::IsValid() const { + return valid_; +} + +bool AndroidContextGLSkia::ClearCurrent() const { + if (eglGetCurrentContext() != context_) { + return true; + } + if (eglMakeCurrent(environment_->Display(), EGL_NO_SURFACE, EGL_NO_SURFACE, + EGL_NO_CONTEXT) != EGL_TRUE) { + FML_LOG(ERROR) << "Could not clear the current context"; + LogLastEGLError(); + return false; + } + return true; +} + +EGLContext AndroidContextGLSkia::GetEGLContext() const { + return context_; +} + +EGLDisplay AndroidContextGLSkia::GetEGLDisplay() const { + return environment_->Display(); +} + +EGLContext AndroidContextGLSkia::CreateNewContext() const { + bool success; + EGLContext context; + std::tie(success, context) = + CreateContext(environment_->Display(), config_, EGL_NO_CONTEXT); + return success ? context : EGL_NO_CONTEXT; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_context_gl_skia.h b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..d5dc6d17dbe0d57a3845434edd0d51384243bb7e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_skia.h @@ -0,0 +1,116 @@ +// 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_ANDROID_ANDROID_CONTEXT_GL_SKIA_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_GL_SKIA_H_ + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/ref_counted.h" +#include "flutter/fml/memory/ref_ptr.h" +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/platform/android/android_environment_gl.h" +#include "flutter/shell/platform/android/context/android_context.h" +#include "flutter/shell/platform/android/surface/android_native_window.h" +#include "third_party/skia/include/core/SkSize.h" + +namespace flutter { + +class AndroidEGLSurface; + +//------------------------------------------------------------------------------ +/// The Android context is used by `AndroidSurfaceGL` to create and manage +/// EGL surfaces. +/// +/// This context binds `EGLContext` to the current rendering thread and to the +/// draw and read `EGLSurface`s. +/// +class AndroidContextGLSkia : public AndroidContext { + public: + AndroidContextGLSkia(fml::RefPtr environment, + const TaskRunners& taskRunners); + + ~AndroidContextGLSkia(); + + //---------------------------------------------------------------------------- + /// @brief Allocates an new EGL window surface that is used for on-screen + /// pixels. + /// + /// @return The window surface. + /// + std::unique_ptr CreateOnscreenSurface( + const fml::RefPtr& window) const; + + //---------------------------------------------------------------------------- + /// @brief Allocates an 1x1 pbuffer surface that is used for making the + /// offscreen current for texture uploads. + /// + /// @return The pbuffer surface. + /// + std::unique_ptr CreateOffscreenSurface() const; + + //---------------------------------------------------------------------------- + /// @brief Allocates an 1x1 pbuffer surface that is used for making the + /// onscreen context current for snapshotting. + /// + /// @return The pbuffer surface. + /// + std::unique_ptr CreatePbufferSurface() const; + + //---------------------------------------------------------------------------- + /// @return The Android environment that contains a reference to the + /// display. + /// + fml::RefPtr Environment() const; + + //---------------------------------------------------------------------------- + /// @return Whether the current context is valid. That is, if the EGL + /// contexts were successfully created. + /// + bool IsValid() const override; + + //---------------------------------------------------------------------------- + /// @return Whether the current context was successfully clear. + /// + bool ClearCurrent() const; + + //---------------------------------------------------------------------------- + /// @brief Returns the EGLContext. + /// + /// @return EGLContext. + /// + EGLContext GetEGLContext() const; + + //---------------------------------------------------------------------------- + /// @brief Returns the EGLDisplay. + /// + /// @return EGLDisplay. + /// + EGLDisplay GetEGLDisplay() const; + + //---------------------------------------------------------------------------- + /// @brief Create a new EGLContext using the same EGLConfig. + /// + /// @return The EGLContext. + /// + EGLContext CreateNewContext() const; + + //---------------------------------------------------------------------------- + /// @brief The EGLConfig for this context. + /// + EGLConfig Config() const { return config_; } + + private: + fml::RefPtr environment_; + EGLConfig config_; + EGLContext context_; + EGLContext resource_context_; + bool valid_ = false; + TaskRunners task_runners_; + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidContextGLSkia); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_GL_SKIA_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_context_gl_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..d19d2d2cb9ff84130937f2e21d44b84019dd82f1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_context_gl_unittests.cc @@ -0,0 +1,228 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include +#include "flutter/shell/common/thread_host.h" +#include "flutter/shell/platform/android/android_context_gl_skia.h" +#include "flutter/shell/platform/android/android_egl_surface.h" +#include "flutter/shell/platform/android/android_environment_gl.h" +#include "flutter/shell/platform/android/android_surface_gl_skia.h" +#include "fml/logging.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "impeller/core/runtime_types.h" +#include "shell/platform/android/context/android_context.h" + +namespace flutter { +namespace testing { +namespace android { +namespace { + +TaskRunners MakeTaskRunners(const std::string& thread_label, + const ThreadHost& thread_host) { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + fml::RefPtr platform_runner = + fml::MessageLoop::GetCurrent().GetTaskRunner(); + + return TaskRunners(thread_label, platform_runner, + thread_host.raster_thread->GetTaskRunner(), + thread_host.ui_thread->GetTaskRunner(), + thread_host.io_thread->GetTaskRunner()); +} +} // namespace + +class TestImpellerContext : public impeller::Context { + public: + TestImpellerContext() : Context(impeller::Flags{}) {} + + ~TestImpellerContext() {} + + impeller::Context::BackendType GetBackendType() const override { + return impeller::Context::BackendType::kOpenGLES; + } + + std::string DescribeGpuModel() const override { return ""; } + + bool IsValid() const override { return true; } + + const std::shared_ptr& GetCapabilities() + const override { + FML_UNREACHABLE(); + } + + bool UpdateOffscreenLayerPixelFormat(impeller::PixelFormat format) override { + FML_UNREACHABLE(); + } + + std::shared_ptr GetResourceAllocator() const override { + FML_UNREACHABLE(); + } + + std::shared_ptr GetShaderLibrary() const override { + FML_UNREACHABLE(); + } + + std::shared_ptr GetSamplerLibrary() const override { + FML_UNREACHABLE(); + } + + std::shared_ptr GetPipelineLibrary() + const override { + FML_UNREACHABLE(); + } + + std::shared_ptr CreateCommandBuffer() + const override { + FML_UNREACHABLE(); + } + + std::shared_ptr GetCommandQueue() const override { + FML_UNREACHABLE(); + } + + void Shutdown() override { did_shutdown = true; } + + impeller::RuntimeStageBackend GetRuntimeStageBackend() const override { + return impeller::RuntimeStageBackend::kVulkan; + } + + bool did_shutdown = false; +}; + +class TestAndroidContext : public AndroidContext { + public: + TestAndroidContext(const std::shared_ptr& impeller_context, + AndroidRenderingAPI rendering_api) + : AndroidContext(rendering_api) { + SetImpellerContext(impeller_context); + } +}; + +TEST(AndroidContextGl, Create) { + GrMockOptions main_context_options; + sk_sp main_context = + GrDirectContext::MakeMock(&main_context_options); + auto environment = fml::MakeRefCounted(); + std::string thread_label = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + thread_label, ThreadHost::Type::kUi | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo)); + TaskRunners task_runners = MakeTaskRunners(thread_label, thread_host); + auto context = + std::make_unique(environment, task_runners); + context->SetMainSkiaContext(main_context); + EXPECT_NE(context.get(), nullptr); + context.reset(); + EXPECT_TRUE(main_context->abandoned()); +} + +TEST(AndroidContextGl, CreateImpeller) { + auto impeller_context = std::make_shared(); + auto android_context = std::make_unique( + impeller_context, AndroidRenderingAPI::kImpellerOpenGLES); + EXPECT_FALSE(impeller_context->did_shutdown); + + android_context.reset(); + + EXPECT_TRUE(impeller_context->did_shutdown); +} + +TEST(AndroidContextGl, CreateSingleThread) { + GrMockOptions main_context_options; + sk_sp main_context = + GrDirectContext::MakeMock(&main_context_options); + auto environment = fml::MakeRefCounted(); + std::string thread_label = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + fml::MessageLoop::EnsureInitializedForCurrentThread(); + fml::RefPtr platform_runner = + fml::MessageLoop::GetCurrent().GetTaskRunner(); + TaskRunners task_runners = + TaskRunners(thread_label, platform_runner, platform_runner, + platform_runner, platform_runner); + auto context = + std::make_unique(environment, task_runners); + context->SetMainSkiaContext(main_context); + EXPECT_NE(context.get(), nullptr); + context.reset(); + EXPECT_TRUE(main_context->abandoned()); +} + +TEST(AndroidSurfaceGL, CreateSnapshopSurfaceWhenOnscreenSurfaceIsNotNull) { + GrMockOptions main_context_options; + sk_sp main_context = + GrDirectContext::MakeMock(&main_context_options); + auto environment = fml::MakeRefCounted(); + std::string thread_label = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + thread_label, ThreadHost::Type::kUi | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo)); + TaskRunners task_runners = MakeTaskRunners(thread_label, thread_host); + auto android_context = + std::make_shared(environment, task_runners); + auto android_surface = + std::make_unique(android_context); + auto window = fml::MakeRefCounted( + nullptr, /*is_fake_window=*/true); + android_surface->SetNativeWindow(window, nullptr); + auto onscreen_surface = android_surface->GetOnscreenSurface(); + EXPECT_NE(onscreen_surface, nullptr); + android_surface->CreateSnapshotSurface(); + EXPECT_EQ(onscreen_surface, android_surface->GetOnscreenSurface()); +} + +TEST(AndroidSurfaceGL, CreateSnapshopSurfaceWhenOnscreenSurfaceIsNull) { + GrMockOptions main_context_options; + sk_sp main_context = + GrDirectContext::MakeMock(&main_context_options); + auto environment = fml::MakeRefCounted(); + std::string thread_label = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + + auto mask = + ThreadHost::Type::kUi | ThreadHost::Type::kRaster | ThreadHost::Type::kIo; + flutter::ThreadHost::ThreadHostConfig host_config(mask); + + ThreadHost thread_host(host_config); + TaskRunners task_runners = MakeTaskRunners(thread_label, thread_host); + auto android_context = + std::make_shared(environment, task_runners); + auto android_surface = + std::make_unique(android_context); + EXPECT_EQ(android_surface->GetOnscreenSurface(), nullptr); + android_surface->CreateSnapshotSurface(); + EXPECT_NE(android_surface->GetOnscreenSurface(), nullptr); +} + +TEST(AndroidContextGl, EnsureMakeCurrentChecksCurrentContextStatus) { + GrMockOptions main_context_options; + sk_sp main_context = + GrDirectContext::MakeMock(&main_context_options); + auto environment = fml::MakeRefCounted(); + std::string thread_label = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + + ThreadHost thread_host(ThreadHost::ThreadHostConfig( + thread_label, ThreadHost::Type::kUi | ThreadHost::Type::kRaster | + ThreadHost::Type::kIo)); + TaskRunners task_runners = MakeTaskRunners(thread_label, thread_host); + auto context = + std::make_unique(environment, task_runners); + + auto pbuffer_surface = context->CreatePbufferSurface(); + auto status = pbuffer_surface->MakeCurrent(); + EXPECT_EQ(AndroidEGLSurfaceMakeCurrentStatus::kSuccessMadeCurrent, status); + + // context already current, so status must reflect that. + status = pbuffer_surface->MakeCurrent(); + EXPECT_EQ(AndroidEGLSurfaceMakeCurrentStatus::kSuccessAlreadyCurrent, status); +} +} // namespace android +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_context_vk_impeller.cc b/flutter/engine/src/flutter/shell/platform/android/android_context_vk_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..98153318d14a39781c5c834fcd914cacbe60d83d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_context_vk_impeller.cc @@ -0,0 +1,88 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_context_vk_impeller.h" + +#include "flutter/fml/logging.h" +#include "flutter/fml/paths.h" +#include "flutter/impeller/entity/vk/entity_shaders_vk.h" +#include "flutter/impeller/entity/vk/framebuffer_blend_shaders_vk.h" +#include "flutter/impeller/entity/vk/modern_shaders_vk.h" +#include "flutter/impeller/renderer/backend/vulkan/context_vk.h" +#include "shell/platform/android/context/android_context.h" + +namespace flutter { + +static std::shared_ptr CreateImpellerContext( + const fml::RefPtr& vulkan_dylib, + const AndroidContext::ContextSettings& p_settings) { + if (!vulkan_dylib) { + VALIDATION_LOG << "Could not open the Vulkan dylib."; + return nullptr; + } + + std::vector> shader_mappings = { + std::make_shared(impeller_entity_shaders_vk_data, + impeller_entity_shaders_vk_length), + std::make_shared( + impeller_framebuffer_blend_shaders_vk_data, + impeller_framebuffer_blend_shaders_vk_length), + std::make_shared(impeller_modern_shaders_vk_data, + impeller_modern_shaders_vk_length), + }; + + auto instance_proc_addr = + vulkan_dylib->ResolveFunction( + "vkGetInstanceProcAddr"); + + if (!instance_proc_addr.has_value()) { + VALIDATION_LOG << "Could not setup Vulkan proc table."; + return nullptr; + } + + impeller::ContextVK::Settings settings; + settings.proc_address_callback = instance_proc_addr.value(); + settings.shader_libraries_data = std::move(shader_mappings); + settings.cache_directory = fml::paths::GetCachesDirectory(); + settings.enable_validation = p_settings.enable_validation; + settings.enable_gpu_tracing = p_settings.enable_gpu_tracing; + settings.enable_surface_control = p_settings.enable_surface_control; + settings.flags = p_settings.impeller_flags; + + auto context = impeller::ContextVK::Create(std::move(settings)); + + if (!p_settings.quiet) { + if (context && impeller::CapabilitiesVK::Cast(*context->GetCapabilities()) + .AreValidationsEnabled()) { + FML_LOG(IMPORTANT) << "Using the Impeller rendering backend (Vulkan with " + "Validation Layers)."; + } else { + FML_LOG(IMPORTANT) << "Using the Impeller rendering backend (Vulkan)."; + } + } + if (context && context->GetDriverInfo()->IsKnownBadDriver()) { + FML_LOG(INFO) + << "Known bad Vulkan driver encountered, falling back to OpenGLES."; + return nullptr; + } + + return context; +} + +AndroidContextVKImpeller::AndroidContextVKImpeller( + const AndroidContext::ContextSettings& settings) + : AndroidContext(AndroidRenderingAPI::kImpellerVulkan), + vulkan_dylib_(fml::NativeLibrary::Create("libvulkan.so")) { + auto impeller_context = CreateImpellerContext(vulkan_dylib_, settings); + SetImpellerContext(impeller_context); + is_valid_ = !!impeller_context; +} + +AndroidContextVKImpeller::~AndroidContextVKImpeller() = default; + +bool AndroidContextVKImpeller::IsValid() const { + return is_valid_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_context_vk_impeller.h b/flutter/engine/src/flutter/shell/platform/android/android_context_vk_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..5eb7b4ec6dc287a77151ba3b02027f59c48892df --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_context_vk_impeller.h @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_VK_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_VK_IMPELLER_H_ + +#include "flutter/fml/macros.h" +#include "flutter/fml/native_library.h" +#include "flutter/shell/platform/android/context/android_context.h" + +namespace flutter { + +class AndroidContextVKImpeller : public AndroidContext { + public: + explicit AndroidContextVKImpeller( + const AndroidContext::ContextSettings& settings); + + ~AndroidContextVKImpeller(); + + // |AndroidContext| + bool IsValid() const override; + + private: + fml::RefPtr vulkan_dylib_; + bool is_valid_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidContextVKImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_VK_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_display.cc b/flutter/engine/src/flutter/shell/platform/android/android_display.cc new file mode 100644 index 0000000000000000000000000000000000000000..9547341957b6726982a3823608e4e13dcd7e1a58 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_display.cc @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_display.h" + +namespace flutter { + +AndroidDisplay::AndroidDisplay( + std::shared_ptr jni_facade) + : Display(0, + jni_facade->GetDisplayRefreshRate(), + jni_facade->GetDisplayWidth(), + jni_facade->GetDisplayHeight(), + jni_facade->GetDisplayDensity()), + jni_facade_(std::move(jni_facade)) {} + +double AndroidDisplay::GetRefreshRate() const { + return jni_facade_->GetDisplayRefreshRate(); +} + +double AndroidDisplay::GetWidth() const { + return jni_facade_->GetDisplayWidth(); +} + +double AndroidDisplay::GetHeight() const { + return jni_facade_->GetDisplayHeight(); +} + +double AndroidDisplay::GetDevicePixelRatio() const { + return jni_facade_->GetDisplayDensity(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_display.h b/flutter/engine/src/flutter/shell/platform/android/android_display.h new file mode 100644 index 0000000000000000000000000000000000000000..c3eb9c33905d19723c1565a9202ee0059ea6e126 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_display.h @@ -0,0 +1,42 @@ +// 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_ANDROID_ANDROID_DISPLAY_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_DISPLAY_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/common/display.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { + +/// A |Display| that listens to refresh rate changes. +class AndroidDisplay : public Display { + public: + explicit AndroidDisplay(std::shared_ptr jni_facade); + ~AndroidDisplay() = default; + + // |Display| + double GetRefreshRate() const override; + + // |Display| + virtual double GetWidth() const override; + + // |Display| + virtual double GetHeight() const override; + + // |Display| + virtual double GetDevicePixelRatio() const override; + + private: + std::shared_ptr jni_facade_; + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidDisplay); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_DISPLAY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_egl_surface.cc b/flutter/engine/src/flutter/shell/platform/android/android_egl_surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..d4f3fc648eead4cb781c4d72b307d43c5b14a39a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_egl_surface.cc @@ -0,0 +1,181 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_egl_surface.h" + +#include +#include + +#include +#include + +#include "flutter/fml/trace_event.h" + +namespace flutter { + +void LogLastEGLError() { + struct EGLNameErrorPair { + const char* name; + EGLint code; + }; + +#define _EGL_ERROR_DESC(a) \ + { #a, a } + + const EGLNameErrorPair pairs[] = { + _EGL_ERROR_DESC(EGL_SUCCESS), + _EGL_ERROR_DESC(EGL_NOT_INITIALIZED), + _EGL_ERROR_DESC(EGL_BAD_ACCESS), + _EGL_ERROR_DESC(EGL_BAD_ALLOC), + _EGL_ERROR_DESC(EGL_BAD_ATTRIBUTE), + _EGL_ERROR_DESC(EGL_BAD_CONTEXT), + _EGL_ERROR_DESC(EGL_BAD_CONFIG), + _EGL_ERROR_DESC(EGL_BAD_CURRENT_SURFACE), + _EGL_ERROR_DESC(EGL_BAD_DISPLAY), + _EGL_ERROR_DESC(EGL_BAD_SURFACE), + _EGL_ERROR_DESC(EGL_BAD_MATCH), + _EGL_ERROR_DESC(EGL_BAD_PARAMETER), + _EGL_ERROR_DESC(EGL_BAD_NATIVE_PIXMAP), + _EGL_ERROR_DESC(EGL_BAD_NATIVE_WINDOW), + _EGL_ERROR_DESC(EGL_CONTEXT_LOST), + }; + +#undef _EGL_ERROR_DESC + + const auto count = sizeof(pairs) / sizeof(EGLNameErrorPair); + + EGLint last_error = eglGetError(); + + for (size_t i = 0; i < count; i++) { + if (last_error == pairs[i].code) { + FML_LOG(ERROR) << "EGL Error: " << pairs[i].name << " (" << pairs[i].code + << ")"; + return; + } + } + + FML_LOG(ERROR) << "Unknown EGL Error"; +} + +class AndroidEGLSurfaceDamage { + public: + void init(EGLDisplay display, EGLContext context) {} + + void SetDamageRegion(EGLDisplay display, + EGLSurface surface, + const std::optional& region) {} + + /// This was disabled after discussion in + /// https://github.com/flutter/flutter/issues/123353 + bool SupportsPartialRepaint() const { return false; } + + std::optional InitialDamage(EGLDisplay display, EGLSurface surface) { + return std::nullopt; + } + + bool SwapBuffersWithDamage(EGLDisplay display, + EGLSurface surface, + const std::optional& damage) { + return eglSwapBuffers(display, surface); + } +}; + +AndroidEGLSurface::AndroidEGLSurface(EGLSurface surface, + EGLDisplay display, + EGLContext context) + : surface_(surface), + display_(display), + context_(context), + damage_(std::make_unique()) { + damage_->init(display_, context); +} + +AndroidEGLSurface::~AndroidEGLSurface() { + [[maybe_unused]] auto result = eglDestroySurface(display_, surface_); + FML_DCHECK(result == EGL_TRUE); +} + +bool AndroidEGLSurface::IsValid() const { + return surface_ != EGL_NO_SURFACE; +} + +bool AndroidEGLSurface::IsContextCurrent() const { + EGLContext current_egl_context = eglGetCurrentContext(); + if (context_ != current_egl_context) { + return false; + } + + EGLDisplay current_egl_display = eglGetCurrentDisplay(); + if (display_ != current_egl_display) { + return false; + } + + EGLSurface draw_surface = eglGetCurrentSurface(EGL_DRAW); + if (draw_surface != surface_) { + return false; + } + + EGLSurface read_surface = eglGetCurrentSurface(EGL_READ); + if (read_surface != surface_) { + return false; + } + + return true; +} + +AndroidEGLSurfaceMakeCurrentStatus AndroidEGLSurface::MakeCurrent() const { + if (IsContextCurrent()) { + return AndroidEGLSurfaceMakeCurrentStatus::kSuccessAlreadyCurrent; + } + if (eglMakeCurrent(display_, surface_, surface_, context_) != EGL_TRUE) { + FML_LOG(ERROR) << "Could not make the context current"; + LogLastEGLError(); + return AndroidEGLSurfaceMakeCurrentStatus::kFailure; + } + return AndroidEGLSurfaceMakeCurrentStatus::kSuccessMadeCurrent; +} + +void AndroidEGLSurface::SetDamageRegion( + const std::optional& buffer_damage) { + damage_->SetDamageRegion(display_, surface_, buffer_damage); +} + +bool AndroidEGLSurface::SetPresentationTime( + const fml::TimePoint& presentation_time) { + if (presentation_time_proc_) { + const auto time_ns = presentation_time.ToEpochDelta().ToNanoseconds(); + return presentation_time_proc_(display_, surface_, time_ns); + } else { + return false; + } +} + +bool AndroidEGLSurface::SwapBuffers( + const std::optional& surface_damage) { + TRACE_EVENT0("flutter", "AndroidContextGL::SwapBuffers"); + return damage_->SwapBuffersWithDamage(display_, surface_, surface_damage); +} + +bool AndroidEGLSurface::SupportsPartialRepaint() const { + return damage_->SupportsPartialRepaint(); +} + +std::optional AndroidEGLSurface::InitialDamage() { + return damage_->InitialDamage(display_, surface_); +} + +SkISize AndroidEGLSurface::GetSize() const { + EGLint width = 0; + EGLint height = 0; + + if (!eglQuerySurface(display_, surface_, EGL_WIDTH, &width) || + !eglQuerySurface(display_, surface_, EGL_HEIGHT, &height)) { + FML_LOG(ERROR) << "Unable to query EGL surface size"; + LogLastEGLError(); + return SkISize::Make(0, 0); + } + return SkISize::Make(width, height); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_egl_surface.h b/flutter/engine/src/flutter/shell/platform/android/android_egl_surface.h new file mode 100644 index 0000000000000000000000000000000000000000..7ab45e03666dd8c9cbff628039aa4211f3e9f482 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_egl_surface.h @@ -0,0 +1,116 @@ +// 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_ANDROID_ANDROID_EGL_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_EGL_SURFACE_H_ + +#include +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/shell/platform/android/android_environment_gl.h" +#include "third_party/skia/include/core/SkRect.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// Holds an `EGLSurface` reference. +/// +/// +/// This can be used in conjunction to unique_ptr to provide better guarantees +/// about the lifespan of the `EGLSurface` object. +/// +class AndroidEGLSurfaceDamage; + +/// Result of calling MakeCurrent on AndroidEGLSurface. +enum class AndroidEGLSurfaceMakeCurrentStatus { + /// Success, the egl context for the surface was already current. + kSuccessAlreadyCurrent, + /// Success, the egl context for the surface made current. + kSuccessMadeCurrent, + /// Failed to make the egl context for the surface current. + kFailure, +}; + +void LogLastEGLError(); + +class AndroidEGLSurface { + public: + AndroidEGLSurface(EGLSurface surface, EGLDisplay display, EGLContext context); + + ~AndroidEGLSurface(); + + //---------------------------------------------------------------------------- + /// @return Whether the current `EGLSurface` reference is valid. That is, + /// if + /// the surface doesn't point to `EGL_NO_SURFACE`. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Binds the EGLContext context to the current rendering thread + /// and to the draw and read surface. + /// + /// @return Whether the surface was made current. + /// + AndroidEGLSurfaceMakeCurrentStatus MakeCurrent() const; + + //---------------------------------------------------------------------------- + /// + /// @return Whether target surface supports partial repaint. + /// + bool SupportsPartialRepaint() const; + + //---------------------------------------------------------------------------- + /// @brief This is the minimal area that needs to be repainted to get + /// correct result. + /// + /// With double or triple buffering this buffer content may lag behind + /// current front buffer and the rect accounts for accumulated damage. + /// + /// @return The area of current surface where it is behind front buffer. + /// + std::optional InitialDamage(); + + //---------------------------------------------------------------------------- + /// @brief Sets the damage region for current surface. Corresponds to + // eglSetDamageRegionKHR + void SetDamageRegion(const std::optional& buffer_damage); + + //---------------------------------------------------------------------------- + /// @brief Sets the presentation time for the current surface. This + // corresponds to calling eglPresentationTimeAndroid when + // available. + bool SetPresentationTime(const fml::TimePoint& presentation_time); + + //---------------------------------------------------------------------------- + /// @brief This only applies to on-screen surfaces such as those created + /// by `AndroidContextGL::CreateOnscreenSurface`. + /// + /// @return Whether the EGL surface color buffer was swapped. + /// + bool SwapBuffers(const std::optional& surface_damage); + + //---------------------------------------------------------------------------- + /// @return The size of an `EGLSurface`. + /// + SkISize GetSize() const; + + private: + /// Returns true if the EGLContext held is current for the display and surface + bool IsContextCurrent() const; + + const EGLSurface surface_; + const EGLDisplay display_; + const EGLContext context_; + std::unique_ptr damage_; + PFNEGLPRESENTATIONTIMEANDROIDPROC presentation_time_proc_ = nullptr; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_EGL_SURFACE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_environment_gl.cc b/flutter/engine/src/flutter/shell/platform/android/android_environment_gl.cc new file mode 100644 index 0000000000000000000000000000000000000000..88e81e6cec5aea33493581a833224429b51aa50e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_environment_gl.cc @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_environment_gl.h" + +namespace flutter { + +AndroidEnvironmentGL::AndroidEnvironmentGL() : display_(EGL_NO_DISPLAY) { + // Get the display. + display_ = eglGetDisplay(EGL_DEFAULT_DISPLAY); + + if (display_ == EGL_NO_DISPLAY) { + return; + } + + // Initialize the display connection. + if (eglInitialize(display_, nullptr, nullptr) != EGL_TRUE) { + return; + } + + valid_ = true; +} + +AndroidEnvironmentGL::~AndroidEnvironmentGL() { + // Disconnect the display if valid. + if (display_ != EGL_NO_DISPLAY) { + eglTerminate(display_); + } +} + +bool AndroidEnvironmentGL::IsValid() const { + return valid_; +} + +EGLDisplay AndroidEnvironmentGL::Display() const { + return display_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_environment_gl.h b/flutter/engine/src/flutter/shell/platform/android/android_environment_gl.h new file mode 100644 index 0000000000000000000000000000000000000000..299a6c5c22b7eb98dd7c01900382203ed57f234e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_environment_gl.h @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_ENVIRONMENT_GL_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_ENVIRONMENT_GL_H_ + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/ref_counted.h" + +#include + +namespace flutter { + +class AndroidEnvironmentGL + : public fml::RefCountedThreadSafe { + private: + // MakeRefCounted + AndroidEnvironmentGL(); + + // MakeRefCounted + ~AndroidEnvironmentGL(); + + public: + bool IsValid() const; + + EGLDisplay Display() const; + + private: + EGLDisplay display_; + bool valid_ = false; + + FML_FRIEND_MAKE_REF_COUNTED(AndroidEnvironmentGL); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(AndroidEnvironmentGL); + FML_DISALLOW_COPY_AND_ASSIGN(AndroidEnvironmentGL); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_ENVIRONMENT_GL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_exports.lst b/flutter/engine/src/flutter/shell/platform/android/android_exports.lst new file mode 100644 index 0000000000000000000000000000000000000000..198bff773dd74e8ff83dd97c250915840972bac6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_exports.lst @@ -0,0 +1,16 @@ +# 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. + +# Linker script that exports the minimal symbols required for libflutter.so + +{ + global: + JNI_OnLoad; + _binary_icudtl_dat_start; + _binary_icudtl_dat_size; + InternalFlutterGpu*; + kInternalFlutterGpu*; + local: + *; +}; diff --git a/flutter/engine/src/flutter/shell/platform/android/android_image_generator.cc b/flutter/engine/src/flutter/shell/platform/android/android_image_generator.cc new file mode 100644 index 0000000000000000000000000000000000000000..9ba4c050c9a9afa3a1045e20e23d27f9df831e5d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_image_generator.cc @@ -0,0 +1,213 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_image_generator.h" + +#include +#include + +#include +#include + +#include "flutter/fml/platform/android/jni_util.h" + +#include "third_party/skia/include/codec/SkCodecAnimation.h" + +namespace flutter { + +static fml::jni::ScopedJavaGlobalRef* g_flutter_jni_class = nullptr; +static jmethodID g_decode_image_method = nullptr; + +AndroidImageGenerator::~AndroidImageGenerator() = default; + +AndroidImageGenerator::AndroidImageGenerator(sk_sp data) + : data_(std::move(data)), image_info_(SkImageInfo::MakeUnknown(-1, -1)) {} + +const SkImageInfo& AndroidImageGenerator::GetInfo() { + header_decoded_latch_.Wait(); + return image_info_; +} + +unsigned int AndroidImageGenerator::GetFrameCount() const { + return 1; +} + +unsigned int AndroidImageGenerator::GetPlayCount() const { + return 1; +} + +const ImageGenerator::FrameInfo AndroidImageGenerator::GetFrameInfo( + unsigned int frame_index) { + return {.required_frame = std::nullopt, + .duration = 0, + .disposal_method = SkCodecAnimation::DisposalMethod::kKeep}; +} + +SkISize AndroidImageGenerator::GetScaledDimensions(float desired_scale) { + return GetInfo().dimensions(); +} + +bool AndroidImageGenerator::GetPixels(const SkImageInfo& info, + void* pixels, + size_t row_bytes, + unsigned int frame_index, + std::optional prior_frame) { + fully_decoded_latch_.Wait(); + + if (!software_decoded_data_) { + return false; + } + + if (kRGBA_8888_SkColorType != info.colorType()) { + return false; + } + + switch (info.alphaType()) { + case kOpaque_SkAlphaType: + if (kOpaque_SkAlphaType != GetInfo().alphaType()) { + return false; + } + break; + case kPremul_SkAlphaType: + break; + default: + return false; + } + + // TODO(bdero): Override `GetImage()` to use `SkImage::FromAHardwareBuffer` on + // API level 30+ once it's updated to do symbol lookups and not get + // preprocessed out in Skia. This will allow for avoiding this copy in + // cases where the result image doesn't need to be resized. + memcpy(pixels, software_decoded_data_->data(), + software_decoded_data_->size()); + return true; +} + +void AndroidImageGenerator::DecodeImage() { + DoDecodeImage(); + + header_decoded_latch_.Signal(); + fully_decoded_latch_.Signal(); +} + +void AndroidImageGenerator::DoDecodeImage() { + FML_DCHECK(g_flutter_jni_class); + FML_DCHECK(g_decode_image_method); + + // Call FlutterJNI.decodeImage + + JNIEnv* env = fml::jni::AttachCurrentThread(); + + // This task is run on the IO thread. Create a frame to ensure that all + // local JNI references used here are freed. + fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env); + + jobject direct_buffer = + env->NewDirectByteBuffer(const_cast(data_->data()), data_->size()); + + auto bitmap = std::make_unique>( + env, env->CallStaticObjectMethod(g_flutter_jni_class->obj(), + g_decode_image_method, direct_buffer, + reinterpret_cast(this))); + FML_CHECK(fml::jni::CheckException(env)); + + if (bitmap->is_null()) { + return; + } + + AndroidBitmapInfo info; + [[maybe_unused]] int status; + if ((status = AndroidBitmap_getInfo(env, bitmap->obj(), &info)) < 0) { + FML_DLOG(ERROR) << "Failed to get bitmap info, status=" << status; + return; + } + FML_DCHECK(info.format == ANDROID_BITMAP_FORMAT_RGBA_8888); + + // Lock the android buffer in a shared pointer + + void* pixel_lock; + if ((status = AndroidBitmap_lockPixels(env, bitmap->obj(), &pixel_lock)) < + 0) { + FML_DLOG(ERROR) << "Failed to lock pixels, error=" << status; + return; + } + + SkData::ReleaseProc on_release = [](const void* ptr, void* context) -> void { + fml::jni::ScopedJavaGlobalRef* bitmap = + reinterpret_cast*>(context); + auto env = fml::jni::AttachCurrentThread(); + AndroidBitmap_unlockPixels(env, bitmap->obj()); + delete bitmap; + }; + + software_decoded_data_ = SkData::MakeWithProc( + pixel_lock, info.width * info.height * sizeof(uint32_t), on_release, + bitmap.release()); +} + +bool AndroidImageGenerator::Register(JNIEnv* env) { + g_flutter_jni_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("io/flutter/embedding/engine/FlutterJNI")); + FML_DCHECK(!g_flutter_jni_class->is_null()); + + g_decode_image_method = env->GetStaticMethodID( + g_flutter_jni_class->obj(), "decodeImage", + "(Ljava/nio/ByteBuffer;J)Landroid/graphics/Bitmap;"); + FML_DCHECK(g_decode_image_method); + + static const JNINativeMethod header_decoded_method = { + .name = "nativeImageHeaderCallback", + .signature = "(JII)V", + .fnPtr = reinterpret_cast( + &AndroidImageGenerator::NativeImageHeaderCallback), + }; + if (env->RegisterNatives(g_flutter_jni_class->obj(), &header_decoded_method, + 1) != 0) { + FML_LOG(ERROR) + << "Failed to register FlutterJNI.nativeImageHeaderCallback method"; + return false; + } + + return true; +} + +std::shared_ptr AndroidImageGenerator::MakeFromData( + sk_sp data, + const fml::RefPtr& task_runner) { + std::shared_ptr generator( + new AndroidImageGenerator(std::move(data))); + + fml::TaskRunner::RunNowOrPostTask( + task_runner, [generator]() { generator->DecodeImage(); }); + + if (generator->IsValidImageData()) { + return generator; + } + + return nullptr; +} + +void AndroidImageGenerator::NativeImageHeaderCallback(JNIEnv* env, + jclass jcaller, + jlong generator_address, + int width, + int height) { + AndroidImageGenerator* generator = + reinterpret_cast(generator_address); + + generator->image_info_ = SkImageInfo::Make( + width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType); + generator->header_decoded_latch_.Signal(); +} + +bool AndroidImageGenerator::IsValidImageData() { + // The generator kicks off an IO task to decode everything, and calls to + // "GetInfo()" block until either the header has been decoded or decoding has + // failed, whichever is sooner. The decoder is initialized with a width and + // height of -1 and will update the dimensions if the image is able to be + // decoded. + return GetInfo().height() != -1; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_image_generator.h b/flutter/engine/src/flutter/shell/platform/android/android_image_generator.h new file mode 100644 index 0000000000000000000000000000000000000000..53cbadde10afc5768d9215c8667b8f4c021c7fd9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_image_generator.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_ANDROID_ANDROID_IMAGE_GENERATOR_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_IMAGE_GENERATOR_H_ + +#include + +#include "flutter/fml/memory/ref_ptr.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/fml/task_runner.h" +#include "flutter/lib/ui/painting/image_generator.h" + +namespace flutter { + +class AndroidImageGenerator : public ImageGenerator { + private: + explicit AndroidImageGenerator(sk_sp buffer); + + public: + ~AndroidImageGenerator(); + + // |ImageGenerator| + const SkImageInfo& GetInfo() override; + + // |ImageGenerator| + unsigned int GetFrameCount() const override; + + // |ImageGenerator| + unsigned int GetPlayCount() const override; + + // |ImageGenerator| + const ImageGenerator::FrameInfo GetFrameInfo( + unsigned int frame_index) override; + + // |ImageGenerator| + SkISize GetScaledDimensions(float desired_scale) override; + + // |ImageGenerator| + bool GetPixels(const SkImageInfo& info, + void* pixels, + size_t row_bytes, + unsigned int frame_index, + std::optional prior_frame) override; + + void DecodeImage(); + + static bool Register(JNIEnv* env); + + static std::shared_ptr MakeFromData( + sk_sp data, + const fml::RefPtr& task_runner); + + static void NativeImageHeaderCallback(JNIEnv* env, + jclass jcaller, + jlong generator_pointer, + int width, + int height); + + private: + sk_sp data_; + sk_sp software_decoded_data_; + + SkImageInfo image_info_; + + /// Blocks until the header of the image has been decoded and the image + /// dimensions have been determined. + fml::ManualResetWaitableEvent header_decoded_latch_; + + /// Blocks until the image has been fully decoded. + fml::ManualResetWaitableEvent fully_decoded_latch_; + + void DoDecodeImage(); + + bool IsValidImageData(); + + FML_DISALLOW_COPY_ASSIGN_AND_MOVE(AndroidImageGenerator); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_IMAGE_GENERATOR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_rendering_selector.h b/flutter/engine/src/flutter/shell/platform/android/android_rendering_selector.h new file mode 100644 index 0000000000000000000000000000000000000000..63220fb85814dbb1827f4eae9ab8e6559d9a4bef --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_rendering_selector.h @@ -0,0 +1,20 @@ +// 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_ANDROID_ANDROID_RENDERING_SELECTOR_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_RENDERING_SELECTOR_H_ + +namespace flutter { + +// The combination of targeted graphics API and Impeller support. +enum class AndroidRenderingAPI { + kSoftware, + kImpellerOpenGLES, + kImpellerVulkan, + kSkiaOpenGLES +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_RENDERING_SELECTOR_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_shell_holder.cc b/flutter/engine/src/flutter/shell/platform/android/android_shell_holder.cc new file mode 100644 index 0000000000000000000000000000000000000000..58a0eb0707d98adce6430fbe9f47d26930682235 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_shell_holder.cc @@ -0,0 +1,370 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#define FML_USED_ON_EMBEDDER + +#include +#include +#include +#include +#include + +#include +#include + +#include "common/settings.h" +#include "flutter/fml/cpu_affinity.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/message_loop.h" +#include "flutter/lib/ui/painting/image_generator_registry.h" +#include "flutter/shell/common/rasterizer.h" +#include "flutter/shell/common/run_configuration.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/shell/platform/android/android_display.h" +#include "flutter/shell/platform/android/android_image_generator.h" +#include "flutter/shell/platform/android/android_rendering_selector.h" +#include "flutter/shell/platform/android/android_shell_holder.h" +#include "flutter/shell/platform/android/context/android_context.h" +#include "flutter/shell/platform/android/platform_view_android.h" + +namespace flutter { + +/// Inheriting ThreadConfigurer and use Android platform thread API to configure +/// the thread priorities +static void AndroidPlatformThreadConfigSetter( + const fml::Thread::ThreadConfig& config) { + // set thread name + fml::Thread::SetCurrentThreadName(config); + // set thread priority + switch (config.priority) { + case fml::Thread::ThreadPriority::kBackground: { + fml::RequestAffinity(fml::CpuAffinity::kEfficiency); + if (::setpriority(PRIO_PROCESS, 0, 10) != 0) { + FML_LOG(ERROR) << "Failed to set IO task runner priority"; + } + break; + } + case fml::Thread::ThreadPriority::kDisplay: { + fml::RequestAffinity(fml::CpuAffinity::kNotEfficiency); + if (::setpriority(PRIO_PROCESS, 0, -1) != 0) { + FML_LOG(ERROR) << "Failed to set UI task runner priority"; + } + break; + } + case fml::Thread::ThreadPriority::kRaster: { + fml::RequestAffinity(fml::CpuAffinity::kNotEfficiency); + // Android describes -8 as "most important display threads, for + // compositing the screen and retrieving input events". Conservatively + // set the raster thread to slightly lower priority than it. + if (::setpriority(PRIO_PROCESS, 0, -5) != 0) { + // Defensive fallback. Depending on the OEM, it may not be possible + // to set priority to -5. + if (::setpriority(PRIO_PROCESS, 0, -2) != 0) { + FML_LOG(ERROR) << "Failed to set raster task runner priority"; + } + } + break; + } + default: + fml::RequestAffinity(fml::CpuAffinity::kNotPerformance); + if (::setpriority(PRIO_PROCESS, 0, 0) != 0) { + FML_LOG(ERROR) << "Failed to set priority"; + } + } +} +static PlatformData GetDefaultPlatformData() { + PlatformData platform_data; + platform_data.lifecycle_state = "AppLifecycleState.detached"; + return platform_data; +} + +AndroidShellHolder::AndroidShellHolder( + const flutter::Settings& settings, + std::shared_ptr jni_facade, + AndroidRenderingAPI android_rendering_api) + : settings_(settings), + jni_facade_(jni_facade), + android_rendering_api_(android_rendering_api) { + static size_t thread_host_count = 1; + auto thread_label = std::to_string(thread_host_count++); + + auto mask = ThreadHost::Type::kRaster | ThreadHost::Type::kIo; + if (!settings.merged_platform_ui_thread) { + mask |= ThreadHost::Type::kUi; + } + + flutter::ThreadHost::ThreadHostConfig host_config( + thread_label, mask, AndroidPlatformThreadConfigSetter); + host_config.ui_config = fml::Thread::ThreadConfig( + flutter::ThreadHost::ThreadHostConfig::MakeThreadName( + flutter::ThreadHost::Type::kUi, thread_label), + fml::Thread::ThreadPriority::kDisplay); + host_config.raster_config = fml::Thread::ThreadConfig( + flutter::ThreadHost::ThreadHostConfig::MakeThreadName( + flutter::ThreadHost::Type::kRaster, thread_label), + fml::Thread::ThreadPriority::kRaster); + host_config.io_config = fml::Thread::ThreadConfig( + flutter::ThreadHost::ThreadHostConfig::MakeThreadName( + flutter::ThreadHost::Type::kIo, thread_label), + fml::Thread::ThreadPriority::kNormal); + + thread_host_ = std::make_shared(host_config); + + fml::WeakPtr weak_platform_view; + AndroidRenderingAPI rendering_api = android_rendering_api_; + Shell::CreateCallback on_create_platform_view = + [&jni_facade, &weak_platform_view, rendering_api](Shell& shell) { + std::unique_ptr platform_view_android; + platform_view_android = std::make_unique( + shell, // delegate + shell.GetTaskRunners(), // task runners + jni_facade, // JNI interop + rendering_api // rendering API + ); + weak_platform_view = platform_view_android->GetWeakPtr(); + return platform_view_android; + }; + + Shell::CreateCallback on_create_rasterizer = [](Shell& shell) { + return std::make_unique(shell); + }; + + // The current thread will be used as the platform thread. Ensure that the + // message loop is initialized. + fml::MessageLoop::EnsureInitializedForCurrentThread(); + fml::RefPtr raster_runner; + fml::RefPtr ui_runner; + fml::RefPtr io_runner; + fml::RefPtr platform_runner = + fml::MessageLoop::GetCurrent().GetTaskRunner(); + raster_runner = thread_host_->raster_thread->GetTaskRunner(); + if (settings.merged_platform_ui_thread) { + ui_runner = platform_runner; + } else { + ui_runner = thread_host_->ui_thread->GetTaskRunner(); + } + io_runner = thread_host_->io_thread->GetTaskRunner(); + + flutter::TaskRunners task_runners(thread_label, // label + platform_runner, // platform + raster_runner, // raster + ui_runner, // ui + io_runner // io + ); + + shell_ = + Shell::Create(GetDefaultPlatformData(), // window data + task_runners, // task runners + settings_, // settings + on_create_platform_view, // platform view create callback + on_create_rasterizer // rasterizer create callback + ); + + if (shell_) { + shell_->GetDartVM()->GetConcurrentMessageLoop()->PostTaskToAllWorkers([]() { + if (::setpriority(PRIO_PROCESS, gettid(), 1) != 0) { + FML_LOG(ERROR) << "Failed to set Workers task runner priority"; + } + }); + + shell_->RegisterImageDecoder( + [runner = task_runners.GetIOTaskRunner()](sk_sp buffer) { + return AndroidImageGenerator::MakeFromData(std::move(buffer), runner); + }, + -1); + FML_DLOG(INFO) << "Registered Android SDK image decoder (API level 28+)"; + } + + platform_view_ = weak_platform_view; + FML_DCHECK(platform_view_); + is_valid_ = shell_ != nullptr; +} + +AndroidShellHolder::AndroidShellHolder( + const Settings& settings, + const std::shared_ptr& jni_facade, + const std::shared_ptr& thread_host, + std::unique_ptr shell, + std::unique_ptr apk_asset_provider, + const fml::WeakPtr& platform_view, + AndroidRenderingAPI rendering_api) + : settings_(settings), + jni_facade_(jni_facade), + platform_view_(platform_view), + thread_host_(thread_host), + shell_(std::move(shell)), + apk_asset_provider_(std::move(apk_asset_provider)), + android_rendering_api_(rendering_api) { + FML_DCHECK(jni_facade); + FML_DCHECK(shell_); + FML_DCHECK(shell_->IsSetup()); + FML_DCHECK(platform_view_); + FML_DCHECK(thread_host_); + is_valid_ = shell_ != nullptr; +} + +AndroidShellHolder::~AndroidShellHolder() { + shell_.reset(); + thread_host_.reset(); +} + +bool AndroidShellHolder::IsValid() const { + return is_valid_; +} + +const flutter::Settings& AndroidShellHolder::GetSettings() const { + return settings_; +} + +std::unique_ptr AndroidShellHolder::Spawn( + std::shared_ptr jni_facade, + const std::string& entrypoint, + const std::string& libraryUrl, + const std::string& initial_route, + const std::vector& entrypoint_args, + int64_t engine_id) const { + FML_DCHECK(shell_ && shell_->IsSetup()) + << "A new Shell can only be spawned " + "if the current Shell is properly constructed"; + + // Pull out the new PlatformViewAndroid from the new Shell to feed to it to + // the new AndroidShellHolder. + // + // It's a weak pointer because it's owned by the Shell (which we're also) + // making below. And the AndroidShellHolder then owns the Shell. + fml::WeakPtr weak_platform_view; + + // Take out the old AndroidContext to reuse inside the PlatformViewAndroid + // of the new Shell. + PlatformViewAndroid* android_platform_view = platform_view_.get(); + // There's some indirection with platform_view_ being a weak pointer but + // we just checked that the shell_ exists above and a valid shell is the + // owner of the platform view so this weak pointer always exists. + FML_DCHECK(android_platform_view); + std::shared_ptr android_context = + android_platform_view->GetAndroidContext(); + FML_DCHECK(android_context); + + // This is a synchronous call, so the captures don't have race checks. + Shell::CreateCallback on_create_platform_view = + [&jni_facade, android_context, &weak_platform_view](Shell& shell) { + std::unique_ptr platform_view_android; + platform_view_android = std::make_unique( + shell, // delegate + shell.GetTaskRunners(), // task runners + jni_facade, // JNI interop + android_context // Android context + ); + weak_platform_view = platform_view_android->GetWeakPtr(); + return platform_view_android; + }; + + Shell::CreateCallback on_create_rasterizer = [](Shell& shell) { + return std::make_unique(shell); + }; + + auto config = BuildRunConfiguration(entrypoint, libraryUrl, entrypoint_args); + if (!config) { + // If the RunConfiguration was null, the kernel blob wasn't readable. + // Fail the whole thing. + return nullptr; + } + config->SetEngineId(engine_id); + + std::unique_ptr shell = + shell_->Spawn(std::move(config.value()), initial_route, + on_create_platform_view, on_create_rasterizer); + + return std::unique_ptr(new AndroidShellHolder( + GetSettings(), jni_facade, thread_host_, std::move(shell), + apk_asset_provider_->Clone(), weak_platform_view, + android_context->RenderingApi())); +} + +void AndroidShellHolder::Launch( + std::unique_ptr apk_asset_provider, + const std::string& entrypoint, + const std::string& libraryUrl, + const std::vector& entrypoint_args, + int64_t engine_id) { + if (!IsValid()) { + return; + } + + apk_asset_provider_ = std::move(apk_asset_provider); + auto config = BuildRunConfiguration(entrypoint, libraryUrl, entrypoint_args); + if (!config) { + return; + } + config->SetEngineId(engine_id); + UpdateDisplayMetrics(); + shell_->RunEngine(std::move(config.value())); +} + +Rasterizer::Screenshot AndroidShellHolder::Screenshot( + Rasterizer::ScreenshotType type, + bool base64_encode) { + if (!IsValid()) { + return {nullptr, SkISize::MakeEmpty(), "", + Rasterizer::ScreenshotFormat::kUnknown}; + } + return shell_->Screenshot(type, base64_encode); +} + +fml::WeakPtr AndroidShellHolder::GetPlatformView() { + FML_DCHECK(platform_view_); + return platform_view_; +} + +void AndroidShellHolder::NotifyLowMemoryWarning() { + FML_DCHECK(shell_); + shell_->NotifyLowMemoryWarning(); +} + +std::optional AndroidShellHolder::BuildRunConfiguration( + const std::string& entrypoint, + const std::string& libraryUrl, + const std::vector& entrypoint_args) const { + std::unique_ptr isolate_configuration; + if (flutter::DartVM::IsRunningPrecompiledCode()) { + isolate_configuration = IsolateConfiguration::CreateForAppSnapshot(); + } else { + std::unique_ptr kernel_blob = + fml::FileMapping::CreateReadOnly( + GetSettings().application_kernel_asset); + if (!kernel_blob) { + FML_DLOG(ERROR) << "Unable to load the kernel blob asset."; + return std::nullopt; + } + isolate_configuration = + IsolateConfiguration::CreateForKernel(std::move(kernel_blob)); + } + + RunConfiguration config(std::move(isolate_configuration)); + config.AddAssetResolver(apk_asset_provider_->Clone()); + + { + if (!entrypoint.empty() && !libraryUrl.empty()) { + config.SetEntrypointAndLibrary(entrypoint, libraryUrl); + } else if (!entrypoint.empty()) { + config.SetEntrypoint(entrypoint); + } + if (!entrypoint_args.empty()) { + config.SetEntrypointArgs(entrypoint_args); + } + } + return config; +} + +void AndroidShellHolder::UpdateDisplayMetrics() { + std::vector> displays; + displays.push_back(std::make_unique(jni_facade_)); + shell_->OnDisplayUpdates(std::move(displays)); +} + +bool AndroidShellHolder::IsSurfaceControlEnabled() { + return GetPlatformView()->IsSurfaceControlEnabled(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_shell_holder.h b/flutter/engine/src/flutter/shell/platform/android/android_shell_holder.h new file mode 100644 index 0000000000000000000000000000000000000000..d3a88006f8cb6b187229244d062a30dbaa8b571f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_shell_holder.h @@ -0,0 +1,154 @@ +// 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_ANDROID_ANDROID_SHELL_HOLDER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SHELL_HOLDER_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/common/run_configuration.h" +#include "flutter/shell/common/shell.h" +#include "flutter/shell/common/thread_host.h" +#include "flutter/shell/platform/android/android_rendering_selector.h" +#include "flutter/shell/platform/android/apk_asset_provider.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/platform_view_android.h" + +namespace flutter { + +//---------------------------------------------------------------------------- +/// @brief This is the Android owner of the core engine Shell. +/// +/// @details This is the top orchestrator class on the C++ side for the +/// Android embedding. It corresponds to a FlutterEngine on the +/// Java side. This class is in C++ because the Shell is in +/// C++ and an Android orchestrator needs to exist to +/// compose it with other Android specific C++ components such as +/// the PlatformViewAndroid. This composition of many-to-one +/// C++ components would be difficult to do through JNI whereas +/// a FlutterEngine and AndroidShellHolder has a 1:1 relationship. +/// +/// Technically, the FlutterJNI class owns this AndroidShellHolder +/// class instance, but the FlutterJNI class is meant to be mostly +/// static and has minimal state to perform the C++ pointer <-> +/// Java class instance translation. +/// +class AndroidShellHolder { + public: + AndroidShellHolder(const flutter::Settings& settings, + std::shared_ptr jni_facade, + AndroidRenderingAPI android_rendering_api); + + ~AndroidShellHolder(); + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief This is a factory for a derived AndroidShellHolder from an + /// existing AndroidShellHolder. + /// + /// @details Creates one Shell from another Shell where the created + /// Shell takes the opportunity to share any internal components + /// it can. This results is a Shell that has a smaller startup + /// time cost and a smaller memory footprint than an Shell created + /// with a Create function. + /// + /// The new Shell is returned in a new AndroidShellHolder + /// instance. + /// + /// The new Shell's flutter::Settings cannot be changed from that + /// of the initial Shell. The RunConfiguration subcomponent can + /// be changed however in the spawned Shell to run a different + /// entrypoint than the existing shell. + /// + /// Since the AndroidShellHolder both binds downwards to a Shell + /// and also upwards to JNI callbacks that the PlatformViewAndroid + /// makes, the JNI instance holding this AndroidShellHolder should + /// be created first to supply the jni_facade callback. + /// + /// @param[in] jni_facade this argument should be the JNI callback facade of + /// a new JNI instance meant to hold this AndroidShellHolder. + /// + /// @returns A new AndroidShellHolder containing a new Shell. Returns + /// nullptr when a new Shell can't be created. + /// + std::unique_ptr Spawn( + std::shared_ptr jni_facade, + const std::string& entrypoint, + const std::string& libraryUrl, + const std::string& initial_route, + const std::vector& entrypoint_args, + int64_t engine_id) const; + + void Launch(std::unique_ptr apk_asset_provider, + const std::string& entrypoint, + const std::string& libraryUrl, + const std::vector& entrypoint_args, + int64_t engine_id); + + const flutter::Settings& GetSettings() const; + + fml::WeakPtr GetPlatformView(); + + bool IsSurfaceControlEnabled(); + + Rasterizer::Screenshot Screenshot(Rasterizer::ScreenshotType type, + bool base64_encode); + + void NotifyLowMemoryWarning(); + + const std::shared_ptr& GetPlatformMessageHandler() + const { + return shell_->GetPlatformMessageHandler(); + } + + void UpdateDisplayMetrics(); + + // Visible for testing. + const std::unique_ptr& GetShellForTesting() const { return shell_; } + + private: + const flutter::Settings settings_; + const std::shared_ptr jni_facade_; + fml::WeakPtr platform_view_; + std::shared_ptr thread_host_; + std::unique_ptr shell_; + bool is_valid_ = false; + uint64_t next_pointer_flow_id_ = 0; + std::unique_ptr apk_asset_provider_; + const AndroidRenderingAPI android_rendering_api_; + + //---------------------------------------------------------------------------- + /// @brief Constructor with its components injected. + /// + /// @details This is similar to the standard constructor, except its + /// members were constructed elsewhere and injected. + /// + /// All injected components must be non-null and valid. + /// + /// Used when constructing the Shell from the inside out when + /// spawning from an existing Shell. + /// + AndroidShellHolder(const flutter::Settings& settings, + const std::shared_ptr& jni_facade, + const std::shared_ptr& thread_host, + std::unique_ptr shell, + std::unique_ptr apk_asset_provider, + const fml::WeakPtr& platform_view, + AndroidRenderingAPI rendering_api); + static void ThreadDestructCallback(void* value); + std::optional BuildRunConfiguration( + const std::string& entrypoint, + const std::string& libraryUrl, + const std::vector& entrypoint_args) const; + + bool IsNDKImageDecoderAvailable(); + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidShellHolder); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SHELL_HOLDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_shell_holder_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/android_shell_holder_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..1b324ffbb63210bc1155446811a9013a2ede3b94 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_shell_holder_unittests.cc @@ -0,0 +1,218 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/shell/platform/android/android_shell_holder.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { +namespace testing { +namespace { +class MockPlatformViewAndroidJNI : public PlatformViewAndroidJNI { + public: + MOCK_METHOD(void, + FlutterViewHandlePlatformMessage, + (std::unique_ptr message, + int responseId), + (override)); + MOCK_METHOD(void, + FlutterViewHandlePlatformMessageResponse, + (int responseId, std::unique_ptr data), + (override)); + MOCK_METHOD(void, + FlutterViewUpdateSemantics, + (std::vector buffer, + std::vector strings, + std::vector> string_attribute_args), + (override)); + MOCK_METHOD(void, + FlutterViewUpdateCustomAccessibilityActions, + (std::vector actions_buffer, + std::vector strings), + (override)); + MOCK_METHOD(void, FlutterViewOnFirstFrame, (), (override)); + MOCK_METHOD(void, FlutterViewOnPreEngineRestart, (), (override)); + MOCK_METHOD(void, + SurfaceTextureAttachToGLContext, + (JavaLocalRef surface_texture, int textureId), + (override)); + MOCK_METHOD(bool, + SurfaceTextureShouldUpdate, + (JavaLocalRef surface_texture), + (override)); + MOCK_METHOD(void, + SurfaceTextureUpdateTexImage, + (JavaLocalRef surface_texture), + (override)); + MOCK_METHOD(SkM44, + SurfaceTextureGetTransformMatrix, + (JavaLocalRef surface_texture), + (override)); + MOCK_METHOD(void, + SurfaceTextureDetachFromGLContext, + (JavaLocalRef surface_texture), + (override)); + MOCK_METHOD(JavaLocalRef, + ImageProducerTextureEntryAcquireLatestImage, + (JavaLocalRef image_texture_entry), + (override)); + MOCK_METHOD(JavaLocalRef, + ImageGetHardwareBuffer, + (JavaLocalRef image), + (override)); + MOCK_METHOD(void, ImageClose, (JavaLocalRef image), (override)); + MOCK_METHOD(void, + HardwareBufferClose, + (JavaLocalRef hardware_buffer), + (override)); + MOCK_METHOD(void, + FlutterViewOnDisplayPlatformView, + (int view_id, + int x, + int y, + int width, + int height, + int viewWidth, + int viewHeight, + MutatorsStack mutators_stack), + (override)); + MOCK_METHOD(void, + FlutterViewDisplayOverlaySurface, + (int surface_id, int x, int y, int width, int height), + (override)); + MOCK_METHOD(void, FlutterViewBeginFrame, (), (override)); + MOCK_METHOD(void, FlutterViewEndFrame, (), (override)); + MOCK_METHOD(std::unique_ptr, + FlutterViewCreateOverlaySurface, + (), + (override)); + MOCK_METHOD(void, FlutterViewDestroyOverlaySurfaces, (), (override)); + MOCK_METHOD(ASurfaceTransaction*, createTransaction, (), (override)); + MOCK_METHOD(void, swapTransaction, (), (override)); + MOCK_METHOD(void, applyTransaction, (), (override)); + MOCK_METHOD(void, destroyOverlaySurface2, (), (override)); + MOCK_METHOD(std::unique_ptr, + createOverlaySurface2, + (), + (override)); + MOCK_METHOD(void, + onDisplayPlatformView2, + (int32_t view_id, + int32_t x, + int32_t y, + int32_t width, + int32_t height, + int32_t viewWidth, + int32_t viewHeight, + MutatorsStack mutators_stack), + (override)); + MOCK_METHOD(void, onEndFrame2, (), (override)); + MOCK_METHOD(void, showOverlaySurface2, (), (override)); + MOCK_METHOD(void, hideOverlaySurface2, (), (override)); + MOCK_METHOD(std::unique_ptr>, + FlutterViewComputePlatformResolvedLocale, + (std::vector supported_locales_data), + (override)); + MOCK_METHOD(double, GetDisplayRefreshRate, (), (override)); + MOCK_METHOD(double, GetDisplayWidth, (), (override)); + MOCK_METHOD(double, GetDisplayHeight, (), (override)); + MOCK_METHOD(double, GetDisplayDensity, (), (override)); + MOCK_METHOD(bool, + RequestDartDeferredLibrary, + (int loading_unit_id), + (override)); + MOCK_METHOD(double, + FlutterViewGetScaledFontSize, + (double font_size, int configuration_id), + (const, override)); +}; + +class MockPlatformMessageResponse : public PlatformMessageResponse { + public: + static fml::RefPtr Create() { + return fml::AdoptRef(new MockPlatformMessageResponse()); + } + MOCK_METHOD(void, Complete, (std::unique_ptr data), (override)); + MOCK_METHOD(void, CompleteEmpty, (), (override)); +}; +} // namespace + +TEST(AndroidShellHolder, Create) { + Settings settings; + settings.enable_software_rendering = false; + auto jni = std::make_shared(); + auto holder = std::make_unique( + settings, jni, AndroidRenderingAPI::kImpellerOpenGLES); + EXPECT_NE(holder.get(), nullptr); + EXPECT_TRUE(holder->IsValid()); + EXPECT_NE(holder->GetPlatformView().get(), nullptr); + auto window = fml::MakeRefCounted( + nullptr, /*is_fake_window=*/true); + holder->GetPlatformView()->NotifyCreated(window); +} + +TEST(AndroidShellHolder, HandlePlatformMessage) { + Settings settings; + settings.enable_software_rendering = false; + auto jni = std::make_shared(); + auto holder = std::make_unique( + settings, jni, AndroidRenderingAPI::kImpellerOpenGLES); + EXPECT_NE(holder.get(), nullptr); + EXPECT_TRUE(holder->IsValid()); + EXPECT_NE(holder->GetPlatformView().get(), nullptr); + auto window = fml::MakeRefCounted( + nullptr, /*is_fake_window=*/true); + holder->GetPlatformView()->NotifyCreated(window); + EXPECT_TRUE(holder->GetPlatformMessageHandler()); + size_t data_size = 4; + fml::MallocMapping bytes = + fml::MallocMapping(static_cast(malloc(data_size)), data_size); + fml::RefPtr response = + MockPlatformMessageResponse::Create(); + auto message = std::make_unique( + /*channel=*/"foo", /*data=*/std::move(bytes), /*response=*/response); + int response_id = 1; + EXPECT_CALL(*jni, + FlutterViewHandlePlatformMessage(::testing::_, response_id)); + EXPECT_CALL(*response, CompleteEmpty()); + holder->GetPlatformMessageHandler()->HandlePlatformMessage( + std::move(message)); + holder->GetPlatformMessageHandler() + ->InvokePlatformMessageEmptyResponseCallback(response_id); +} + +TEST(AndroidShellHolder, CreateWithMergedPlatformAndUIThread) { + Settings settings; + auto jni = std::make_shared(); + auto holder = std::make_unique( + settings, jni, AndroidRenderingAPI::kImpellerOpenGLES); + auto window = fml::MakeRefCounted( + nullptr, /*is_fake_window=*/true); + holder->GetPlatformView()->NotifyCreated(window); + + EXPECT_EQ( + holder->GetShellForTesting()->GetTaskRunners().GetUITaskRunner(), + holder->GetShellForTesting()->GetTaskRunners().GetPlatformTaskRunner()); +} + +TEST(AndroidShellHolder, CreateWithUnMergedPlatformAndUIThread) { + Settings settings; + settings.merged_platform_ui_thread = false; + auto jni = std::make_shared(); + auto holder = std::make_unique( + settings, jni, AndroidRenderingAPI::kImpellerOpenGLES); + auto window = fml::MakeRefCounted( + nullptr, /*is_fake_window=*/true); + holder->GetPlatformView()->NotifyCreated(window); + + EXPECT_NE( + holder->GetShellForTesting()->GetTaskRunners().GetUITaskRunner(), + holder->GetShellForTesting()->GetTaskRunners().GetPlatformTaskRunner()); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_impeller.cc b/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..918bbef665544c9befa863e48340154fb894f39c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_impeller.cc @@ -0,0 +1,190 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_surface_gl_impeller.h" + +#include "flutter/fml/logging.h" +#include "flutter/impeller/toolkit/egl/surface.h" +#include "flutter/shell/gpu/gpu_surface_gl_impeller.h" + +namespace flutter { + +AndroidSurfaceGLImpeller::AndroidSurfaceGLImpeller( + const std::shared_ptr& android_context) + : android_context_(android_context) { + offscreen_surface_ = android_context_->CreateOffscreenSurface(); + + if (!offscreen_surface_) { + FML_DLOG(ERROR) << "Could not create offscreen surface."; + return; + } + + // The onscreen surface will be acquired once the native window is set. + + is_valid_ = true; +} + +AndroidSurfaceGLImpeller::~AndroidSurfaceGLImpeller() = default; + +// |AndroidSurface| +bool AndroidSurfaceGLImpeller::IsValid() const { + return is_valid_; +} + +// |AndroidSurface| +std::unique_ptr AndroidSurfaceGLImpeller::CreateGPUSurface( + GrDirectContext* gr_context) { + auto surface = std::make_unique( + this, // delegate + android_context_->GetImpellerContext(), // context + true // render to surface + ); + if (!surface->IsValid()) { + return nullptr; + } + return surface; +} + +// |AndroidSurface| +void AndroidSurfaceGLImpeller::TeardownOnScreenContext() { + GLContextClearCurrent(); + onscreen_surface_.reset(); +} + +// |AndroidSurface| +bool AndroidSurfaceGLImpeller::OnScreenSurfaceResize(const SkISize& size) { + // The size is unused. It was added only for iOS where the sizes were + // necessary to re-create auxiliary buffers (stencil, depth, etc.). + return RecreateOnscreenSurfaceAndMakeOnscreenContextCurrent(); +} + +// |AndroidSurface| +bool AndroidSurfaceGLImpeller::ResourceContextMakeCurrent() { + if (!offscreen_surface_) { + return false; + } + return android_context_->ResourceContextMakeCurrent(offscreen_surface_.get()); +} + +// |AndroidSurface| +bool AndroidSurfaceGLImpeller::ResourceContextClearCurrent() { + return android_context_->ResourceContextClearCurrent(); +} + +// |AndroidSurface| +bool AndroidSurfaceGLImpeller::SetNativeWindow( + fml::RefPtr window, + const std::shared_ptr& jni_facade) { + native_window_ = std::move(window); + return RecreateOnscreenSurfaceAndMakeOnscreenContextCurrent(); +} + +// |AndroidSurface| +std::unique_ptr AndroidSurfaceGLImpeller::CreateSnapshotSurface() { + if (!onscreen_surface_ || !onscreen_surface_->IsValid()) { + onscreen_surface_ = android_context_->CreateOffscreenSurface(); + if (!onscreen_surface_) { + FML_DLOG(ERROR) << "Could not create offscreen surface for snapshot."; + return nullptr; + } + } + // Make the snapshot surface current because constucting a + // GPUSurfaceGLImpeller and its AiksContext may invoke graphics APIs. + if (!android_context_->OnscreenContextMakeCurrent(onscreen_surface_.get())) { + FML_DLOG(ERROR) << "Could not make snapshot surface current."; + return nullptr; + } + return std::make_unique( + this, // delegate + android_context_->GetImpellerContext(), // context + true // render to surface + ); +} + +// |AndroidSurface| +std::shared_ptr +AndroidSurfaceGLImpeller::GetImpellerContext() { + return android_context_->GetImpellerContext(); +} + +// |GPUSurfaceGLDelegate| +std::unique_ptr +AndroidSurfaceGLImpeller::GLContextMakeCurrent() { + return std::make_unique(OnGLContextMakeCurrent()); +} + +bool AndroidSurfaceGLImpeller::OnGLContextMakeCurrent() { + if (!onscreen_surface_) { + return false; + } + + return android_context_->OnscreenContextMakeCurrent(onscreen_surface_.get()); +} + +// |GPUSurfaceGLDelegate| +bool AndroidSurfaceGLImpeller::GLContextClearCurrent() { + if (!onscreen_surface_) { + return false; + } + + return android_context_->OnscreenContextClearCurrent(); +} + +// |GPUSurfaceGLDelegate| +SurfaceFrame::FramebufferInfo +AndroidSurfaceGLImpeller::GLContextFramebufferInfo() const { + auto info = SurfaceFrame::FramebufferInfo{}; + info.supports_readback = true; + info.supports_partial_repaint = false; + return info; +} + +// |GPUSurfaceGLDelegate| +void AndroidSurfaceGLImpeller::GLContextSetDamageRegion( + const std::optional& region) { + // Not supported. +} + +// |GPUSurfaceGLDelegate| +bool AndroidSurfaceGLImpeller::GLContextPresent( + const GLPresentInfo& present_info) { + // The FBO ID is superfluous and was introduced for iOS where the default + // framebuffer was not FBO0. + if (!onscreen_surface_) { + return false; + } + return onscreen_surface_->Present(); +} + +// |GPUSurfaceGLDelegate| +GLFBOInfo AndroidSurfaceGLImpeller::GLContextFBO(GLFrameInfo frame_info) const { + // FBO0 is the default window bound framebuffer in EGL environments. + return GLFBOInfo{ + .fbo_id = 0, + }; +} + +// |GPUSurfaceGLDelegate| +sk_sp AndroidSurfaceGLImpeller::GetGLInterface() const { + return nullptr; +} + +bool AndroidSurfaceGLImpeller:: + RecreateOnscreenSurfaceAndMakeOnscreenContextCurrent() { + GLContextClearCurrent(); + if (!native_window_) { + return false; + } + onscreen_surface_.reset(); + auto onscreen_surface = + android_context_->CreateOnscreenSurface(native_window_->handle()); + if (!onscreen_surface) { + FML_DLOG(ERROR) << "Could not create onscreen surface."; + return false; + } + onscreen_surface_ = std::move(onscreen_surface); + return OnGLContextMakeCurrent(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_impeller.h b/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..b300aae9febd540f0ddeac35ea065ccf5e2e437e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_impeller.h @@ -0,0 +1,94 @@ +// 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_ANDROID_ANDROID_SURFACE_GL_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_IMPELLER_H_ + +#include "flutter/fml/macros.h" +#include "flutter/impeller/renderer/context.h" +#include "flutter/shell/gpu/gpu_surface_gl_delegate.h" +#include "flutter/shell/platform/android/android_context_gl_impeller.h" +#include "flutter/shell/platform/android/surface/android_native_window.h" +#include "flutter/shell/platform/android/surface/android_surface.h" + +namespace flutter { + +class AndroidSurfaceGLImpeller final : public GPUSurfaceGLDelegate, + public AndroidSurface { + public: + explicit AndroidSurfaceGLImpeller( + const std::shared_ptr& android_context); + + // |AndroidSurface| + ~AndroidSurfaceGLImpeller() override; + + // |AndroidSurface| + bool IsValid() const override; + + // |AndroidSurface| + std::unique_ptr CreateGPUSurface( + GrDirectContext* gr_context) override; + + // |AndroidSurface| + void TeardownOnScreenContext() override; + + // |AndroidSurface| + bool OnScreenSurfaceResize(const SkISize& size) override; + + // |AndroidSurface| + bool ResourceContextMakeCurrent() override; + + // |AndroidSurface| + bool ResourceContextClearCurrent() override; + + // |AndroidSurface| + bool SetNativeWindow( + fml::RefPtr window, + const std::shared_ptr& jni_facade) override; + + // |AndroidSurface| + std::unique_ptr CreateSnapshotSurface() override; + + // |AndroidSurface| + std::shared_ptr GetImpellerContext() override; + + // |GPUSurfaceGLDelegate| + std::unique_ptr GLContextMakeCurrent() override; + + // |GPUSurfaceGLDelegate| + bool GLContextClearCurrent() override; + + // |GPUSurfaceGLDelegate| + SurfaceFrame::FramebufferInfo GLContextFramebufferInfo() const override; + + // |GPUSurfaceGLDelegate| + void GLContextSetDamageRegion(const std::optional& region) override; + + // |GPUSurfaceGLDelegate| + bool GLContextPresent(const GLPresentInfo& present_info) override; + + // |GPUSurfaceGLDelegate| + GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const override; + + // |GPUSurfaceGLDelegate| + sk_sp GetGLInterface() const override; + + private: + std::shared_ptr android_context_; + std::unique_ptr onscreen_surface_; + std::unique_ptr offscreen_surface_; + fml::RefPtr native_window_; + + bool is_valid_ = false; + + bool OnGLContextMakeCurrent(); + + bool RecreateOnscreenSurfaceAndMakeOnscreenContextCurrent(); + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidSurfaceGLImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_skia.cc b/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..69eab845b203f50863a7a388803f6dbc84fd06fa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_skia.cc @@ -0,0 +1,221 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_surface_gl_skia.h" + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/memory/ref_ptr.h" +#include "flutter/shell/platform/android/android_egl_surface.h" +#include "flutter/shell/platform/android/android_shell_holder.h" + +namespace flutter { + +namespace { +// GL renderer string prefix used by the Android emulator GLES implementation. +constexpr char kEmulatorRendererPrefix[] = + "Android Emulator OpenGL ES Translator"; +} // anonymous namespace + +AndroidSurfaceGLSkia::AndroidSurfaceGLSkia( + const std::shared_ptr& android_context) + : android_context_(android_context), + native_window_(nullptr), + onscreen_surface_(nullptr), + offscreen_surface_(nullptr) { + // Acquire the offscreen surface. + offscreen_surface_ = android_context_->CreateOffscreenSurface(); + if (!offscreen_surface_->IsValid()) { + offscreen_surface_ = nullptr; + } +} + +AndroidSurfaceGLSkia::~AndroidSurfaceGLSkia() = default; + +void AndroidSurfaceGLSkia::TeardownOnScreenContext() { + // When the onscreen surface is destroyed, the context and the surface + // instance should be deleted. Issue: + // https://github.com/flutter/flutter/issues/64414 + android_context_->ClearCurrent(); + onscreen_surface_ = nullptr; +} + +bool AndroidSurfaceGLSkia::IsValid() const { + return offscreen_surface_ && android_context_->IsValid(); +} + +std::unique_ptr AndroidSurfaceGLSkia::CreateGPUSurface( + GrDirectContext* gr_context) { + if (gr_context) { + return std::make_unique(sk_ref_sp(gr_context), this, + true); + } else { + sk_sp main_skia_context = + android_context_->GetMainSkiaContext(); + if (!main_skia_context) { + main_skia_context = GPUSurfaceGLSkia::MakeGLContext(this); + android_context_->SetMainSkiaContext(main_skia_context); + } + return std::make_unique(main_skia_context, this, true); + } +} + +bool AndroidSurfaceGLSkia::OnScreenSurfaceResize(const SkISize& size) { + FML_DCHECK(IsValid()); + FML_DCHECK(onscreen_surface_); + FML_DCHECK(native_window_); + + if (size == onscreen_surface_->GetSize()) { + return true; + } + + android_context_->ClearCurrent(); + + // Ensure the destructor is called since it destroys the `EGLSurface` before + // creating a new onscreen surface. + onscreen_surface_ = nullptr; + onscreen_surface_ = android_context_->CreateOnscreenSurface(native_window_); + if (!onscreen_surface_->IsValid()) { + FML_LOG(ERROR) << "Unable to create EGL window surface on resize."; + return false; + } + onscreen_surface_->MakeCurrent(); + return true; +} + +bool AndroidSurfaceGLSkia::ResourceContextMakeCurrent() { + FML_DCHECK(IsValid()); + auto status = offscreen_surface_->MakeCurrent(); + return status != AndroidEGLSurfaceMakeCurrentStatus::kFailure; +} + +bool AndroidSurfaceGLSkia::ResourceContextClearCurrent() { + FML_DCHECK(IsValid()); + EGLBoolean result = eglMakeCurrent(eglGetCurrentDisplay(), EGL_NO_SURFACE, + EGL_NO_SURFACE, EGL_NO_CONTEXT); + return result == EGL_TRUE; +} + +bool AndroidSurfaceGLSkia::SetNativeWindow( + fml::RefPtr window, + const std::shared_ptr& jni_facade) { + FML_DCHECK(IsValid()); + FML_DCHECK(window); + native_window_ = window; + // Ensure the destructor is called since it destroys the `EGLSurface` before + // creating a new onscreen surface. + onscreen_surface_ = nullptr; + // Create the onscreen surface. + onscreen_surface_ = android_context_->CreateOnscreenSurface(window); + if (!onscreen_surface_->IsValid()) { + return false; + } + return true; +} + +std::unique_ptr AndroidSurfaceGLSkia::GLContextMakeCurrent() { + FML_DCHECK(IsValid()); + FML_DCHECK(onscreen_surface_); + auto status = onscreen_surface_->MakeCurrent(); + auto default_context_result = std::make_unique( + status != AndroidEGLSurfaceMakeCurrentStatus::kFailure); + return std::move(default_context_result); +} + +bool AndroidSurfaceGLSkia::GLContextClearCurrent() { + FML_DCHECK(IsValid()); + return android_context_->ClearCurrent(); +} + +SurfaceFrame::FramebufferInfo AndroidSurfaceGLSkia::GLContextFramebufferInfo() + const { + FML_DCHECK(IsValid()); + SurfaceFrame::FramebufferInfo res; + res.supports_readback = true; + res.supports_partial_repaint = onscreen_surface_->SupportsPartialRepaint(); + res.existing_damage = onscreen_surface_->InitialDamage(); + // Some devices (Pixel2 XL) needs EGL_KHR_partial_update rect aligned to 4, + // otherwise there are glitches + // (https://github.com/flutter/flutter/issues/97482#) + // Larger alignment might also be beneficial for tile base renderers. + res.horizontal_clip_alignment = 32; + res.vertical_clip_alignment = 32; + + return res; +} + +void AndroidSurfaceGLSkia::GLContextSetDamageRegion( + const std::optional& region) { + FML_DCHECK(IsValid()); + onscreen_surface_->SetDamageRegion(region); +} + +bool AndroidSurfaceGLSkia::GLContextPresent(const GLPresentInfo& present_info) { + FML_DCHECK(IsValid()); + FML_DCHECK(onscreen_surface_); + if (present_info.presentation_time) { + onscreen_surface_->SetPresentationTime(*present_info.presentation_time); + } + return onscreen_surface_->SwapBuffers(present_info.frame_damage); +} + +GLFBOInfo AndroidSurfaceGLSkia::GLContextFBO(GLFrameInfo frame_info) const { + FML_DCHECK(IsValid()); + // The default window bound framebuffer on Android. + return GLFBOInfo{ + .fbo_id = 0, + .existing_damage = onscreen_surface_->InitialDamage(), + }; +} + +// |GPUSurfaceGLDelegate| +sk_sp AndroidSurfaceGLSkia::GetGLInterface() const { + // This is a workaround for a bug in the Android emulator EGL/GLES + // implementation. Some versions of the emulator will not update the + // GL version string when the process switches to a new EGL context + // unless the EGL context is being made current for the first time. + // The inaccurate version string will be rejected by Skia when it + // tries to build the GrGLInterface. Flutter can work around this + // by creating a new context, making it current to force an update + // of the version, and then reverting to the previous context. + const char* gl_renderer = + reinterpret_cast(glGetString(GL_RENDERER)); + if (gl_renderer && strncmp(gl_renderer, kEmulatorRendererPrefix, + strlen(kEmulatorRendererPrefix)) == 0) { + EGLContext new_context = android_context_->CreateNewContext(); + if (new_context != EGL_NO_CONTEXT) { + EGLContext old_context = eglGetCurrentContext(); + EGLDisplay display = eglGetCurrentDisplay(); + EGLSurface draw_surface = eglGetCurrentSurface(EGL_DRAW); + EGLSurface read_surface = eglGetCurrentSurface(EGL_READ); + [[maybe_unused]] EGLBoolean result = + eglMakeCurrent(display, draw_surface, read_surface, new_context); + FML_DCHECK(result == EGL_TRUE); + result = eglMakeCurrent(display, draw_surface, read_surface, old_context); + FML_DCHECK(result == EGL_TRUE); + result = eglDestroyContext(display, new_context); + FML_DCHECK(result == EGL_TRUE); + } + } + + return GPUSurfaceGLDelegate::GetGLInterface(); +} + +std::unique_ptr AndroidSurfaceGLSkia::CreateSnapshotSurface() { + if (!onscreen_surface_ || !onscreen_surface_->IsValid()) { + onscreen_surface_ = android_context_->CreatePbufferSurface(); + } + sk_sp main_skia_context = + android_context_->GetMainSkiaContext(); + if (!main_skia_context) { + main_skia_context = GPUSurfaceGLSkia::MakeGLContext(this); + android_context_->SetMainSkiaContext(main_skia_context); + } + + return std::make_unique(main_skia_context, this, true); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_skia.h b/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..976f26ef559f97bde691437ab424bf198c26e1bf --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_surface_gl_skia.h @@ -0,0 +1,96 @@ +// 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_ANDROID_ANDROID_SURFACE_GL_SKIA_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_SKIA_H_ + +#include + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/gpu/gpu_surface_gl_skia.h" +#include "flutter/shell/platform/android/android_context_gl_skia.h" +#include "flutter/shell/platform/android/android_environment_gl.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/surface/android_surface.h" + +namespace flutter { + +class AndroidSurfaceGLSkia final : public GPUSurfaceGLDelegate, + public AndroidSurface { + public: + explicit AndroidSurfaceGLSkia( + const std::shared_ptr& android_context); + + ~AndroidSurfaceGLSkia() override; + + // |AndroidSurface| + bool IsValid() const override; + + // |AndroidSurface| + std::unique_ptr CreateGPUSurface( + GrDirectContext* gr_context) override; + + // |AndroidSurface| + void TeardownOnScreenContext() override; + + // |AndroidSurface| + bool OnScreenSurfaceResize(const SkISize& size) override; + + // |AndroidSurface| + bool ResourceContextMakeCurrent() override; + + // |AndroidSurface| + bool ResourceContextClearCurrent() override; + + // |AndroidSurface| + bool SetNativeWindow( + fml::RefPtr window, + const std::shared_ptr& jni_facade) override; + + // |AndroidSurface| + virtual std::unique_ptr CreateSnapshotSurface() override; + + // |GPUSurfaceGLDelegate| + std::unique_ptr GLContextMakeCurrent() override; + + // |GPUSurfaceGLDelegate| + bool GLContextClearCurrent() override; + + // |GPUSurfaceGLDelegate| + SurfaceFrame::FramebufferInfo GLContextFramebufferInfo() const override; + + // |GPUSurfaceGLDelegate| + void GLContextSetDamageRegion(const std::optional& region) override; + + // |GPUSurfaceGLDelegate| + bool GLContextPresent(const GLPresentInfo& present_info) override; + + // |GPUSurfaceGLDelegate| + GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const override; + + // |GPUSurfaceGLDelegate| + sk_sp GetGLInterface() const override; + + // Obtain a raw pointer to the on-screen AndroidEGLSurface. + // + // This method is intended for use in tests. Callers must not + // delete the returned pointer. + AndroidEGLSurface* GetOnscreenSurface() const { + return onscreen_surface_.get(); + } + + private: + std::shared_ptr android_context_; + fml::RefPtr native_window_; + std::unique_ptr onscreen_surface_; + std::unique_ptr offscreen_surface_; + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidSurfaceGLSkia); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_SKIA_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_surface_software.cc b/flutter/engine/src/flutter/shell/platform/android/android_surface_software.cc new file mode 100644 index 0000000000000000000000000000000000000000..11e2dc385dffa8b5f755b1f2ae4e10a9568cf7b2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_surface_software.cc @@ -0,0 +1,170 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_surface_software.h" + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/platform/android/jni_weak_ref.h" +#include "flutter/fml/platform/android/scoped_java_ref.h" +#include "flutter/fml/trace_event.h" +#include "flutter/shell/platform/android/android_shell_holder.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" + +#include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { + +namespace { + +bool GetSkColorType(int32_t buffer_format, + SkColorType* color_type, + SkAlphaType* alpha_type) { + switch (buffer_format) { + case WINDOW_FORMAT_RGB_565: + *color_type = kRGB_565_SkColorType; + *alpha_type = kOpaque_SkAlphaType; + return true; + case WINDOW_FORMAT_RGBA_8888: + *color_type = kRGBA_8888_SkColorType; + *alpha_type = kPremul_SkAlphaType; + return true; + default: + return false; + } +} + +} // anonymous namespace + +AndroidSurfaceSoftware::AndroidSurfaceSoftware() { + GetSkColorType(WINDOW_FORMAT_RGBA_8888, &target_color_type_, + &target_alpha_type_); +} + +AndroidSurfaceSoftware::~AndroidSurfaceSoftware() = default; + +bool AndroidSurfaceSoftware::IsValid() const { + return true; +} + +bool AndroidSurfaceSoftware::ResourceContextMakeCurrent() { + // Resource Context always not available on software backend. + return false; +} + +bool AndroidSurfaceSoftware::ResourceContextClearCurrent() { + return false; +} + +std::unique_ptr AndroidSurfaceSoftware::CreateGPUSurface( + // The software AndroidSurface neither uses any passed in Skia context + // nor does it interact with the AndroidContext's raster Skia context. + GrDirectContext* gr_context) { + if (!IsValid()) { + return nullptr; + } + + auto surface = + std::make_unique(this, true /* render to surface */); + + if (!surface->IsValid()) { + return nullptr; + } + + return surface; +} + +sk_sp AndroidSurfaceSoftware::AcquireBackingStore( + const SkISize& size) { + TRACE_EVENT0("flutter", "AndroidSurfaceSoftware::AcquireBackingStore"); + if (!IsValid()) { + return nullptr; + } + + if (sk_surface_ != nullptr && + SkISize::Make(sk_surface_->width(), sk_surface_->height()) == size) { + // The old and new surface sizes are the same. Nothing to do here. + return sk_surface_; + } + + SkImageInfo image_info = + SkImageInfo::Make(size.fWidth, size.fHeight, target_color_type_, + target_alpha_type_, SkColorSpace::MakeSRGB()); + + sk_surface_ = SkSurfaces::Raster(image_info); + + return sk_surface_; +} + +bool AndroidSurfaceSoftware::PresentBackingStore( + sk_sp backing_store) { + TRACE_EVENT0("flutter", "AndroidSurfaceSoftware::PresentBackingStore"); + if (!IsValid() || backing_store == nullptr) { + return false; + } + + SkPixmap pixmap; + if (!backing_store->peekPixels(&pixmap)) { + return false; + } + + ANativeWindow_Buffer native_buffer; + if (ANativeWindow_lock(native_window_->handle(), &native_buffer, nullptr)) { + return false; + } + + SkColorType color_type; + SkAlphaType alpha_type; + if (GetSkColorType(native_buffer.format, &color_type, &alpha_type)) { + SkImageInfo native_image_info = SkImageInfo::Make( + native_buffer.width, native_buffer.height, color_type, alpha_type); + + std::unique_ptr canvas = SkCanvas::MakeRasterDirect( + native_image_info, native_buffer.bits, + native_buffer.stride * SkColorTypeBytesPerPixel(color_type)); + + if (canvas) { + SkBitmap bitmap; + if (bitmap.installPixels(pixmap)) { + canvas->drawImageRect( + bitmap.asImage(), + SkRect::MakeIWH(native_buffer.width, native_buffer.height), + SkSamplingOptions()); + } + } + } + + ANativeWindow_unlockAndPost(native_window_->handle()); + + return true; +} + +void AndroidSurfaceSoftware::TeardownOnScreenContext() {} + +bool AndroidSurfaceSoftware::OnScreenSurfaceResize(const SkISize& size) { + return true; +} + +bool AndroidSurfaceSoftware::SetNativeWindow( + fml::RefPtr window, + const std::shared_ptr& jni_facade) { + native_window_ = std::move(window); + if (!(native_window_ && native_window_->IsValid())) { + return false; + } + int32_t window_format = ANativeWindow_getFormat(native_window_->handle()); + if (window_format < 0) { + return false; + } + if (!GetSkColorType(window_format, &target_color_type_, + &target_alpha_type_)) { + return false; + } + return true; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_surface_software.h b/flutter/engine/src/flutter/shell/platform/android/android_surface_software.h new file mode 100644 index 0000000000000000000000000000000000000000..fd62c8053d6511b929f214beee20d7ebd541bf23 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_surface_software.h @@ -0,0 +1,67 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_SOFTWARE_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_SOFTWARE_H_ + +#include "flutter/fml/macros.h" +#include "flutter/fml/platform/android/jni_weak_ref.h" +#include "flutter/fml/platform/android/scoped_java_ref.h" +#include "flutter/shell/gpu/gpu_surface_software.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/surface/android_surface.h" + +#include "third_party/skia/include/core/SkSurface.h" + +namespace flutter { + +class AndroidSurfaceSoftware final : public AndroidSurface, + public GPUSurfaceSoftwareDelegate { + public: + AndroidSurfaceSoftware(); + + ~AndroidSurfaceSoftware() override; + + // |AndroidSurface| + bool IsValid() const override; + + // |AndroidSurface| + bool ResourceContextMakeCurrent() override; + + // |AndroidSurface| + bool ResourceContextClearCurrent() override; + + // |AndroidSurface| + std::unique_ptr CreateGPUSurface( + GrDirectContext* gr_context) override; + + // |AndroidSurface| + void TeardownOnScreenContext() override; + + // |AndroidSurface| + bool OnScreenSurfaceResize(const SkISize& size) override; + + // |AndroidSurface| + bool SetNativeWindow( + fml::RefPtr window, + const std::shared_ptr& jni_facade) override; + + // |GPUSurfaceSoftwareDelegate| + sk_sp AcquireBackingStore(const SkISize& size) override; + + // |GPUSurfaceSoftwareDelegate| + bool PresentBackingStore(sk_sp backing_store) override; + + private: + sk_sp sk_surface_; + fml::RefPtr native_window_; + SkColorType target_color_type_; + SkAlphaType target_alpha_type_; + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidSurfaceSoftware); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_SOFTWARE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/android_surface_vk_impeller.cc b/flutter/engine/src/flutter/shell/platform/android/android_surface_vk_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..008724c72bf458f9b20fc46d6929f6e45c30af01 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_surface_vk_impeller.cc @@ -0,0 +1,125 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/android_surface_vk_impeller.h" + +#include +#include + +#include "flutter/fml/concurrent_message_loop.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/memory/ref_ptr.h" +#include "flutter/impeller/renderer/backend/vulkan/context_vk.h" +#include "flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_vk.h" +#include "flutter/shell/gpu/gpu_surface_vulkan_impeller.h" +#include "flutter/vulkan/vulkan_native_surface_android.h" +#include "impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_vk.h" +#include "impeller/toolkit/android/surface_transaction.h" + +namespace flutter { + +AndroidSurfaceVKImpeller::AndroidSurfaceVKImpeller( + const std::shared_ptr& android_context) { + is_valid_ = android_context->IsValid(); + + auto& context_vk = + impeller::ContextVK::Cast(*android_context->GetImpellerContext()); + surface_context_vk_ = context_vk.CreateSurfaceContext(); + eager_gpu_surface_ = + std::make_unique(nullptr, surface_context_vk_); +} + +AndroidSurfaceVKImpeller::~AndroidSurfaceVKImpeller() = default; + +bool AndroidSurfaceVKImpeller::IsValid() const { + return is_valid_; +} + +void AndroidSurfaceVKImpeller::TeardownOnScreenContext() { + surface_context_vk_->TeardownSwapchain(); +} + +std::unique_ptr AndroidSurfaceVKImpeller::CreateGPUSurface( + GrDirectContext* gr_context) { + if (!IsValid()) { + return nullptr; + } + + if (!native_window_ || !native_window_->IsValid()) { + return nullptr; + } + + if (eager_gpu_surface_) { + auto gpu_surface = std::move(eager_gpu_surface_); + if (!gpu_surface->IsValid()) { + return nullptr; + } + return gpu_surface; + } + + std::unique_ptr gpu_surface = + std::make_unique(nullptr, surface_context_vk_); + + if (!gpu_surface->IsValid()) { + return nullptr; + } + + return gpu_surface; +} + +bool AndroidSurfaceVKImpeller::OnScreenSurfaceResize(const SkISize& size) { + surface_context_vk_->UpdateSurfaceSize( + impeller::ISize{size.width(), size.height()}); + return true; +} + +bool AndroidSurfaceVKImpeller::ResourceContextMakeCurrent() { + return true; +} + +bool AndroidSurfaceVKImpeller::ResourceContextClearCurrent() { + return true; +} + +bool AndroidSurfaceVKImpeller::SetNativeWindow( + fml::RefPtr window, + const std::shared_ptr& jni_facade) { + if (window && (native_window_ == window)) { + return OnScreenSurfaceResize(window->GetSize()); + } + + native_window_ = nullptr; + + if (!window || !window->IsValid()) { + return false; + } + + impeller::CreateTransactionCB cb = [jni_facade = jni_facade]() { + FML_CHECK(jni_facade) << "JNI was nullptr"; + ASurfaceTransaction* tx = jni_facade->createTransaction(); + if (tx == nullptr) { + return impeller::android::SurfaceTransaction(); + } + return impeller::android::SurfaceTransaction(tx); + }; + + auto swapchain = impeller::SwapchainVK::Create( + std::reinterpret_pointer_cast( + surface_context_vk_->GetParent()), + window->handle(), cb); + + if (surface_context_vk_->SetSwapchain(std::move(swapchain))) { + native_window_ = std::move(window); + return true; + } + + return false; +} + +std::shared_ptr +AndroidSurfaceVKImpeller::GetImpellerContext() { + return surface_context_vk_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/android_surface_vk_impeller.h b/flutter/engine/src/flutter/shell/platform/android/android_surface_vk_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..8921ee0a8e2d722d20d1c4ee58c08de0821e464a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/android_surface_vk_impeller.h @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_VK_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_VK_IMPELLER_H_ + +#include "flutter/fml/concurrent_message_loop.h" +#include "flutter/fml/macros.h" +#include "flutter/impeller/display_list/aiks_context.h" +#include "flutter/impeller/renderer/backend/vulkan/surface_context_vk.h" +#include "flutter/shell/platform/android/android_context_vk_impeller.h" +#include "flutter/shell/platform/android/surface/android_native_window.h" +#include "flutter/shell/platform/android/surface/android_surface.h" +#include "shell/gpu/gpu_surface_vulkan_impeller.h" + +namespace flutter { + +class AndroidSurfaceVKImpeller : public AndroidSurface { + public: + explicit AndroidSurfaceVKImpeller( + const std::shared_ptr& android_context); + + ~AndroidSurfaceVKImpeller() override; + + // |AndroidSurface| + bool IsValid() const override; + + // |AndroidSurface| + std::unique_ptr CreateGPUSurface( + GrDirectContext* gr_context) override; + + // |AndroidSurface| + void TeardownOnScreenContext() override; + + // |AndroidSurface| + bool OnScreenSurfaceResize(const SkISize& size) override; + + // |AndroidSurface| + bool ResourceContextMakeCurrent() override; + + // |AndroidSurface| + bool ResourceContextClearCurrent() override; + + // |AndroidSurface| + std::shared_ptr GetImpellerContext() override; + + // |AndroidSurface| + bool SetNativeWindow( + fml::RefPtr window, + const std::shared_ptr& jni_facade) override; + + private: + std::shared_ptr surface_context_vk_; + fml::RefPtr native_window_; + // The first GPU Surface is initialized as soon as the + // AndroidSurfaceVulkanImpeller is created. This ensures that the pipelines + // are bootstrapped as early as possible. + std::unique_ptr eager_gpu_surface_; + + bool is_valid_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(AndroidSurfaceVKImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_VK_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/apk_asset_provider.cc b/flutter/engine/src/flutter/shell/platform/android/apk_asset_provider.cc new file mode 100644 index 0000000000000000000000000000000000000000..ef5bbd23afe7c1e750590e22da25adf9f750b233 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/apk_asset_provider.cc @@ -0,0 +1,115 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/apk_asset_provider.h" + +#include + +#include +#include +#include + +#include "flutter/assets/asset_resolver.h" +#include "flutter/fml/logging.h" + +namespace flutter { + +class APKAssetMapping : public fml::Mapping { + public: + explicit APKAssetMapping(AAsset* asset) : asset_(asset) {} + + ~APKAssetMapping() override { AAsset_close(asset_); } + + size_t GetSize() const override { return AAsset_getLength(asset_); } + + const uint8_t* GetMapping() const override { + return reinterpret_cast(AAsset_getBuffer(asset_)); + } + + bool IsDontNeedSafe() const override { return !AAsset_isAllocated(asset_); } + + private: + AAsset* const asset_; + + FML_DISALLOW_COPY_AND_ASSIGN(APKAssetMapping); +}; + +class APKAssetProviderImpl : public APKAssetProviderInternal { + public: + explicit APKAssetProviderImpl(JNIEnv* env, + jobject jassetManager, + std::string directory) + : java_asset_manager_(env, jassetManager), + directory_(std::move(directory)) { + asset_manager_ = AAssetManager_fromJava(env, jassetManager); + } + + ~APKAssetProviderImpl() = default; + + std::unique_ptr GetAsMapping( + const std::string& asset_name) const override { + std::stringstream ss; + ss << directory_.c_str() << "/" << asset_name; + AAsset* asset = AAssetManager_open(asset_manager_, ss.str().c_str(), + AASSET_MODE_BUFFER); + if (!asset) { + return nullptr; + } + + return std::make_unique(asset); + }; + + private: + fml::jni::ScopedJavaGlobalRef java_asset_manager_; + AAssetManager* asset_manager_; + const std::string directory_; + + FML_DISALLOW_COPY_AND_ASSIGN(APKAssetProviderImpl); +}; + +APKAssetProvider::APKAssetProvider(JNIEnv* env, + jobject assetManager, + std::string directory) + : impl_(std::make_shared(env, + assetManager, + std::move(directory))) {} + +APKAssetProvider::APKAssetProvider( + std::shared_ptr impl) + : impl_(std::move(impl)) {} + +// |AssetResolver| +bool APKAssetProvider::IsValid() const { + return true; +} + +// |AssetResolver| +bool APKAssetProvider::IsValidAfterAssetManagerChange() const { + return true; +} + +// |AssetResolver| +AssetResolver::AssetResolverType APKAssetProvider::GetType() const { + return AssetResolver::AssetResolverType::kApkAssetProvider; +} + +// |AssetResolver| +std::unique_ptr APKAssetProvider::GetAsMapping( + const std::string& asset_name) const { + return impl_->GetAsMapping(asset_name); +} + +std::unique_ptr APKAssetProvider::Clone() const { + return std::make_unique(impl_); +} + +bool APKAssetProvider::operator==(const AssetResolver& other) const { + auto other_provider = other.as_apk_asset_provider(); + if (!other_provider) { + return false; + } + return impl_ == other_provider->impl_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/apk_asset_provider.h b/flutter/engine/src/flutter/shell/platform/android/apk_asset_provider.h new file mode 100644 index 0000000000000000000000000000000000000000..5d1c472fc06acd41766e66b043d6969f606b1180 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/apk_asset_provider.h @@ -0,0 +1,74 @@ +// 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_ANDROID_APK_ASSET_PROVIDER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_APK_ASSET_PROVIDER_H_ + +#include +#include + +#include "flutter/assets/asset_resolver.h" +#include "flutter/fml/memory/ref_counted.h" +#include "flutter/fml/platform/android/scoped_java_ref.h" + +namespace flutter { + +class APKAssetProviderInternal { + public: + virtual std::unique_ptr GetAsMapping( + const std::string& asset_name) const = 0; + + protected: + virtual ~APKAssetProviderInternal() = default; +}; + +class APKAssetProvider final : public AssetResolver { + public: + explicit APKAssetProvider(JNIEnv* env, + jobject assetManager, + std::string directory); + + explicit APKAssetProvider(std::shared_ptr impl); + + ~APKAssetProvider() = default; + + // Returns a new 'std::unique_ptr' with the same 'impl_' as + // this provider. + std::unique_ptr Clone() const; + + // Obtain a raw pointer to the APKAssetProviderInternal. + // + // This method is intended for use in tests. Callers must not + // delete the returned pointer. + APKAssetProviderInternal* GetImpl() const { return impl_.get(); } + + bool operator==(const AssetResolver& other) const override; + + private: + std::shared_ptr impl_; + + // |flutter::AssetResolver| + bool IsValid() const override; + + // |flutter::AssetResolver| + bool IsValidAfterAssetManagerChange() const override; + + // |AssetResolver| + AssetResolver::AssetResolverType GetType() const override; + + // |flutter::AssetResolver| + std::unique_ptr GetAsMapping( + const std::string& asset_name) const override; + + // |AssetResolver| + const APKAssetProvider* as_apk_asset_provider() const override { + return this; + } + + FML_DISALLOW_COPY_AND_ASSIGN(APKAssetProvider); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_APK_ASSET_PROVIDER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/apk_asset_provider_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/apk_asset_provider_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..5f6a7ef894b3558376448797ff27ac6a110a718b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/apk_asset_provider_unittests.cc @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/apk_asset_provider.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { +class MockAPKAssetProviderImpl : public APKAssetProviderInternal { + public: + MOCK_METHOD(std::unique_ptr, + GetAsMapping, + (const std::string& asset_name), + (const, override)); +}; + +TEST(APKAssetProvider, CloneAndEquals) { + auto first_provider = std::make_unique( + std::make_shared()); + auto second_provider = std::make_unique( + std::make_shared()); + auto third_provider = first_provider->Clone(); + + ASSERT_NE(first_provider->GetImpl(), second_provider->GetImpl()); + ASSERT_EQ(first_provider->GetImpl(), third_provider->GetImpl()); + ASSERT_FALSE(*first_provider == *second_provider); + ASSERT_TRUE(*first_provider == *third_provider); +} +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/build.gradle b/flutter/engine/src/flutter/shell/platform/android/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..11dd5f89c447446a6bdd29c15c4c16fd9cf7b8c8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/build.gradle @@ -0,0 +1,65 @@ +// This file only exists to provide IDE support to Android Studio. +// +// See ./README.md for details. + +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath "com.android.tools.build:gradle:8.7.2" + } +} + +repositories { + google() + mavenCentral() +} + +apply plugin: "com.android.library" + +android { + namespace "io.flutter.embedding" + compileSdk 35 + + defaultConfig { + minSdkVersion 21 + } + + sourceSets { + main { + manifest.srcFile 'AndroidManifest.xml' + java.srcDirs './' + java.include './io.flutter/**' + test { + java.srcDir './test' + java.include './test/io.flutter/**' + } + } + } + + testOptions { + unitTests { + includeAndroidResources = true + } + + } + + dependencies { + implementation fileTree(include: ["*.jar"], dir: "../../../../flutter/third_party/android_embedding_dependencies/lib/") + + // These dependencies should be kept in line with those in the ./test_runner/build.gradle + implementation "androidx.test:core:1.4.0" + implementation "com.google.android.play:core:1.8.0" + implementation "com.ibm.icu:icu4j:69.1" + implementation "org.robolectric:robolectric:4.14.1" + implementation "junit:junit:4.13.2" + implementation "androidx.test.ext:junit:1.1.4-alpha07" + + def mockitoVersion = "4.7.0" + implementation "org.mockito:mockito-core:$mockitoVersion" + implementation "org.mockito:mockito-inline:$mockitoVersion" + implementation "org.mockito:mockito-android:$mockitoVersion" + } +} diff --git a/flutter/engine/src/flutter/shell/platform/android/flutter_main.cc b/flutter/engine/src/flutter/shell/platform/android/flutter_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..b4300bbdaa179f9a3c17dadc1b05280285989dff --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/flutter_main.cc @@ -0,0 +1,357 @@ +// 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. + +#define FML_USED_ON_EMBEDDER + +#include +#include +#include +#include +#include +#include + +#include "common/settings.h" +#include "flutter/fml/command_line.h" +#include "flutter/fml/file.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/message_loop.h" +#include "flutter/fml/platform/android/jni_util.h" +#include "flutter/fml/platform/android/paths_android.h" +#include "flutter/lib/ui/plugins/callback_cache.h" +#include "flutter/runtime/dart_vm.h" +#include "flutter/shell/common/switches.h" +#include "flutter/shell/platform/android/android_context_vk_impeller.h" +#include "flutter/shell/platform/android/android_rendering_selector.h" +#include "flutter/shell/platform/android/context/android_context.h" +#include "flutter/shell/platform/android/flutter_main.h" +#include "impeller/base/validation.h" +#include "impeller/toolkit/android/proc_table.h" +#include "txt/platform.h" + +namespace flutter { + +constexpr int kMinimumAndroidApiLevelForImpeller = 29; +constexpr int kMinimumAndroidApiLevelForMediaTekVulkan = 31; + +extern "C" { +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG +// Used for debugging dart:* sources. +extern const uint8_t kPlatformStrongDill[]; +extern const intptr_t kPlatformStrongDillSize; +#endif +} + +namespace { + +fml::jni::ScopedJavaGlobalRef* g_flutter_jni_class = nullptr; + +static const constexpr char* kAndroidHuawei = "android-huawei"; + +/// These are SoCs that crash when using AHB imports. +static constexpr const char* kBLC[] = { + // Most Exynos Series SoC + "exynos7870", // + "exynos7880", // + "exynos7872", // + "exynos7884", // + "exynos7885", // + "exynos8890", // + "exynos8895", // + "exynos7904", // + "exynos9609", // + "exynos9610", // + "exynos9611", // + "exynos9810" // +}; + +} // anonymous namespace + +FlutterMain::FlutterMain(const flutter::Settings& settings, + flutter::AndroidRenderingAPI android_rendering_api) + : settings_(settings), android_rendering_api_(android_rendering_api) {} + +FlutterMain::~FlutterMain() = default; + +static std::unique_ptr g_flutter_main; + +FlutterMain& FlutterMain::Get() { + FML_CHECK(g_flutter_main) << "ensureInitializationComplete must have already " + "been called."; + return *g_flutter_main; +} + +const flutter::Settings& FlutterMain::GetSettings() const { + return settings_; +} + +flutter::AndroidRenderingAPI FlutterMain::GetAndroidRenderingAPI() { + return android_rendering_api_; +} + +void FlutterMain::Init(JNIEnv* env, + jclass clazz, + jobject context, + jobjectArray jargs, + jstring kernelPath, + jstring appStoragePath, + jstring engineCachesPath, + jlong initTimeMillis, + jint api_level) { + std::vector args; + args.push_back("flutter"); + for (auto& arg : fml::jni::StringArrayToVector(env, jargs)) { + args.push_back(std::move(arg)); + } + auto command_line = fml::CommandLineFromIterators(args.begin(), args.end()); + + auto settings = SettingsFromCommandLine(command_line); + + // Turn systracing on if ATrace_isEnabled is true and the user did not already + // request systracing + if (!settings.trace_systrace) { + settings.trace_systrace = + impeller::android::GetProcTable().TraceIsEnabled(); + if (settings.trace_systrace) { + __android_log_print( + ANDROID_LOG_INFO, "Flutter", + "ATrace was enabled at startup. Flutter and Dart " + "tracing will be forwarded to systrace and will not show up in " + "Dart DevTools."); + } + } + // The API level must be provided from java, as the NDK function + // android_get_device_api_level() is only available on API 24 and greater, and + // Flutter still supports 21, 22, and 23. + + AndroidRenderingAPI android_rendering_api = + SelectedRenderingAPI(settings, api_level); + switch (android_rendering_api) { + case AndroidRenderingAPI::kSoftware: + case AndroidRenderingAPI::kSkiaOpenGLES: + settings.enable_impeller = false; + break; + case AndroidRenderingAPI::kImpellerOpenGLES: + case AndroidRenderingAPI::kImpellerVulkan: + settings.enable_impeller = true; + break; + } + +#if FLUTTER_RELEASE + // On most platforms the timeline is always disabled in release mode. + // On Android, enable it in release mode only when using systrace. + settings.enable_timeline_event_handler = settings.trace_systrace; +#endif // FLUTTER_RELEASE + + // Restore the callback cache. + // TODO(chinmaygarde): Route all cache file access through FML and remove this + // setter. + flutter::DartCallbackCache::SetCachePath( + fml::jni::JavaStringToString(env, appStoragePath)); + + fml::paths::InitializeAndroidCachesPath( + fml::jni::JavaStringToString(env, engineCachesPath)); + + flutter::DartCallbackCache::LoadCacheFromDisk(); + + if (!flutter::DartVM::IsRunningPrecompiledCode() && kernelPath) { + // Check to see if the appropriate kernel files are present and configure + // settings accordingly. + auto application_kernel_path = + fml::jni::JavaStringToString(env, kernelPath); + + if (fml::IsFile(application_kernel_path)) { + settings.application_kernel_asset = application_kernel_path; + } + } + + settings.task_observer_add = [](intptr_t key, const fml::closure& callback) { + fml::MessageLoop::GetCurrent().AddTaskObserver(key, callback); + }; + + settings.task_observer_remove = [](intptr_t key) { + fml::MessageLoop::GetCurrent().RemoveTaskObserver(key); + }; + + settings.log_message_callback = [](const std::string& tag, + const std::string& message) { + __android_log_print(ANDROID_LOG_INFO, tag.c_str(), "%.*s", + static_cast(message.size()), message.c_str()); + }; + + settings.enable_platform_isolates = true; + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + // There are no ownership concerns here as all mappings are owned by the + // embedder and not the engine. + auto make_mapping_callback = [](const uint8_t* mapping, size_t size) { + return [mapping, size]() { + return std::make_unique(mapping, size); + }; + }; + + settings.dart_library_sources_kernel = + make_mapping_callback(kPlatformStrongDill, kPlatformStrongDillSize); +#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + + // Not thread safe. Will be removed when FlutterMain is refactored to no + // longer be a singleton. + g_flutter_main.reset(new FlutterMain(settings, android_rendering_api)); + g_flutter_main->SetupDartVMServiceUriCallback(env); +} + +void FlutterMain::SetupDartVMServiceUriCallback(JNIEnv* env) { + g_flutter_jni_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("io/flutter/embedding/engine/FlutterJNI")); + if (g_flutter_jni_class->is_null()) { + return; + } + jfieldID uri_field = env->GetStaticFieldID( + g_flutter_jni_class->obj(), "vmServiceUri", "Ljava/lang/String;"); + if (uri_field == nullptr) { + return; + } + + auto set_uri = [env, uri_field](const std::string& uri) { + fml::jni::ScopedJavaLocalRef java_uri = + fml::jni::StringToJavaString(env, uri); + env->SetStaticObjectField(g_flutter_jni_class->obj(), uri_field, + java_uri.obj()); + }; + + fml::MessageLoop::EnsureInitializedForCurrentThread(); + fml::RefPtr platform_runner = + fml::MessageLoop::GetCurrent().GetTaskRunner(); + + vm_service_uri_callback_ = DartServiceIsolate::AddServerStatusCallback( + [platform_runner, set_uri](const std::string& uri) { + platform_runner->PostTask([uri, set_uri] { set_uri(uri); }); + }); +} + +static void PrefetchDefaultFontManager(JNIEnv* env, jclass jcaller) { + // Initialize a singleton owned by Skia. + txt::GetDefaultFontManager(); +} + +bool FlutterMain::Register(JNIEnv* env) { + static const JNINativeMethod methods[] = { + { + .name = "nativeInit", + .signature = "(Landroid/content/Context;[Ljava/lang/String;Ljava/" + "lang/String;Ljava/lang/String;Ljava/lang/String;JI)V", + .fnPtr = reinterpret_cast(&Init), + }, + { + .name = "nativePrefetchDefaultFontManager", + .signature = "()V", + .fnPtr = reinterpret_cast(&PrefetchDefaultFontManager), + }, + }; + + jclass clazz = env->FindClass("io/flutter/embedding/engine/FlutterJNI"); + + if (clazz == nullptr) { + return false; + } + + return env->RegisterNatives(clazz, methods, std::size(methods)) == 0; +} + +// static +bool FlutterMain::IsDeviceEmulator(std::string_view product_model) { + return std::string(product_model).find("gphone") != std::string::npos; +} + +// static +bool FlutterMain::IsKnownBadSOC(std::string_view hardware) { + // TODO(jonahwilliams): if the list gets too long (> 16), convert + // to a hash map first. + for (const auto& board : kBLC) { + if (strcmp(board, hardware.data()) == 0) { + return true; + } + } + return false; +} + +// static +AndroidRenderingAPI FlutterMain::SelectedRenderingAPI( + const flutter::Settings& settings, + int api_level) { + if (settings.enable_software_rendering) { + FML_CHECK(!settings.enable_impeller) + << "Impeller does not support software rendering. Either disable " + "software rendering or disable impeller."; + return AndroidRenderingAPI::kSoftware; + } + constexpr AndroidRenderingAPI kVulkanUnsupportedFallback = + AndroidRenderingAPI::kImpellerOpenGLES; + + // Debug/Profile only functionality for testing a specific + // backend configuration. +#ifndef FLUTTER_RELEASE + if (settings.requested_rendering_backend == "opengles" && + settings.enable_impeller) { + return AndroidRenderingAPI::kImpellerOpenGLES; + } + if (settings.requested_rendering_backend == "vulkan" && + settings.enable_impeller) { + return AndroidRenderingAPI::kImpellerVulkan; + } +#endif + + if (settings.enable_impeller) { + // Impeller must only be used on API level 29+, as older API levels do not + // have requisite features to support platform views. + // + // Even if this check returns true, Impeller may determine it cannot use + // Vulkan for some other reason, such as a missing required extension or + // feature. In these cases it will use OpenGLES. + if (api_level < kMinimumAndroidApiLevelForImpeller) { + return AndroidRenderingAPI::kSkiaOpenGLES; + } + char product_model[PROP_VALUE_MAX]; + __system_property_get("ro.product.model", product_model); + if (IsDeviceEmulator(product_model)) { + // Avoid using Vulkan on known emulators. + return kVulkanUnsupportedFallback; + } + + __system_property_get("ro.com.google.clientidbase", product_model); + if (strcmp(product_model, kAndroidHuawei) == 0) { + // Avoid using Vulkan on Huawei as AHB imports do not + // consistently work. + return kVulkanUnsupportedFallback; + } + + if (api_level < kMinimumAndroidApiLevelForMediaTekVulkan && + __system_property_find("ro.vendor.mediatek.platform") != nullptr) { + // Probably MediaTek. Avoid Vulkan if older than 34 to work around + // crashes when importing AHB. + return kVulkanUnsupportedFallback; + } + + __system_property_get("ro.product.board", product_model); + if (IsKnownBadSOC(product_model)) { + // Avoid using Vulkan on known bad SoCs. + return kVulkanUnsupportedFallback; + } + + // Determine if Vulkan is supported by creating a Vulkan context and + // checking if it is valid. + impeller::ScopedValidationDisable disable_validation; + auto vulkan_backend = std::make_unique( + AndroidContext::ContextSettings{.enable_validation = false, + .enable_gpu_tracing = false, + .quiet = true}); + if (!vulkan_backend->IsValid()) { + return kVulkanUnsupportedFallback; + } + return AndroidRenderingAPI::kImpellerVulkan; + } + + return AndroidRenderingAPI::kSkiaOpenGLES; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/flutter_main.h b/flutter/engine/src/flutter/shell/platform/android/flutter_main.h new file mode 100644 index 0000000000000000000000000000000000000000..2354caa8c9dd672c9b2e5ffb12682135b046f642 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/flutter_main.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_FLUTTER_MAIN_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_FLUTTER_MAIN_H_ + +#include + +#include "flutter/common/settings.h" +#include "flutter/fml/macros.h" +#include "flutter/runtime/dart_service_isolate.h" +#include "flutter/shell/platform/android/android_rendering_selector.h" + +namespace flutter { + +class FlutterMain { + public: + ~FlutterMain(); + + static bool Register(JNIEnv* env); + + static FlutterMain& Get(); + + const flutter::Settings& GetSettings() const; + flutter::AndroidRenderingAPI GetAndroidRenderingAPI(); + + static AndroidRenderingAPI SelectedRenderingAPI( + const flutter::Settings& settings, + int api_level); + + static bool IsDeviceEmulator(std::string_view product_model); + + static bool IsKnownBadSOC(std::string_view hardware); + + private: + const flutter::Settings settings_; + const flutter::AndroidRenderingAPI android_rendering_api_; + DartServiceIsolate::CallbackHandle vm_service_uri_callback_ = 0; + + explicit FlutterMain(const flutter::Settings& settings, + flutter::AndroidRenderingAPI android_rendering_api); + + static void Init(JNIEnv* env, + jclass clazz, + jobject context, + jobjectArray jargs, + jstring kernelPath, + jstring appStoragePath, + jstring engineCachesPath, + jlong initTimeMillis, + jint api_level); + + void SetupDartVMServiceUriCallback(JNIEnv* env); + + FML_DISALLOW_COPY_AND_ASSIGN(FlutterMain); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_FLUTTER_MAIN_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/flutter_shell_native_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/flutter_shell_native_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..de1401c1ad00924af01dbe08d657fb3b869aa0f2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/flutter_shell_native_unittests.cc @@ -0,0 +1,10 @@ +// 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 "gtest/gtest.h" + +int main(int argc, char* argv[]) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/flutter/engine/src/flutter/shell/platform/android/gradle.properties b/flutter/engine/src/flutter/shell/platform/android/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..b515f69e9946dbf84d3acbf2d44664fb75dd9599 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/gradle.properties @@ -0,0 +1,5 @@ +# This file only exists to provide IDE support to Android Studio. +# +# See ./README.md for details. +android.useAndroidX=true +android.enableJetifier=true diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture.cc b/flutter/engine/src/flutter/shell/platform/android/image_external_texture.cc new file mode 100644 index 0000000000000000000000000000000000000000..4b8ea52c9accb50f72311cf5398bd3da8bac8443 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture.cc @@ -0,0 +1,133 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/image_external_texture.h" + +#include +#include + +#include "flutter/fml/platform/android/jni_util.h" +#include "flutter/impeller/toolkit/android/proc_table.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { + +ImageExternalTexture::ImageExternalTexture( + int64_t id, + const fml::jni::ScopedJavaGlobalRef& image_texture_entry, + const std::shared_ptr& jni_facade, + ImageLifecycle lifecycle) + : Texture(id), + image_texture_entry_(image_texture_entry), + jni_facade_(jni_facade), + texture_lifecycle_(lifecycle) {} + +ImageExternalTexture::~ImageExternalTexture() = default; + +// Implementing flutter::Texture. +void ImageExternalTexture::Paint(PaintContext& context, + const DlRect& bounds, + bool freeze, + const DlImageSampling sampling) { + if (state_ == AttachmentState::kDetached) { + return; + } + Attach(context); + const bool should_process_frame = !freeze; + if (should_process_frame) { + ProcessFrame(context, ToSkRect(bounds)); + } + if (dl_image_) { + context.canvas->DrawImageRect( + dl_image_, // image + DlRect::Make(dl_image_->GetBounds()), // source rect + bounds, // destination rect + sampling, // sampling + context.paint, // paint + flutter::DlSrcRectConstraint::kStrict // enforce edges + ); + } else { + FML_LOG(INFO) << "No DlImage available for ImageExternalTexture to paint."; + } +} + +// Implementing flutter::Texture. +void ImageExternalTexture::MarkNewFrameAvailable() { + // NOOP. +} + +// Implementing flutter::Texture. +void ImageExternalTexture::OnTextureUnregistered() {} + +// Implementing flutter::ContextListener. +void ImageExternalTexture::OnGrContextCreated() { + state_ = AttachmentState::kUninitialized; +} + +// Implementing flutter::ContextListener. +void ImageExternalTexture::OnGrContextDestroyed() { + if (state_ == AttachmentState::kAttached) { + switch (texture_lifecycle_) { + case ImageLifecycle::kReset: { + dl_image_.reset(); + image_lru_.Clear(); + } break; + case ImageLifecycle::kKeepAlive: + // Intentionally do nothing. + /// + // If we reset the image, we are not able to re-acquire it, but the + // producer of the image will not know to reproduce it, resulting in a + // blank image. See https://github.com/flutter/flutter/issues/163561. + break; + } + Detach(); + } + state_ = AttachmentState::kDetached; +} + +JavaLocalRef ImageExternalTexture::AcquireLatestImage() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + FML_CHECK(env != nullptr); + + // ImageTextureEntry.acquireLatestImage. + JavaLocalRef image_java = + jni_facade_->ImageProducerTextureEntryAcquireLatestImage( + JavaLocalRef(image_texture_entry_)); + return image_java; +} + +void ImageExternalTexture::CloseImage(const fml::jni::JavaRef& image) { + if (image.obj() == nullptr) { + return; + } + jni_facade_->ImageClose(JavaLocalRef(image)); +} + +void ImageExternalTexture::CloseHardwareBuffer( + const fml::jni::JavaRef& hardware_buffer) { + if (hardware_buffer.obj() == nullptr) { + return; + } + jni_facade_->HardwareBufferClose(JavaLocalRef(hardware_buffer)); +} + +JavaLocalRef ImageExternalTexture::HardwareBufferFor( + const fml::jni::JavaRef& image) { + if (image.obj() == nullptr) { + return JavaLocalRef(); + } + // Image.getHardwareBuffer. + return jni_facade_->ImageGetHardwareBuffer(JavaLocalRef(image)); +} + +AHardwareBuffer* ImageExternalTexture::AHardwareBufferFor( + const fml::jni::JavaRef& hardware_buffer) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + FML_CHECK(env != nullptr); + const auto& proc = + impeller::android::GetProcTable().AHardwareBuffer_fromHardwareBuffer; + return proc ? proc(env, hardware_buffer.obj()) : nullptr; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture.h b/flutter/engine/src/flutter/shell/platform/android/image_external_texture.h new file mode 100644 index 0000000000000000000000000000000000000000..96b78ed68f3dfb779cc138b247fc422e9a9b5490 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture.h @@ -0,0 +1,113 @@ +// 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_ANDROID_IMAGE_EXTERNAL_TEXTURE_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_H_ + +#include "flutter/common/graphics/texture.h" +#include "flutter/fml/logging.h" +#include "flutter/shell/platform/android/image_lru.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/platform_view_android_jni_impl.h" + +#include +#include + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief External texture peered to a sequence of +/// android.hardware.HardwareBuffers. +/// +/// Android Hardware Buffers are available on newer versions of +/// Android (API 29 and above). +/// +/// This is an abstract base class and graphics packages provide +/// concrete implementations of this class that bind hardware +/// buffers to their own package-specific implementations of +/// textures (SkImages, impeller::Texture, etc...). +/// +/// Android Hardware Buffers allow binding to both OpenGL and Vulkan +/// client-rendering APIs in a zero copy manner. Because of this +/// graphics packages that support OpenGL and Vulkan can have +/// multiple subclasses for each supported client-rendering API. +/// +class ImageExternalTexture : public flutter::Texture { + public: + /// Whether the last image should be reset when the context is destroyed. + enum class ImageLifecycle { kReset, kKeepAlive }; + + explicit ImageExternalTexture( + int64_t id, + const fml::jni::ScopedJavaGlobalRef& image_texture_entry, + const std::shared_ptr& jni_facade, + ImageLifecycle lifecycle); + + // |flutter::Texture| + virtual ~ImageExternalTexture(); + + protected: + //---------------------------------------------------------------------------- + /// @brief Subclasses override this method to bind the latest + /// representation of the hardware buffer wrapped by this texture + /// instance to their own graphics package specific texture + /// classes (SkImage, impeller::Texture, etc...). + /// + /// After a call to this method, attachment state of this instance + /// must be kAttached. That is the responsibility of the subclass. + /// + /// @param context The context + /// @param[in] bounds The bounds + /// + virtual void ProcessFrame(PaintContext& context, const SkRect& bounds) = 0; + + virtual void Attach(PaintContext& context) = 0; + + virtual void Detach() = 0; + + JavaLocalRef AcquireLatestImage(); + + void CloseImage(const fml::jni::JavaRef& image); + + JavaLocalRef HardwareBufferFor(const fml::jni::JavaRef& image); + + void CloseHardwareBuffer(const fml::jni::JavaRef& hardware_buffer); + + AHardwareBuffer* AHardwareBufferFor( + const fml::jni::JavaRef& hardware_buffer); + + fml::jni::ScopedJavaGlobalRef image_texture_entry_; + std::shared_ptr jni_facade_; + + enum class AttachmentState { kUninitialized, kAttached, kDetached }; + AttachmentState state_ = AttachmentState::kUninitialized; + sk_sp dl_image_; + ImageLRU image_lru_ = ImageLRU(); + + private: + // |flutter::Texture|. + void Paint(PaintContext& context, + const DlRect& bounds, + bool freeze, + const DlImageSampling sampling) override; + + // |flutter::Texture|. + void MarkNewFrameAvailable() override; + + // |flutter::Texture| + void OnTextureUnregistered() override; + + // |flutter::ContextListener| + void OnGrContextCreated() override; + + // |flutter::ContextListener| + void OnGrContextDestroyed() override; + + const ImageLifecycle texture_lifecycle_; + FML_DISALLOW_COPY_AND_ASSIGN(ImageExternalTexture); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl.cc b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl.cc new file mode 100644 index 0000000000000000000000000000000000000000..21cf09ae59e9476339e33f475b939a5fbd797149 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl.cc @@ -0,0 +1,115 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/image_external_texture_gl.h" + +#include +#include + +#include "flutter/common/graphics/texture.h" +#include "flutter/impeller/core/formats.h" +#include "flutter/impeller/display_list/dl_image_impeller.h" +#include "flutter/impeller/toolkit/android/hardware_buffer.h" +#include "flutter/impeller/toolkit/egl/image.h" +#include "flutter/impeller/toolkit/gles/texture.h" +#include "third_party/skia/include/core/SkAlphaType.h" +#include "third_party/skia/include/core/SkColorType.h" +#include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" +#include "third_party/skia/include/gpu/ganesh/gl/GrGLTypes.h" + +namespace flutter { + +ImageExternalTextureGL::ImageExternalTextureGL( + int64_t id, + const fml::jni::ScopedJavaGlobalRef& image_texture_entry, + const std::shared_ptr& jni_facade, + ImageExternalTexture::ImageLifecycle lifecycle) + : ImageExternalTexture(id, image_texture_entry, jni_facade, lifecycle) {} + +void ImageExternalTextureGL::Attach(PaintContext& context) { + if (state_ == AttachmentState::kUninitialized) { + // TODO(johnmccurtchan): We currently display the first frame after an + // attach-detach cycle as blank. There seems to be an issue on some + // devices where ImageReaders/Images from before the detach aren't + // valid after the attach. According to Android folks this doesn't + // match the spec. Revisit this in the future. + // See https://github.com/flutter/flutter/issues/142978 and + // https://github.com/flutter/flutter/issues/139039. + state_ = AttachmentState::kAttached; + } +} + +void ImageExternalTextureGL::UpdateImage(JavaLocalRef& hardware_buffer, + const SkRect& bounds, + PaintContext& context) { + AHardwareBuffer* latest_hardware_buffer = AHardwareBufferFor(hardware_buffer); + std::optional key = + impeller::android::HardwareBuffer::GetSystemUniqueID( + latest_hardware_buffer); + auto existing_image = image_lru_.FindImage(key); + if (existing_image != nullptr) { + dl_image_ = existing_image; + return; + } + + auto egl_image = CreateEGLImage(latest_hardware_buffer); + if (!egl_image.is_valid()) { + return; + } + + dl_image_ = CreateDlImage(context, bounds, key, std::move(egl_image)); + if (key.has_value()) { + gl_entries_.erase(image_lru_.AddImage(dl_image_, key.value())); + } +} + +void ImageExternalTextureGL::ProcessFrame(PaintContext& context, + const SkRect& bounds) { + JavaLocalRef image = AcquireLatestImage(); + if (image.is_null()) { + return; + } + JavaLocalRef hardware_buffer = HardwareBufferFor(image); + UpdateImage(hardware_buffer, bounds, context); + CloseHardwareBuffer(hardware_buffer); +} + +void ImageExternalTextureGL::Detach() { + image_lru_.Clear(); + gl_entries_.clear(); +} + +impeller::UniqueEGLImageKHR ImageExternalTextureGL::CreateEGLImage( + AHardwareBuffer* hardware_buffer) { + if (hardware_buffer == nullptr) { + return impeller::UniqueEGLImageKHR(); + } + + EGLDisplay display = eglGetCurrentDisplay(); + if (display == EGL_NO_DISPLAY) { + // This could happen when running in a deferred task that executes after + // the thread has lost its EGL state. + return impeller::UniqueEGLImageKHR(); + } + + EGLClientBuffer client_buffer = + impeller::android::GetProcTable().eglGetNativeClientBufferANDROID( + hardware_buffer); + FML_DCHECK(client_buffer != nullptr); + if (client_buffer == nullptr) { + FML_LOG(ERROR) << "eglGetNativeClientBufferAndroid returned null."; + return impeller::UniqueEGLImageKHR(); + } + + impeller::EGLImageKHRWithDisplay maybe_image = + impeller::EGLImageKHRWithDisplay{ + eglCreateImageKHR(display, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, + client_buffer, 0), + display}; + + return impeller::UniqueEGLImageKHR(maybe_image); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl.h b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl.h new file mode 100644 index 0000000000000000000000000000000000000000..ccb9d7d485f7d9f298d13defcfab7575326363e8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl.h @@ -0,0 +1,63 @@ +// 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_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_H_ + +#include +#include +#include + +#include "flutter/impeller/toolkit/egl/image.h" +#include "flutter/impeller/toolkit/gles/texture.h" +#include "flutter/shell/platform/android/image_external_texture.h" + +namespace flutter { + +class ImageExternalTextureGL : public ImageExternalTexture { + public: + ImageExternalTextureGL( + int64_t id, + const fml::jni::ScopedJavaGlobalRef& image_textury_entry, + const std::shared_ptr& jni_facade, + ImageExternalTexture::ImageLifecycle lifecycle); + + protected: + // |ImageExternalTexture| + void Attach(PaintContext& context) override; + + // |ImageExternalTexture| + void Detach() override; + + // |ImageExternalTexture| + void ProcessFrame(PaintContext& context, const SkRect& bounds) override; + + virtual sk_sp CreateDlImage( + PaintContext& context, + const SkRect& bounds, + std::optional id, + impeller::UniqueEGLImageKHR&& egl_image) = 0; + + void UpdateImage(JavaLocalRef& hardware_buffer, + const SkRect& bounds, + PaintContext& context); + + impeller::UniqueEGLImageKHR CreateEGLImage(AHardwareBuffer* buffer); + + struct GlEntry { + impeller::UniqueEGLImageKHR egl_image; + impeller::UniqueGLTexture texture; + }; + + // Each GL entry is keyed off of the currently active + // hardware buffers and evicted when the hardware buffer + // is removed from the LRU cache. + std::unordered_map gl_entries_; + + FML_DISALLOW_COPY_AND_ASSIGN(ImageExternalTextureGL); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_impeller.cc b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..1deb2f56b04deb399643a39f4f3395f3ee9a8522 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_impeller.cc @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/image_external_texture_gl_impeller.h" + +#include "flutter/impeller/display_list/dl_image_impeller.h" +#include "flutter/impeller/renderer/backend/gles/texture_gles.h" + +namespace flutter { + +ImageExternalTextureGLImpeller::ImageExternalTextureGLImpeller( + const std::shared_ptr& context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& image_textury_entry, + const std::shared_ptr& jni_facade, + ImageExternalTexture::ImageLifecycle lifecycle) + : ImageExternalTextureGL(id, image_textury_entry, jni_facade, lifecycle), + impeller_context_(context) {} + +void ImageExternalTextureGLImpeller::Detach() {} + +void ImageExternalTextureGLImpeller::Attach(PaintContext& context) { + if (state_ == AttachmentState::kUninitialized) { + ImageExternalTextureGL::Attach(context); + } +} + +sk_sp ImageExternalTextureGLImpeller::CreateDlImage( + PaintContext& context, + const SkRect& bounds, + std::optional id, + impeller::UniqueEGLImageKHR&& egl_image) { + impeller::TextureDescriptor desc; + desc.type = impeller::TextureType::kTextureExternalOES; + desc.storage_mode = impeller::StorageMode::kDevicePrivate; + desc.format = impeller::PixelFormat::kR8G8B8A8UNormInt; + desc.size = {static_cast(bounds.width()), + static_cast(bounds.height())}; + desc.mip_count = 1; + auto texture = std::make_shared( + impeller_context_->GetReactor(), desc); + // The contents will be initialized later in the call to + // `glEGLImageTargetTexture2DOES` instead of by Impeller. + texture->MarkContentsInitialized(); + texture->SetCoordinateSystem( + impeller::TextureCoordinateSystem::kUploadFromHost); + if (!texture->Bind()) { + return nullptr; + } + // Associate the hardware buffer image with the texture. + glEGLImageTargetTexture2DOES( + GL_TEXTURE_EXTERNAL_OES, + static_cast(egl_image.get().image)); + gl_entries_[id.value_or(0)] = GlEntry{ + .egl_image = std::move(egl_image), + }; + return impeller::DlImageImpeller::Make(texture); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_impeller.h b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..e02a04ea684ef73991e06b925a2beb333766b851 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_impeller.h @@ -0,0 +1,49 @@ +// 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_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_IMPELLER_H_ + +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/impeller/renderer/backend/gles/context_gles.h" +#include "flutter/shell/platform/android/image_external_texture_gl.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { + +class ImageExternalTextureGLImpeller : public ImageExternalTextureGL { + public: + ImageExternalTextureGLImpeller( + const std::shared_ptr& context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& + hardware_buffer_texture_entry, + const std::shared_ptr& jni_facade, + ImageExternalTexture::ImageLifecycle lifecycle); + + private: + // |ImageExternalTexture| + void Attach(PaintContext& context) override; + + // |ImageExternalTexture| + void Detach() override; + + // |ImageExternalTextureGL| + sk_sp CreateDlImage( + PaintContext& context, + const SkRect& bounds, + std::optional id, + impeller::UniqueEGLImageKHR&& egl_image) override; + + const std::shared_ptr impeller_context_; + + FML_DISALLOW_COPY_AND_ASSIGN(ImageExternalTextureGLImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_skia.cc b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..bf27acc7a8300211aaa57b23891141112c0c0226 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_skia.cc @@ -0,0 +1,67 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/image_external_texture_gl_skia.h" + +#include "flutter/third_party/skia/include/gpu/ganesh/SkImageGanesh.h" +#include "flutter/third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" + +namespace flutter { + +ImageExternalTextureGLSkia::ImageExternalTextureGLSkia( + const std::shared_ptr& context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& image_texture_entry, + const std::shared_ptr& jni_facade, + ImageExternalTexture::ImageLifecycle lifecycle) + : ImageExternalTextureGL(id, image_texture_entry, jni_facade, lifecycle) {} + +void ImageExternalTextureGLSkia::Attach(PaintContext& context) { + if (state_ == AttachmentState::kUninitialized) { + // After this call state_ will be AttachmentState::kAttached and egl_image_ + // will have been created if we still have an Image associated with us. + ImageExternalTextureGL::Attach(context); + } +} + +void ImageExternalTextureGLSkia::Detach() { + ImageExternalTextureGL::Detach(); +} + +void ImageExternalTextureGLSkia::BindImageToTexture( + const impeller::UniqueEGLImageKHR& image, + GLuint tex) { + if (!image.is_valid() || tex == 0) { + return; + } + glBindTexture(GL_TEXTURE_EXTERNAL_OES, tex); + glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, + static_cast(image.get().image)); +} + +sk_sp ImageExternalTextureGLSkia::CreateDlImage( + PaintContext& context, + const SkRect& bounds, + std::optional id, + impeller::UniqueEGLImageKHR&& egl_image) { + GLuint texture_name; + glGenTextures(1, &texture_name); + auto gl_texture = impeller::GLTexture{texture_name}; + impeller::UniqueGLTexture unique_texture; + unique_texture.reset(gl_texture); + + BindImageToTexture(egl_image, unique_texture.get().texture_name); + GrGLTextureInfo textureInfo = { + GL_TEXTURE_EXTERNAL_OES, unique_texture.get().texture_name, GL_RGBA8_OES}; + auto backendTexture = + GrBackendTextures::MakeGL(1, 1, skgpu::Mipmapped::kNo, textureInfo); + + gl_entries_[id.value_or(0)] = GlEntry{.egl_image = std::move(egl_image), + .texture = std::move(unique_texture)}; + return DlImage::Make(SkImages::BorrowTextureFrom( + context.gr_context, backendTexture, kTopLeft_GrSurfaceOrigin, + kRGBA_8888_SkColorType, kPremul_SkAlphaType, nullptr)); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_skia.h b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..722c92b27edefdd5d7a6bd9f223f1368739b923b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_gl_skia.h @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_SKIA_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_SKIA_H_ + +#include +#include + +#include "flutter/shell/platform/android/android_context_gl_skia.h" +#include "flutter/shell/platform/android/image_external_texture_gl.h" + +namespace flutter { + +class ImageExternalTextureGLSkia : public ImageExternalTextureGL { + public: + ImageExternalTextureGLSkia( + const std::shared_ptr& context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& image_textury_entry, + const std::shared_ptr& jni_facade, + ImageExternalTexture::ImageLifecycle lifecycle); + + private: + // |ImageExternalTexture| + void Attach(PaintContext& context) override; + + // |ImageExternalTexture| + void Detach() override; + + // |ImageExternalTextureGL| + sk_sp CreateDlImage( + PaintContext& context, + const SkRect& bounds, + std::optional id, + impeller::UniqueEGLImageKHR&& egl_image) override; + + void BindImageToTexture(const impeller::UniqueEGLImageKHR& image, GLuint tex); + + FML_DISALLOW_COPY_AND_ASSIGN(ImageExternalTextureGLSkia); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_GL_SKIA_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture_vk_impeller.cc b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_vk_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..557cc19402b487c4061f5f7d0025c94de1b918b1 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_vk_impeller.cc @@ -0,0 +1,103 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/image_external_texture_vk_impeller.h" + +#include + +#include "flutter/impeller/core/formats.h" +#include "flutter/impeller/core/texture_descriptor.h" +#include "flutter/impeller/display_list/dl_image_impeller.h" +#include "flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h" +#include "flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "flutter/impeller/renderer/backend/vulkan/texture_vk.h" +#include "flutter/impeller/toolkit/android/hardware_buffer.h" + +namespace flutter { + +ImageExternalTextureVKImpeller::ImageExternalTextureVKImpeller( + const std::shared_ptr& impeller_context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& image_texture_entry, + const std::shared_ptr& jni_facade, + ImageExternalTexture::ImageLifecycle lifecycle) + : ImageExternalTexture(id, image_texture_entry, jni_facade, lifecycle), + impeller_context_(impeller_context) {} + +ImageExternalTextureVKImpeller::~ImageExternalTextureVKImpeller() {} + +void ImageExternalTextureVKImpeller::Attach(PaintContext& context) { + if (state_ == AttachmentState::kUninitialized) { + // First processed frame we are attached. + state_ = AttachmentState::kAttached; + } +} + +void ImageExternalTextureVKImpeller::Detach() {} + +void ImageExternalTextureVKImpeller::ProcessFrame(PaintContext& context, + const SkRect& bounds) { + JavaLocalRef image = AcquireLatestImage(); + if (image.is_null()) { + return; + } + JavaLocalRef hardware_buffer = HardwareBufferFor(image); + AHardwareBuffer* latest_hardware_buffer = AHardwareBufferFor(hardware_buffer); + + auto hb_desc = + impeller::android::HardwareBuffer::Describe(latest_hardware_buffer); + std::optional key = + impeller::android::HardwareBuffer::GetSystemUniqueID( + latest_hardware_buffer); + auto existing_image = image_lru_.FindImage(key); + if (existing_image != nullptr || !hb_desc.has_value()) { + dl_image_ = existing_image; + + CloseHardwareBuffer(hardware_buffer); + return; + } + + auto texture_source = std::make_shared( + impeller_context_, latest_hardware_buffer, hb_desc.value()); + if (!texture_source->IsValid()) { + CloseHardwareBuffer(hardware_buffer); + return; + } + + auto texture = + std::make_shared(impeller_context_, texture_source); + // Transition the layout to shader read. + { + auto buffer = impeller_context_->CreateCommandBuffer(); + impeller::CommandBufferVK& buffer_vk = + impeller::CommandBufferVK::Cast(*buffer); + + impeller::BarrierVK barrier; + barrier.cmd_buffer = buffer_vk.GetCommandBuffer(); + barrier.src_access = impeller::vk::AccessFlagBits::eColorAttachmentWrite | + impeller::vk::AccessFlagBits::eTransferWrite; + barrier.src_stage = + impeller::vk::PipelineStageFlagBits::eColorAttachmentOutput | + impeller::vk::PipelineStageFlagBits::eTransfer; + barrier.dst_access = impeller::vk::AccessFlagBits::eShaderRead; + barrier.dst_stage = impeller::vk::PipelineStageFlagBits::eFragmentShader; + + barrier.new_layout = impeller::vk::ImageLayout::eShaderReadOnlyOptimal; + + if (!texture->SetLayout(barrier)) { + return; + } + if (!impeller_context_->GetCommandQueue()->Submit({buffer}).ok()) { + return; + } + } + + dl_image_ = impeller::DlImageImpeller::Make(texture); + if (key.has_value()) { + image_lru_.AddImage(dl_image_, key.value()); + } + CloseHardwareBuffer(hardware_buffer); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/image_external_texture_vk_impeller.h b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_vk_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..8e102d2ce67b12764eed80c700302b6438ca674a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_external_texture_vk_impeller.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_VK_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_VK_IMPELLER_H_ + +#include +#include +#include "flutter/shell/platform/android/image_external_texture.h" + +#include "flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h" +#include "flutter/impeller/renderer/backend/vulkan/context_vk.h" +#include "flutter/impeller/renderer/backend/vulkan/vk.h" +#include "flutter/shell/platform/android/android_context_vk_impeller.h" + +namespace flutter { + +class ImageExternalTextureVKImpeller : public ImageExternalTexture { + public: + ImageExternalTextureVKImpeller( + const std::shared_ptr& impeller_context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& + hardware_buffer_texture_entry, + const std::shared_ptr& jni_facade, + ImageExternalTexture::ImageLifecycle lifecycle); + + ~ImageExternalTextureVKImpeller() override; + + private: + void Attach(PaintContext& context) override; + void ProcessFrame(PaintContext& context, const SkRect& bounds) override; + void Detach() override; + + const std::shared_ptr impeller_context_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_EXTERNAL_TEXTURE_VK_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/image_lru.cc b/flutter/engine/src/flutter/shell/platform/android/image_lru.cc new file mode 100644 index 0000000000000000000000000000000000000000..6971483e034a071b777fd086650099435d983ae6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_lru.cc @@ -0,0 +1,66 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/image_lru.h" + +namespace flutter { + +sk_sp ImageLRU::FindImage( + std::optional key) { + if (!key.has_value()) { + return nullptr; + } + auto key_value = key.value(); + for (size_t i = 0u; i < kImageReaderSwapchainSize; i++) { + if (images_[i].key == key_value) { + auto result = images_[i].value; + UpdateKey(result, key_value); + return result; + } + } + return nullptr; +} + +void ImageLRU::UpdateKey(const sk_sp& image, + HardwareBufferKey key) { + if (images_[0].key == key) { + return; + } + size_t i = 1u; + for (; i < kImageReaderSwapchainSize; i++) { + if (images_[i].key == key) { + break; + } + } + for (auto j = i; j > 0; j--) { + images_[j] = images_[j - 1]; + } + images_[0] = Data{.key = key, .value = image}; +} + +HardwareBufferKey ImageLRU::AddImage(const sk_sp& image, + HardwareBufferKey key) { + HardwareBufferKey lru_key = images_[kImageReaderSwapchainSize - 1].key; + bool updated_image = false; + for (size_t i = 0u; i < kImageReaderSwapchainSize; i++) { + if (images_[i].key == lru_key) { + updated_image = true; + images_[i] = Data{.key = key, .value = image}; + break; + } + } + if (!updated_image) { + images_[0] = Data{.key = key, .value = image}; + } + UpdateKey(image, key); + return lru_key; +} + +void ImageLRU::Clear() { + for (size_t i = 0u; i < kImageReaderSwapchainSize; i++) { + images_[i] = Data{.key = 0u, .value = nullptr}; + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/image_lru.h b/flutter/engine/src/flutter/shell/platform/android/image_lru.h new file mode 100644 index 0000000000000000000000000000000000000000..63829efb970accffd01e2847a0d264116312a090 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_lru.h @@ -0,0 +1,57 @@ +// 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_ANDROID_IMAGE_LRU_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_LRU_H_ + +#include +#include + +#include "display_list/image/dl_image.h" + +namespace flutter { + +// This value needs to be larger than the number of swapchain images +// that a typical image reader will produce to ensure that we effectively +// cache. If the value is too small, we will unnecessarily churn through +// images, while if it is too large we may retain images longer than +// necessary. +static constexpr size_t kImageReaderSwapchainSize = 6u; + +using HardwareBufferKey = uint64_t; + +class ImageLRU { + public: + ImageLRU() = default; + + ~ImageLRU() = default; + + /// @brief Retrieve the image associated with the given [key], or nullptr. + sk_sp FindImage(std::optional key); + + /// @brief Add a new image to the cache with a key, returning the key of the + /// LRU entry that was removed. + /// + /// The value may be `0`, in which case nothing was removed. + HardwareBufferKey AddImage(const sk_sp& image, + HardwareBufferKey key); + + /// @brief Remove all entires from the image cache. + void Clear(); + + private: + /// @brief Marks [key] as the most recently used. + void UpdateKey(const sk_sp& image, HardwareBufferKey key); + + struct Data { + HardwareBufferKey key = 0u; + sk_sp value; + }; + + std::array images_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_IMAGE_LRU_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/image_lru_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/image_lru_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..d97edfdffc5f756e7a2aaca2bbfd1f88244bdf67 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/image_lru_unittests.cc @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/image_lru.h" +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +TEST(ImageLRU, CanStoreSingleImage) { + auto image = DlImage::Make(nullptr); + ImageLRU image_lru; + + EXPECT_EQ(image_lru.FindImage(1), nullptr); + + image_lru.AddImage(image, 1); + + EXPECT_EQ(image_lru.FindImage(1), image); +} + +TEST(ImageLRU, EvictsLRU) { + auto image = DlImage::Make(nullptr); + ImageLRU image_lru; + + // Fill up the cache, nothing is removed + for (auto i = 0u; i < kImageReaderSwapchainSize; i++) { + EXPECT_EQ(image_lru.AddImage(image, i + 1), 0u); + } + // Confirm each image is in the cache. This should keep the LRU + // order the same. + for (auto i = 0u; i < kImageReaderSwapchainSize; i++) { + EXPECT_EQ(image_lru.FindImage(i + 1), image); + } + + // Insert new image and verify least recently used was removed. + EXPECT_EQ(image_lru.AddImage(image, 100), 1u); +} + +TEST(ImageLRU, CanClear) { + auto image = DlImage::Make(nullptr); + ImageLRU image_lru; + + // Fill up the cache, nothing is removed + for (auto i = 0u; i < kImageReaderSwapchainSize; i++) { + EXPECT_EQ(image_lru.AddImage(image, i + 1), 0u); + } + image_lru.Clear(); + + // Expect no cache entries. + for (auto i = 0u; i < kImageReaderSwapchainSize; i++) { + EXPECT_EQ(image_lru.FindImage(i + 1), nullptr); + } +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/library_loader.cc b/flutter/engine/src/flutter/shell/platform/android/library_loader.cc new file mode 100644 index 0000000000000000000000000000000000000000..644bd5de3b8ec1d20343a7e44daff64443e64bf8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/library_loader.cc @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/platform/android/jni_util.h" +#include "flutter/shell/platform/android/android_image_generator.h" +#include "flutter/shell/platform/android/flutter_main.h" +#include "flutter/shell/platform/android/platform_view_android.h" +#include "flutter/shell/platform/android/vsync_waiter_android.h" + +// This is called by the VM when the shared library is first loaded. +JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { + // Initialize the Java VM. + fml::jni::InitJavaVM(vm); + + JNIEnv* env = fml::jni::AttachCurrentThread(); + bool result = false; + + // Register FlutterMain. + result = flutter::FlutterMain::Register(env); + FML_CHECK(result); + + // Register PlatformView + result = flutter::PlatformViewAndroid::Register(env); + FML_CHECK(result); + + // Register VSyncWaiter. + result = flutter::VsyncWaiterAndroid::Register(env); + FML_CHECK(result); + + // Register AndroidImageDecoder. + result = flutter::AndroidImageGenerator::Register(env); + FML_CHECK(result); + + return JNI_VERSION_1_4; +} diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_message_handler_android.cc b/flutter/engine/src/flutter/shell/platform/android/platform_message_handler_android.cc new file mode 100644 index 0000000000000000000000000000000000000000..1f8f191ff2b0c468240591aec03d459e9d0349a6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_message_handler_android.cc @@ -0,0 +1,69 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/platform_message_handler_android.h" + +namespace flutter { + +PlatformMessageHandlerAndroid::PlatformMessageHandlerAndroid( + const std::shared_ptr& jni_facade) + : jni_facade_(jni_facade) {} + +void PlatformMessageHandlerAndroid::InvokePlatformMessageResponseCallback( + int response_id, + std::unique_ptr mapping) { + // Called from any thread. + if (!response_id) { + return; + } + // TODO(gaaclarke): Move the jump to the ui thread here from + // PlatformMessageResponseDart so we won't need to use a mutex anymore. + fml::RefPtr message_response; + { + std::lock_guard lock(pending_responses_mutex_); + auto it = pending_responses_.find(response_id); + if (it == pending_responses_.end()) { + return; + } + message_response = std::move(it->second); + pending_responses_.erase(it); + } + + message_response->Complete(std::move(mapping)); +} + +void PlatformMessageHandlerAndroid::InvokePlatformMessageEmptyResponseCallback( + int response_id) { + // Called from any thread. + if (!response_id) { + return; + } + fml::RefPtr message_response; + { + std::lock_guard lock(pending_responses_mutex_); + auto it = pending_responses_.find(response_id); + if (it == pending_responses_.end()) { + return; + } + message_response = std::move(it->second); + pending_responses_.erase(it); + } + message_response->CompleteEmpty(); +} + +// |PlatformView| +void PlatformMessageHandlerAndroid::HandlePlatformMessage( + std::unique_ptr message) { + // Called from any thread. + int response_id = next_response_id_.fetch_add(1); + if (auto response = message->response()) { + std::lock_guard lock(pending_responses_mutex_); + pending_responses_[response_id] = response; + } + // This call can re-enter in InvokePlatformMessageXxxResponseCallback. + jni_facade_->FlutterViewHandlePlatformMessage(std::move(message), + response_id); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_message_handler_android.h b/flutter/engine/src/flutter/shell/platform/android/platform_message_handler_android.h new file mode 100644 index 0000000000000000000000000000000000000000..2833e6cc56ea06e9318de677eab267a5cda94da0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_message_handler_android.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_MESSAGE_HANDLER_ANDROID_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_MESSAGE_HANDLER_ANDROID_H_ + +#include +#include +#include +#include + +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/shell/common/platform_message_handler.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { +class PlatformMessageHandlerAndroid : public PlatformMessageHandler { + public: + explicit PlatformMessageHandlerAndroid( + const std::shared_ptr& jni_facade); + void HandlePlatformMessage(std::unique_ptr message) override; + bool DoesHandlePlatformMessageOnPlatformThread() const override { + return false; + } + void InvokePlatformMessageResponseCallback( + int response_id, + std::unique_ptr mapping) override; + + void InvokePlatformMessageEmptyResponseCallback(int response_id) override; + + private: + const std::shared_ptr jni_facade_; + std::atomic next_response_id_ = 1; + std::unordered_map> + pending_responses_; + std::mutex pending_responses_mutex_; +}; +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_MESSAGE_HANDLER_ANDROID_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_message_response_android.cc b/flutter/engine/src/flutter/shell/platform/android/platform_message_response_android.cc new file mode 100644 index 0000000000000000000000000000000000000000..6c88b85e6e32d446f07e1149a83dd4b522c2e268 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_message_response_android.cc @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/platform_message_response_android.h" + +#include + +#include "flutter/fml/make_copyable.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { + +PlatformMessageResponseAndroid::PlatformMessageResponseAndroid( + int response_id, + std::shared_ptr jni_facade, + fml::RefPtr platform_task_runner) + : response_id_(response_id), + jni_facade_(std::move(jni_facade)), + platform_task_runner_(std::move(platform_task_runner)) {} + +PlatformMessageResponseAndroid::~PlatformMessageResponseAndroid() = default; + +// |flutter::PlatformMessageResponse| +void PlatformMessageResponseAndroid::Complete( + std::unique_ptr data) { + platform_task_runner_->PostTask( + fml::MakeCopyable([response_id = response_id_, // + data = std::move(data), // + jni_facade = jni_facade_]() mutable { + jni_facade->FlutterViewHandlePlatformMessageResponse(response_id, + std::move(data)); + })); +} + +// |flutter::PlatformMessageResponse| +void PlatformMessageResponseAndroid::CompleteEmpty() { + platform_task_runner_->PostTask( + fml::MakeCopyable([response_id = response_id_, // + jni_facade = jni_facade_ // + ]() { + // Make the response call into Java. + jni_facade->FlutterViewHandlePlatformMessageResponse(response_id, + nullptr); + })); +} +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_message_response_android.h b/flutter/engine/src/flutter/shell/platform/android/platform_message_response_android.h new file mode 100644 index 0000000000000000000000000000000000000000..5b13e4bd268aea60bed76442616a56619054e214 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_message_response_android.h @@ -0,0 +1,42 @@ +// 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_ANDROID_PLATFORM_MESSAGE_RESPONSE_ANDROID_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_MESSAGE_RESPONSE_ANDROID_H_ + +#include "flutter/fml/macros.h" +#include "flutter/fml/platform/android/jni_weak_ref.h" +#include "flutter/fml/task_runner.h" +#include "flutter/lib/ui/window/platform_message_response.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { + +class PlatformMessageResponseAndroid : public flutter::PlatformMessageResponse { + public: + // |flutter::PlatformMessageResponse| + void Complete(std::unique_ptr data) override; + + // |flutter::PlatformMessageResponse| + void CompleteEmpty() override; + + private: + PlatformMessageResponseAndroid( + int response_id, + std::shared_ptr jni_facade, + fml::RefPtr platform_task_runner); + + ~PlatformMessageResponseAndroid() override; + + const int response_id_; + const std::shared_ptr jni_facade_; + const fml::RefPtr platform_task_runner_; + + FML_FRIEND_MAKE_REF_COUNTED(PlatformMessageResponseAndroid); + FML_DISALLOW_COPY_AND_ASSIGN(PlatformMessageResponseAndroid); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_MESSAGE_RESPONSE_ANDROID_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_view_android.cc b/flutter/engine/src/flutter/shell/platform/android/platform_view_android.cc new file mode 100644 index 0000000000000000000000000000000000000000..5d438df9805ba86f8dd359e52d286372781c515b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_view_android.cc @@ -0,0 +1,520 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/platform_view_android.h" + +#include +#include +#include + +#include "common/settings.h" +#include "flutter/common/graphics/texture.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/shell/common/shell_io_manager.h" +#include "flutter/shell/gpu/gpu_surface_gl_delegate.h" +#include "flutter/shell/platform/android/android_context_gl_impeller.h" +#include "flutter/shell/platform/android/android_context_gl_skia.h" +#include "flutter/shell/platform/android/android_context_vk_impeller.h" +#include "flutter/shell/platform/android/android_rendering_selector.h" +#include "flutter/shell/platform/android/android_surface_gl_impeller.h" +#include "flutter/shell/platform/android/android_surface_gl_skia.h" +#include "flutter/shell/platform/android/android_surface_software.h" +#include "flutter/shell/platform/android/image_external_texture_gl_impeller.h" +#include "flutter/shell/platform/android/image_external_texture_gl_skia.h" +#include "flutter/shell/platform/android/surface_texture_external_texture_gl_impeller.h" +#include "flutter/shell/platform/android/surface_texture_external_texture_gl_skia.h" +#include "flutter/shell/platform/android/surface_texture_external_texture_vk_impeller.h" +#include "fml/logging.h" +#include "impeller/display_list/aiks_context.h" +#if IMPELLER_ENABLE_VULKAN // b/258506856 for why this is behind an if +#include "flutter/shell/platform/android/android_surface_vk_impeller.h" +#include "flutter/shell/platform/android/image_external_texture_vk_impeller.h" +#endif +#include "flutter/shell/platform/android/context/android_context.h" +#include "flutter/shell/platform/android/external_view_embedder/external_view_embedder.h" +#include "flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/platform_message_response_android.h" +#include "flutter/shell/platform/android/surface/android_surface.h" +#include "flutter/shell/platform/android/surface/snapshot_surface_producer.h" +#include "flutter/shell/platform/android/vsync_waiter_android.h" + +namespace flutter { + +namespace { + +static constexpr int kMinAPILevelHCPP = 34; +static constexpr int64_t kImplicitViewId = 0; + +AndroidContext::ContextSettings CreateContextSettings( + const Settings& p_settings) { + AndroidContext::ContextSettings settings; + settings.enable_gpu_tracing = p_settings.enable_vulkan_gpu_tracing; + settings.enable_validation = p_settings.enable_vulkan_validation; + settings.enable_surface_control = p_settings.enable_surface_control; + settings.impeller_flags.lazy_shader_mode = + p_settings.impeller_enable_lazy_shader_mode; + settings.impeller_flags.antialiased_lines = + p_settings.impeller_antialiased_lines; + return settings; +} +} // namespace + +AndroidSurfaceFactoryImpl::AndroidSurfaceFactoryImpl( + const std::shared_ptr& context, + bool enable_impeller, + bool lazy_shader_mode) + : android_context_(context), + enable_impeller_(enable_impeller), + lazy_shader_mode_(lazy_shader_mode) {} + +AndroidSurfaceFactoryImpl::~AndroidSurfaceFactoryImpl() = default; + +std::unique_ptr AndroidSurfaceFactoryImpl::CreateSurface() { + switch (android_context_->RenderingApi()) { + case AndroidRenderingAPI::kSoftware: + return std::make_unique(); + case AndroidRenderingAPI::kImpellerOpenGLES: + return std::make_unique( + std::static_pointer_cast(android_context_)); + case AndroidRenderingAPI::kSkiaOpenGLES: + return std::make_unique( + std::static_pointer_cast(android_context_)); + case AndroidRenderingAPI::kImpellerVulkan: + return std::make_unique( + std::static_pointer_cast(android_context_)); + } + FML_UNREACHABLE(); +} + +static std::shared_ptr CreateAndroidContext( + const flutter::TaskRunners& task_runners, + AndroidRenderingAPI android_rendering_api, + bool enable_opengl_gpu_tracing, + const AndroidContext::ContextSettings& settings) { + switch (android_rendering_api) { + case AndroidRenderingAPI::kSoftware: + return std::make_shared(AndroidRenderingAPI::kSoftware); + case AndroidRenderingAPI::kImpellerOpenGLES: + return std::make_unique( + std::make_unique(), + enable_opengl_gpu_tracing); + case AndroidRenderingAPI::kImpellerVulkan: + return std::make_unique(settings); + case AndroidRenderingAPI::kSkiaOpenGLES: + return std::make_unique( + fml::MakeRefCounted(), // + task_runners // + ); + } + FML_UNREACHABLE(); +} + +PlatformViewAndroid::PlatformViewAndroid( + PlatformView::Delegate& delegate, + const flutter::TaskRunners& task_runners, + const std::shared_ptr& jni_facade, + AndroidRenderingAPI rendering_api) + : PlatformViewAndroid( + delegate, + task_runners, + jni_facade, + CreateAndroidContext( + task_runners, + rendering_api, + delegate.OnPlatformViewGetSettings().enable_opengl_gpu_tracing, + CreateContextSettings(delegate.OnPlatformViewGetSettings()))) {} + +PlatformViewAndroid::PlatformViewAndroid( + PlatformView::Delegate& delegate, + const flutter::TaskRunners& task_runners, + const std::shared_ptr& jni_facade, + const std::shared_ptr& android_context) + : PlatformView(delegate, task_runners), + jni_facade_(jni_facade), + android_context_(android_context), + platform_view_android_delegate_(jni_facade), + platform_message_handler_(new PlatformMessageHandlerAndroid(jni_facade)) { + if (android_context_) { + FML_CHECK(android_context_->IsValid()) + << "Could not create surface from invalid Android context."; + surface_factory_ = std::make_shared( + android_context_, // + delegate.OnPlatformViewGetSettings().enable_impeller, // + delegate.OnPlatformViewGetSettings() + .impeller_enable_lazy_shader_mode // + ); + android_surface_ = surface_factory_->CreateSurface(); + android_use_new_platform_view_ = + android_context->RenderingApi() == + AndroidRenderingAPI::kImpellerVulkan && + (android_get_device_api_level() >= kMinAPILevelHCPP) && + delegate.OnPlatformViewGetSettings().enable_surface_control && + impeller::ContextVK::Cast(*android_context->GetImpellerContext()) + .GetShouldEnableSurfaceControlSwapchain(); + FML_CHECK(android_surface_ && android_surface_->IsValid()) + << "Could not create an OpenGL, Vulkan or Software surface to set " + "up " + "rendering."; + } +} + +PlatformViewAndroid::~PlatformViewAndroid() = default; + +void PlatformViewAndroid::NotifyCreated( + fml::RefPtr native_window) { + if (android_surface_) { + InstallFirstFrameCallback(); + + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetRasterTaskRunner(), + [&latch, surface = android_surface_.get(), + native_window = std::move(native_window), jni_facade = jni_facade_]() { + surface->SetNativeWindow(native_window, jni_facade); + latch.Signal(); + }); + latch.Wait(); + } + + PlatformView::NotifyCreated(); +} + +void PlatformViewAndroid::NotifySurfaceWindowChanged( + fml::RefPtr native_window) { + if (android_surface_) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetRasterTaskRunner(), + [&latch, surface = android_surface_.get(), + native_window = std::move(native_window), jni_facade = jni_facade_]() { + surface->TeardownOnScreenContext(); + surface->SetNativeWindow(native_window, jni_facade); + latch.Signal(); + }); + latch.Wait(); + } + + PlatformView::ScheduleFrame(); +} + +void PlatformViewAndroid::NotifyDestroyed() { + PlatformView::NotifyDestroyed(); + + if (android_surface_) { + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetRasterTaskRunner(), + [&latch, surface = android_surface_.get()]() { + surface->TeardownOnScreenContext(); + latch.Signal(); + }); + latch.Wait(); + } +} + +void PlatformViewAndroid::NotifyChanged(const SkISize& size) { + if (!android_surface_) { + return; + } + fml::AutoResetWaitableEvent latch; + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetRasterTaskRunner(), // + [&latch, surface = android_surface_.get(), size]() { + surface->OnScreenSurfaceResize(size); + latch.Signal(); + }); + latch.Wait(); +} + +void PlatformViewAndroid::DispatchPlatformMessage(JNIEnv* env, + std::string name, + jobject java_message_data, + jint java_message_position, + jint response_id) { + uint8_t* message_data = + static_cast(env->GetDirectBufferAddress(java_message_data)); + fml::MallocMapping message = + fml::MallocMapping::Copy(message_data, java_message_position); + + fml::RefPtr response; + if (response_id) { + response = fml::MakeRefCounted( + response_id, jni_facade_, task_runners_.GetPlatformTaskRunner()); + } + + PlatformView::DispatchPlatformMessage( + std::make_unique( + std::move(name), std::move(message), std::move(response))); +} + +void PlatformViewAndroid::DispatchEmptyPlatformMessage(JNIEnv* env, + std::string name, + jint response_id) { + fml::RefPtr response; + if (response_id) { + response = fml::MakeRefCounted( + response_id, jni_facade_, task_runners_.GetPlatformTaskRunner()); + } + + PlatformView::DispatchPlatformMessage( + std::make_unique(std::move(name), + std::move(response))); +} + +// |PlatformView| +void PlatformViewAndroid::HandlePlatformMessage( + std::unique_ptr message) { + // Called from the ui thread. + platform_message_handler_->HandlePlatformMessage(std::move(message)); +} + +// |PlatformView| +void PlatformViewAndroid::OnPreEngineRestart() const { + jni_facade_->FlutterViewOnPreEngineRestart(); +} + +void PlatformViewAndroid::DispatchSemanticsAction(JNIEnv* env, + jint node_id, + jint action, + jobject args, + jint args_position) { + // TODO(team-android): Remove implicit view assumption. + // https://github.com/flutter/flutter/issues/142845 + if (env->IsSameObject(args, NULL)) { + PlatformView::DispatchSemanticsAction( + kImplicitViewId, node_id, static_cast(action), + fml::MallocMapping()); + return; + } + + uint8_t* args_data = static_cast(env->GetDirectBufferAddress(args)); + auto args_vector = fml::MallocMapping::Copy(args_data, args_position); + + PlatformView::DispatchSemanticsAction( + kImplicitViewId, node_id, static_cast(action), + std::move(args_vector)); +} + +// |PlatformView| +void PlatformViewAndroid::UpdateSemantics( + int64_t view_id, + flutter::SemanticsNodeUpdates update, + flutter::CustomAccessibilityActionUpdates actions) { + platform_view_android_delegate_.UpdateSemantics(update, actions); +} + +void PlatformViewAndroid::RegisterExternalTexture( + int64_t texture_id, + const fml::jni::ScopedJavaGlobalRef& surface_texture) { + switch (android_context_->RenderingApi()) { + case AndroidRenderingAPI::kImpellerOpenGLES: + // Impeller GLES. + RegisterTexture(std::make_shared( + std::static_pointer_cast( + android_context_->GetImpellerContext()), // + texture_id, // + surface_texture, // + jni_facade_ // + )); + break; + case AndroidRenderingAPI::kSkiaOpenGLES: + // Legacy GL. + RegisterTexture(std::make_shared( + texture_id, // + surface_texture, // + jni_facade_ // + )); + break; + case AndroidRenderingAPI::kSoftware: + FML_LOG(INFO) << "Software rendering does not support external textures."; + break; + case AndroidRenderingAPI::kImpellerVulkan: + FML_LOG(IMPORTANT) + << "Flutter recommends migrating plugins that create and " + "register surface textures to the new surface producer " + "API. See https://docs.flutter.dev/release/breaking-changes/" + "android-surface-plugins"; + RegisterTexture(std::make_shared( + std::static_pointer_cast( + android_context_->GetImpellerContext()), // + texture_id, // + surface_texture, // + jni_facade_ // + )); + } +} + +void PlatformViewAndroid::RegisterImageTexture( + int64_t texture_id, + const fml::jni::ScopedJavaGlobalRef& image_texture_entry, + ImageExternalTexture::ImageLifecycle lifecycle) { + switch (android_context_->RenderingApi()) { + case AndroidRenderingAPI::kImpellerOpenGLES: + // Impeller GLES. + RegisterTexture(std::make_shared( + std::static_pointer_cast( + android_context_->GetImpellerContext()), + texture_id, image_texture_entry, jni_facade_, lifecycle)); + break; + case AndroidRenderingAPI::kSkiaOpenGLES: + // Legacy GL. + RegisterTexture(std::make_shared( + std::static_pointer_cast(android_context_), + texture_id, image_texture_entry, jni_facade_, lifecycle)); + break; + case AndroidRenderingAPI::kImpellerVulkan: + RegisterTexture(std::make_shared( + std::static_pointer_cast( + android_context_->GetImpellerContext()), + texture_id, image_texture_entry, jni_facade_, lifecycle)); + break; + case AndroidRenderingAPI::kSoftware: + FML_LOG(INFO) << "Software rendering does not support external textures."; + break; + } +} + +// |PlatformView| +std::unique_ptr PlatformViewAndroid::CreateVSyncWaiter() { + return std::make_unique(task_runners_); +} + +// |PlatformView| +std::unique_ptr PlatformViewAndroid::CreateRenderingSurface() { + if (!android_surface_) { + return nullptr; + } + return android_surface_->CreateGPUSurface( + android_context_->GetMainSkiaContext().get()); +} + +// |PlatformView| +std::shared_ptr +PlatformViewAndroid::CreateExternalViewEmbedder() { + if (android_use_new_platform_view_) { + return std::make_shared( + *android_context_, jni_facade_, surface_factory_, task_runners_); + } + return std::make_shared( + *android_context_, jni_facade_, surface_factory_, task_runners_); +} + +// |PlatformView| +std::unique_ptr +PlatformViewAndroid::CreateSnapshotSurfaceProducer() { + if (!android_surface_) { + return nullptr; + } + return std::make_unique(*android_surface_); +} + +// |PlatformView| +sk_sp PlatformViewAndroid::CreateResourceContext() const { + if (!android_surface_) { + return nullptr; + } + sk_sp resource_context; + if (android_surface_->ResourceContextMakeCurrent()) { + // TODO(chinmaygarde): Currently, this code depends on the fact that only + // the OpenGL surface will be able to make a resource context current. If + // this changes, this assumption breaks. Handle the same. + resource_context = ShellIOManager::CreateCompatibleResourceLoadingContext( + GrBackendApi::kOpenGL, + GPUSurfaceGLDelegate::GetDefaultPlatformGLInterface()); + } else { + FML_DLOG(ERROR) << "Could not make the resource context current."; + } + + return resource_context; +} + +// |PlatformView| +void PlatformViewAndroid::ReleaseResourceContext() const { + if (android_surface_) { + android_surface_->ResourceContextClearCurrent(); + } +} + +// |PlatformView| +std::shared_ptr PlatformViewAndroid::GetImpellerContext() + const { + if (android_surface_) { + return android_surface_->GetImpellerContext(); + } + return nullptr; +} + +// |PlatformView| +std::unique_ptr> +PlatformViewAndroid::ComputePlatformResolvedLocales( + const std::vector& supported_locale_data) { + return jni_facade_->FlutterViewComputePlatformResolvedLocale( + supported_locale_data); +} + +// |PlatformView| +void PlatformViewAndroid::RequestDartDeferredLibrary(intptr_t loading_unit_id) { + if (jni_facade_->RequestDartDeferredLibrary(loading_unit_id)) { + return; + } + return; // TODO(garyq): Call LoadDartDeferredLibraryFailure() +} + +// |PlatformView| +void PlatformViewAndroid::LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) { + delegate_.LoadDartDeferredLibrary(loading_unit_id, std::move(snapshot_data), + std::move(snapshot_instructions)); +} + +// |PlatformView| +void PlatformViewAndroid::LoadDartDeferredLibraryError( + intptr_t loading_unit_id, + const std::string error_message, + bool transient) { + delegate_.LoadDartDeferredLibraryError(loading_unit_id, error_message, + transient); +} + +// |PlatformView| +void PlatformViewAndroid::UpdateAssetResolverByType( + std::unique_ptr updated_asset_resolver, + AssetResolver::AssetResolverType type) { + delegate_.UpdateAssetResolverByType(std::move(updated_asset_resolver), type); +} + +void PlatformViewAndroid::InstallFirstFrameCallback() { + // On Platform Task Runner. + SetNextFrameCallback( + [platform_view = GetWeakPtr(), + platform_task_runner = task_runners_.GetPlatformTaskRunner()]() { + // On GPU Task Runner. + platform_task_runner->PostTask([platform_view]() { + // Back on Platform Task Runner. + if (platform_view) { + reinterpret_cast(platform_view.get()) + ->FireFirstFrameCallback(); + } + }); + }); +} + +void PlatformViewAndroid::FireFirstFrameCallback() { + jni_facade_->FlutterViewOnFirstFrame(); +} + +double PlatformViewAndroid::GetScaledFontSize(double unscaled_font_size, + int configuration_id) const { + return jni_facade_->FlutterViewGetScaledFontSize(unscaled_font_size, + configuration_id); +} + +bool PlatformViewAndroid::IsSurfaceControlEnabled() const { + return android_use_new_platform_view_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_view_android.h b/flutter/engine/src/flutter/shell/platform/android/platform_view_android.h new file mode 100644 index 0000000000000000000000000000000000000000..c019f4a112f6ce52ad11c30345ca8661aa9584b7 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_view_android.h @@ -0,0 +1,191 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_ + +#include +#include +#include + +#include +#include "flutter/fml/platform/android/scoped_java_ref.h" +#include "flutter/lib/ui/window/platform_message.h" +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/common/snapshot_surface_producer.h" +#include "flutter/shell/platform/android/context/android_context.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/platform_message_handler_android.h" +#include "flutter/shell/platform/android/platform_view_android_delegate/platform_view_android_delegate.h" +#include "flutter/shell/platform/android/surface/android_native_window.h" +#include "flutter/shell/platform/android/surface/android_surface.h" +#include "shell/platform/android/image_external_texture.h" + +namespace flutter { + +class AndroidSurfaceFactoryImpl : public AndroidSurfaceFactory { + public: + AndroidSurfaceFactoryImpl(const std::shared_ptr& context, + bool enable_impeller, + bool lazy_shader_mode); + + ~AndroidSurfaceFactoryImpl() override; + + std::unique_ptr CreateSurface() override; + + private: + const std::shared_ptr& android_context_; + const bool enable_impeller_; + const bool lazy_shader_mode_; +}; + +class PlatformViewAndroid final : public PlatformView { + public: + static bool Register(JNIEnv* env); + + PlatformViewAndroid(PlatformView::Delegate& delegate, + const flutter::TaskRunners& task_runners, + const std::shared_ptr& jni_facade, + AndroidRenderingAPI rendering_api); + + //---------------------------------------------------------------------------- + /// @brief Creates a new PlatformViewAndroid but using an existing + /// Android GPU context to create new surfaces. This maximizes + /// resource sharing between 2 PlatformViewAndroids of 2 Shells. + /// + PlatformViewAndroid( + PlatformView::Delegate& delegate, + const flutter::TaskRunners& task_runners, + const std::shared_ptr& jni_facade, + const std::shared_ptr& android_context); + + ~PlatformViewAndroid() override; + + void NotifyCreated(fml::RefPtr native_window); + + void NotifySurfaceWindowChanged( + fml::RefPtr native_window); + + void NotifyChanged(const SkISize& size); + + // |PlatformView| + void NotifyDestroyed() override; + + void DispatchPlatformMessage(JNIEnv* env, + std::string name, + jobject message_data, + jint message_position, + jint response_id); + + void DispatchEmptyPlatformMessage(JNIEnv* env, + std::string name, + jint response_id); + + void DispatchSemanticsAction(JNIEnv* env, + jint id, + jint action, + jobject args, + jint args_position); + + void RegisterExternalTexture( + int64_t texture_id, + const fml::jni::ScopedJavaGlobalRef& surface_texture); + + void RegisterImageTexture( + int64_t texture_id, + const fml::jni::ScopedJavaGlobalRef& image_texture_entry, + ImageExternalTexture::ImageLifecycle lifecycle); + + // |PlatformView| + void LoadDartDeferredLibrary( + intptr_t loading_unit_id, + std::unique_ptr snapshot_data, + std::unique_ptr snapshot_instructions) override; + + void LoadDartDeferredLibraryError(intptr_t loading_unit_id, + const std::string error_message, + bool transient) override; + + // |PlatformView| + void UpdateAssetResolverByType( + std::unique_ptr updated_asset_resolver, + AssetResolver::AssetResolverType type) override; + + const std::shared_ptr& GetAndroidContext() { + return android_context_; + } + + std::shared_ptr GetPlatformMessageHandler() + const override { + return platform_message_handler_; + } + + /// @brief Whether the SurfaceControl based swapchain is enabled and active. + bool IsSurfaceControlEnabled() const; + + private: + const std::shared_ptr jni_facade_; + std::shared_ptr android_context_; + std::shared_ptr surface_factory_; + + PlatformViewAndroidDelegate platform_view_android_delegate_; + + std::unique_ptr android_surface_; + std::shared_ptr platform_message_handler_; + bool android_use_new_platform_view_ = false; + + // |PlatformView| + void UpdateSemantics( + int64_t view_id, + flutter::SemanticsNodeUpdates update, + flutter::CustomAccessibilityActionUpdates actions) override; + + // |PlatformView| + void HandlePlatformMessage( + std::unique_ptr message) override; + + // |PlatformView| + void OnPreEngineRestart() const override; + + // |PlatformView| + std::unique_ptr CreateVSyncWaiter() override; + + // |PlatformView| + std::unique_ptr CreateRenderingSurface() override; + + // |PlatformView| + std::shared_ptr CreateExternalViewEmbedder() override; + + // |PlatformView| + std::unique_ptr CreateSnapshotSurfaceProducer() + override; + + // |PlatformView| + sk_sp CreateResourceContext() const override; + + // |PlatformView| + void ReleaseResourceContext() const override; + + // |PlatformView| + std::shared_ptr GetImpellerContext() const override; + + // |PlatformView| + std::unique_ptr> ComputePlatformResolvedLocales( + const std::vector& supported_locale_data) override; + + // |PlatformView| + void RequestDartDeferredLibrary(intptr_t loading_unit_id) override; + + void InstallFirstFrameCallback(); + + void FireFirstFrameCallback(); + + double GetScaledFontSize(double unscaled_font_size, + int configuration_id) const override; + + FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewAndroid); +}; +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.cc b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..29ed47dbcb039903557d5a491087e4b88cba287d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.cc @@ -0,0 +1,2250 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/platform_view_android_jni_impl.h" + +#include +#include +#include +#include +#include +#include + +#include "unicode/uchar.h" + +#include "flutter/common/constants.h" +#include "flutter/flow/embedded_views.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/native_library.h" +#include "flutter/fml/platform/android/jni_util.h" +#include "flutter/fml/platform/android/jni_weak_ref.h" +#include "flutter/fml/platform/android/scoped_java_ref.h" +#include "flutter/impeller/toolkit/android/proc_table.h" +#include "flutter/lib/ui/plugins/callback_cache.h" +#include "flutter/shell/platform/android/android_shell_holder.h" +#include "flutter/shell/platform/android/apk_asset_provider.h" +#include "flutter/shell/platform/android/flutter_main.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" +#include "flutter/shell/platform/android/platform_view_android.h" + +#define ANDROID_SHELL_HOLDER \ + (reinterpret_cast(shell_holder)) + +namespace flutter { + +static fml::jni::ScopedJavaGlobalRef* g_flutter_callback_info_class = + nullptr; + +static fml::jni::ScopedJavaGlobalRef* g_flutter_jni_class = nullptr; + +static fml::jni::ScopedJavaGlobalRef* g_java_weak_reference_class = + nullptr; + +static fml::jni::ScopedJavaGlobalRef* g_texture_wrapper_class = nullptr; + +static fml::jni::ScopedJavaGlobalRef* + g_image_consumer_texture_registry_interface = nullptr; + +static fml::jni::ScopedJavaGlobalRef* g_image_class = nullptr; + +static fml::jni::ScopedJavaGlobalRef* g_hardware_buffer_class = nullptr; + +static fml::jni::ScopedJavaGlobalRef* g_java_long_class = nullptr; + +static fml::jni::ScopedJavaGlobalRef* g_bitmap_class = nullptr; + +static fml::jni::ScopedJavaGlobalRef* g_bitmap_config_class = nullptr; + +// Called By Native + +static jmethodID g_flutter_callback_info_constructor = nullptr; + +static jfieldID g_jni_shell_holder_field = nullptr; + +#define FLUTTER_FOR_EACH_JNI_METHOD(V) \ + V(g_handle_platform_message_method, handlePlatformMessage, \ + "(Ljava/lang/String;Ljava/nio/ByteBuffer;IJ)V") \ + V(g_handle_platform_message_response_method, handlePlatformMessageResponse, \ + "(ILjava/nio/ByteBuffer;)V") \ + V(g_update_semantics_method, updateSemantics, \ + "(Ljava/nio/ByteBuffer;[Ljava/lang/String;[Ljava/nio/ByteBuffer;)V") \ + V(g_on_display_platform_view_method, onDisplayPlatformView, \ + "(IIIIIIILio/flutter/embedding/engine/mutatorsstack/" \ + "FlutterMutatorsStack;)V") \ + V(g_on_begin_frame_method, onBeginFrame, "()V") \ + V(g_on_end_frame_method, onEndFrame, "()V") \ + V(g_on_display_overlay_surface_method, onDisplayOverlaySurface, "(IIIII)V") \ + V(g_create_transaction_method, createTransaction, \ + "()Landroid/view/SurfaceControl$Transaction;") \ + V(g_swap_transaction_method, swapTransactions, "()V") \ + V(g_apply_transaction_method, applyTransactions, "()V") \ + V(g_create_overlay_surface2_method, createOverlaySurface2, \ + "()Lio/flutter/embedding/engine/FlutterOverlaySurface;") \ + V(g_destroy_overlay_surface2_method, destroyOverlaySurface2, "()V") \ + V(g_on_display_platform_view2_method, onDisplayPlatformView2, \ + "(IIIIIIILio/flutter/embedding/engine/mutatorsstack/" \ + "FlutterMutatorsStack;)V") \ + V(g_on_end_frame2_method, endFrame2, "()V") \ + V(g_show_overlay_surface2_method, showOverlaySurface2, "()V") \ + V(g_hide_overlay_surface2_method, hideOverlaySurface2, "()V") \ + V(g_get_scaled_font_size_method, getScaledFontSize, "(FI)F") \ + V(g_update_custom_accessibility_actions_method, \ + updateCustomAccessibilityActions, \ + "(Ljava/nio/ByteBuffer;[Ljava/lang/String;)V") \ + V(g_on_first_frame_method, onFirstFrame, "()V") \ + V(g_on_engine_restart_method, onPreEngineRestart, "()V") \ + V(g_create_overlay_surface_method, createOverlaySurface, \ + "()Lio/flutter/embedding/engine/FlutterOverlaySurface;") \ + V(g_destroy_overlay_surfaces_method, destroyOverlaySurfaces, "()V") + +// + +#define FLUTTER_DECLARE_JNI(global_field, jni_name, jni_arg) \ + static jmethodID global_field = nullptr; + +#define FLUTTER_BIND_JNI(global_field, jni_name, jni_arg) \ + global_field = \ + env->GetMethodID(g_flutter_jni_class->obj(), #jni_name, jni_arg); \ + if (global_field == nullptr) { \ + FML_LOG(ERROR) << "Could not locate " << #jni_name << " method."; \ + return false; \ + } + +static jmethodID g_jni_constructor = nullptr; + +static jmethodID g_long_constructor = nullptr; + +FLUTTER_FOR_EACH_JNI_METHOD(FLUTTER_DECLARE_JNI) + +static jmethodID g_java_weak_reference_get_method = nullptr; + +static jmethodID g_attach_to_gl_context_method = nullptr; + +static jmethodID g_surface_texture_wrapper_should_update = nullptr; + +static jmethodID g_update_tex_image_method = nullptr; + +static jmethodID g_get_transform_matrix_method = nullptr; + +static jmethodID g_detach_from_gl_context_method = nullptr; + +static jmethodID g_acquire_latest_image_method = nullptr; + +static jmethodID g_image_get_hardware_buffer_method = nullptr; + +static jmethodID g_image_close_method = nullptr; + +static jmethodID g_hardware_buffer_close_method = nullptr; + +static jmethodID g_compute_platform_resolved_locale_method = nullptr; + +static jmethodID g_request_dart_deferred_library_method = nullptr; + +// Called By Java + +static jmethodID g_overlay_surface_id_method = nullptr; + +static jmethodID g_overlay_surface_surface_method = nullptr; + +static jmethodID g_bitmap_create_bitmap_method = nullptr; + +static jmethodID g_bitmap_copy_pixels_from_buffer_method = nullptr; + +static jmethodID g_bitmap_config_value_of = nullptr; + +// Mutators +static fml::jni::ScopedJavaGlobalRef* g_mutators_stack_class = nullptr; +static jmethodID g_mutators_stack_init_method = nullptr; +static jmethodID g_mutators_stack_push_transform_method = nullptr; +static jmethodID g_mutators_stack_push_cliprect_method = nullptr; +static jmethodID g_mutators_stack_push_cliprrect_method = nullptr; +static jmethodID g_mutators_stack_push_opacity_method = nullptr; +static jmethodID g_mutators_stack_push_clippath_method = nullptr; + +// android.graphics.Path class and methods +static fml::jni::ScopedJavaGlobalRef* path_class = nullptr; +static jmethodID path_constructor = nullptr; +static jmethodID path_move_to_method = nullptr; +static jmethodID path_line_to_method = nullptr; +static jmethodID path_quad_to_method = nullptr; +static jmethodID path_cubic_to_method = nullptr; +static jmethodID path_conic_to_method = nullptr; +static jmethodID path_close_method = nullptr; + +// Called By Java +static jlong AttachJNI(JNIEnv* env, jclass clazz, jobject flutterJNI) { + fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterJNI); + std::shared_ptr jni_facade = + std::make_shared(java_object); + auto shell_holder = std::make_unique( + FlutterMain::Get().GetSettings(), jni_facade, + FlutterMain::Get().GetAndroidRenderingAPI()); + if (shell_holder->IsValid()) { + return reinterpret_cast(shell_holder.release()); + } else { + return 0; + } +} + +static void DestroyJNI(JNIEnv* env, jobject jcaller, jlong shell_holder) { + delete ANDROID_SHELL_HOLDER; +} + +// Signature is similar to RunBundleAndSnapshotFromLibrary but it can't change +// the bundle path or asset manager since we can only spawn with the same +// AOT. +// +// The shell_holder instance must be a pointer address to the current +// AndroidShellHolder whose Shell will be used to spawn a new Shell. +// +// This creates a Java Long that points to the newly created +// AndroidShellHolder's raw pointer, connects that Long to a newly created +// FlutterJNI instance, then returns the FlutterJNI instance. +static jobject SpawnJNI(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jstring jEntrypoint, + jstring jLibraryUrl, + jstring jInitialRoute, + jobject jEntrypointArgs, + jlong engineId) { + jobject jni = env->NewObject(g_flutter_jni_class->obj(), g_jni_constructor); + if (jni == nullptr) { + FML_LOG(ERROR) << "Could not create a FlutterJNI instance"; + return nullptr; + } + + fml::jni::JavaObjectWeakGlobalRef java_jni(env, jni); + std::shared_ptr jni_facade = + std::make_shared(java_jni); + + auto entrypoint = fml::jni::JavaStringToString(env, jEntrypoint); + auto libraryUrl = fml::jni::JavaStringToString(env, jLibraryUrl); + auto initial_route = fml::jni::JavaStringToString(env, jInitialRoute); + auto entrypoint_args = fml::jni::StringListToVector(env, jEntrypointArgs); + + auto spawned_shell_holder = + ANDROID_SHELL_HOLDER->Spawn(jni_facade, entrypoint, libraryUrl, + initial_route, entrypoint_args, engineId); + + if (spawned_shell_holder == nullptr || !spawned_shell_holder->IsValid()) { + FML_LOG(ERROR) << "Could not spawn Shell"; + return nullptr; + } + + jobject javaLong = env->CallStaticObjectMethod( + g_java_long_class->obj(), g_long_constructor, + reinterpret_cast(spawned_shell_holder.release())); + if (javaLong == nullptr) { + FML_LOG(ERROR) << "Could not create a Long instance"; + return nullptr; + } + + env->SetObjectField(jni, g_jni_shell_holder_field, javaLong); + + return jni; +} + +static void SurfaceCreated(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jobject jsurface) { + // Note: This frame ensures that any local references used by + // ANativeWindow_fromSurface are released immediately. This is needed as a + // workaround for https://code.google.com/p/android/issues/detail?id=68174 + fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env); + auto window = fml::MakeRefCounted( + ANativeWindow_fromSurface(env, jsurface)); + ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyCreated(std::move(window)); +} + +static void SurfaceWindowChanged(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jobject jsurface) { + // Note: This frame ensures that any local references used by + // ANativeWindow_fromSurface are released immediately. This is needed as a + // workaround for https://code.google.com/p/android/issues/detail?id=68174 + fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env); + auto window = fml::MakeRefCounted( + ANativeWindow_fromSurface(env, jsurface)); + ANDROID_SHELL_HOLDER->GetPlatformView()->NotifySurfaceWindowChanged( + std::move(window)); +} + +static void SurfaceChanged(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jint width, + jint height) { + ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyChanged( + SkISize::Make(width, height)); +} + +static void SurfaceDestroyed(JNIEnv* env, jobject jcaller, jlong shell_holder) { + ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyDestroyed(); +} + +static void RunBundleAndSnapshotFromLibrary(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jstring jBundlePath, + jstring jEntrypoint, + jstring jLibraryUrl, + jobject jAssetManager, + jobject jEntrypointArgs, + jlong engineId) { + auto apk_asset_provider = std::make_unique( + env, // jni environment + jAssetManager, // asset manager + fml::jni::JavaStringToString(env, jBundlePath) // apk asset dir + ); + auto entrypoint = fml::jni::JavaStringToString(env, jEntrypoint); + auto libraryUrl = fml::jni::JavaStringToString(env, jLibraryUrl); + auto entrypoint_args = fml::jni::StringListToVector(env, jEntrypointArgs); + + ANDROID_SHELL_HOLDER->Launch(std::move(apk_asset_provider), entrypoint, + libraryUrl, entrypoint_args, engineId); +} + +static jobject LookupCallbackInformation(JNIEnv* env, + /* unused */ jobject, + jlong handle) { + auto cbInfo = flutter::DartCallbackCache::GetCallbackInformation(handle); + if (cbInfo == nullptr) { + return nullptr; + } + return env->NewObject(g_flutter_callback_info_class->obj(), + g_flutter_callback_info_constructor, + env->NewStringUTF(cbInfo->name.c_str()), + env->NewStringUTF(cbInfo->class_name.c_str()), + env->NewStringUTF(cbInfo->library_path.c_str())); +} + +static void SetViewportMetrics(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jfloat devicePixelRatio, + jint physicalWidth, + jint physicalHeight, + jint physicalPaddingTop, + jint physicalPaddingRight, + jint physicalPaddingBottom, + jint physicalPaddingLeft, + jint physicalViewInsetTop, + jint physicalViewInsetRight, + jint physicalViewInsetBottom, + jint physicalViewInsetLeft, + jint systemGestureInsetTop, + jint systemGestureInsetRight, + jint systemGestureInsetBottom, + jint systemGestureInsetLeft, + jint physicalTouchSlop, + jintArray javaDisplayFeaturesBounds, + jintArray javaDisplayFeaturesType, + jintArray javaDisplayFeaturesState) { + // Convert java->c++. javaDisplayFeaturesBounds, javaDisplayFeaturesType and + // javaDisplayFeaturesState cannot be null + jsize rectSize = env->GetArrayLength(javaDisplayFeaturesBounds); + std::vector boundsIntVector(rectSize); + env->GetIntArrayRegion(javaDisplayFeaturesBounds, 0, rectSize, + &boundsIntVector[0]); + std::vector displayFeaturesBounds(boundsIntVector.begin(), + boundsIntVector.end()); + jsize typeSize = env->GetArrayLength(javaDisplayFeaturesType); + std::vector displayFeaturesType(typeSize); + env->GetIntArrayRegion(javaDisplayFeaturesType, 0, typeSize, + &displayFeaturesType[0]); + + jsize stateSize = env->GetArrayLength(javaDisplayFeaturesState); + std::vector displayFeaturesState(stateSize); + env->GetIntArrayRegion(javaDisplayFeaturesState, 0, stateSize, + &displayFeaturesState[0]); + + const flutter::ViewportMetrics metrics{ + static_cast(devicePixelRatio), + static_cast(physicalWidth), + static_cast(physicalHeight), + static_cast(physicalPaddingTop), + static_cast(physicalPaddingRight), + static_cast(physicalPaddingBottom), + static_cast(physicalPaddingLeft), + static_cast(physicalViewInsetTop), + static_cast(physicalViewInsetRight), + static_cast(physicalViewInsetBottom), + static_cast(physicalViewInsetLeft), + static_cast(systemGestureInsetTop), + static_cast(systemGestureInsetRight), + static_cast(systemGestureInsetBottom), + static_cast(systemGestureInsetLeft), + static_cast(physicalTouchSlop), + displayFeaturesBounds, + displayFeaturesType, + displayFeaturesState, + 0, // Display ID + }; + + ANDROID_SHELL_HOLDER->GetPlatformView()->SetViewportMetrics( + kFlutterImplicitViewId, metrics); +} + +static void UpdateDisplayMetrics(JNIEnv* env, + jobject jcaller, + jlong shell_holder) { + ANDROID_SHELL_HOLDER->UpdateDisplayMetrics(); +} + +static bool IsSurfaceControlEnabled(JNIEnv* env, + jobject jcaller, + jlong shell_holder) { + return ANDROID_SHELL_HOLDER->IsSurfaceControlEnabled(); +} + +static jobject GetBitmap(JNIEnv* env, jobject jcaller, jlong shell_holder) { + auto screenshot = ANDROID_SHELL_HOLDER->Screenshot( + Rasterizer::ScreenshotType::UncompressedImage, false); + if (screenshot.data == nullptr) { + return nullptr; + } + + jstring argb = env->NewStringUTF("ARGB_8888"); + if (argb == nullptr) { + return nullptr; + } + + jobject bitmap_config = env->CallStaticObjectMethod( + g_bitmap_config_class->obj(), g_bitmap_config_value_of, argb); + if (bitmap_config == nullptr) { + return nullptr; + } + + auto bitmap = env->CallStaticObjectMethod( + g_bitmap_class->obj(), g_bitmap_create_bitmap_method, + screenshot.frame_size.width(), screenshot.frame_size.height(), + bitmap_config); + + fml::jni::ScopedJavaLocalRef buffer( + env, + env->NewDirectByteBuffer(const_cast(screenshot.data->bytes()), + screenshot.data->size())); + + env->CallVoidMethod(bitmap, g_bitmap_copy_pixels_from_buffer_method, + buffer.obj()); + + return bitmap; +} + +static void DispatchPlatformMessage(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jstring channel, + jobject message, + jint position, + jint responseId) { + ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchPlatformMessage( + env, // + fml::jni::JavaStringToString(env, channel), // + message, // + position, // + responseId // + ); +} + +static void DispatchEmptyPlatformMessage(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jstring channel, + jint responseId) { + ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchEmptyPlatformMessage( + env, // + fml::jni::JavaStringToString(env, channel), // + responseId // + ); +} + +static void CleanupMessageData(JNIEnv* env, + jobject jcaller, + jlong message_data) { + // Called from any thread. + free(reinterpret_cast(message_data)); +} + +static void DispatchPointerDataPacket(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jobject buffer, + jint position) { + uint8_t* data = static_cast(env->GetDirectBufferAddress(buffer)); + auto packet = std::make_unique(data, position); + ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchPointerDataPacket( + std::move(packet)); +} + +static void DispatchSemanticsAction(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jint id, + jint action, + jobject args, + jint args_position) { + ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchSemanticsAction( + env, // + id, // + action, // + args, // + args_position // + ); +} + +static void SetSemanticsEnabled(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jboolean enabled) { + ANDROID_SHELL_HOLDER->GetPlatformView()->SetSemanticsEnabled(enabled); +} + +static void SetAccessibilityFeatures(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jint flags) { + ANDROID_SHELL_HOLDER->GetPlatformView()->SetAccessibilityFeatures(flags); +} + +static jboolean GetIsSoftwareRendering(JNIEnv* env, jobject jcaller) { + return FlutterMain::Get().GetSettings().enable_software_rendering; +} + +static void RegisterTexture(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jlong texture_id, + jobject surface_texture) { + ANDROID_SHELL_HOLDER->GetPlatformView()->RegisterExternalTexture( + static_cast(texture_id), // + fml::jni::ScopedJavaGlobalRef(env, surface_texture) // + ); +} + +static void RegisterImageTexture(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jlong texture_id, + jobject image_texture_entry, + jboolean reset_on_background) { + ImageExternalTexture::ImageLifecycle lifecycle = + reset_on_background ? ImageExternalTexture::ImageLifecycle::kReset + : ImageExternalTexture::ImageLifecycle::kKeepAlive; + + ANDROID_SHELL_HOLDER->GetPlatformView()->RegisterImageTexture( + static_cast(texture_id), // + fml::jni::ScopedJavaGlobalRef(env, image_texture_entry), // + lifecycle // + ); +} + +static void UnregisterTexture(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jlong texture_id) { + ANDROID_SHELL_HOLDER->GetPlatformView()->UnregisterTexture( + static_cast(texture_id)); +} + +static void MarkTextureFrameAvailable(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jlong texture_id) { + ANDROID_SHELL_HOLDER->GetPlatformView()->MarkTextureFrameAvailable( + static_cast(texture_id)); +} + +static void ScheduleFrame(JNIEnv* env, jobject jcaller, jlong shell_holder) { + ANDROID_SHELL_HOLDER->GetPlatformView()->ScheduleFrame(); +} + +static void InvokePlatformMessageResponseCallback(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jint responseId, + jobject message, + jint position) { + uint8_t* response_data = + static_cast(env->GetDirectBufferAddress(message)); + FML_DCHECK(response_data != nullptr); + auto mapping = std::make_unique( + fml::MallocMapping::Copy(response_data, response_data + position)); + ANDROID_SHELL_HOLDER->GetPlatformMessageHandler() + ->InvokePlatformMessageResponseCallback(responseId, std::move(mapping)); +} + +static void InvokePlatformMessageEmptyResponseCallback(JNIEnv* env, + jobject jcaller, + jlong shell_holder, + jint responseId) { + ANDROID_SHELL_HOLDER->GetPlatformMessageHandler() + ->InvokePlatformMessageEmptyResponseCallback(responseId); +} + +static void NotifyLowMemoryWarning(JNIEnv* env, + jobject obj, + jlong shell_holder) { + ANDROID_SHELL_HOLDER->NotifyLowMemoryWarning(); +} + +static jboolean FlutterTextUtilsIsEmoji(JNIEnv* env, + jobject obj, + jint codePoint) { + return u_hasBinaryProperty(codePoint, UProperty::UCHAR_EMOJI); +} + +static jboolean FlutterTextUtilsIsEmojiModifier(JNIEnv* env, + jobject obj, + jint codePoint) { + return u_hasBinaryProperty(codePoint, UProperty::UCHAR_EMOJI_MODIFIER); +} + +static jboolean FlutterTextUtilsIsEmojiModifierBase(JNIEnv* env, + jobject obj, + jint codePoint) { + return u_hasBinaryProperty(codePoint, UProperty::UCHAR_EMOJI_MODIFIER_BASE); +} + +static jboolean FlutterTextUtilsIsVariationSelector(JNIEnv* env, + jobject obj, + jint codePoint) { + return u_hasBinaryProperty(codePoint, UProperty::UCHAR_VARIATION_SELECTOR); +} + +static jboolean FlutterTextUtilsIsRegionalIndicator(JNIEnv* env, + jobject obj, + jint codePoint) { + return u_hasBinaryProperty(codePoint, UProperty::UCHAR_REGIONAL_INDICATOR); +} + +static void LoadLoadingUnitFailure(intptr_t loading_unit_id, + const std::string& message, + bool transient) { + // TODO(garyq): Implement +} + +static void DeferredComponentInstallFailure(JNIEnv* env, + jobject obj, + jint jLoadingUnitId, + jstring jError, + jboolean jTransient) { + LoadLoadingUnitFailure(static_cast(jLoadingUnitId), + fml::jni::JavaStringToString(env, jError), + static_cast(jTransient)); +} + +static void LoadDartDeferredLibrary(JNIEnv* env, + jobject obj, + jlong shell_holder, + jint jLoadingUnitId, + jobjectArray jSearchPaths) { + // Convert java->c++ + intptr_t loading_unit_id = static_cast(jLoadingUnitId); + std::vector search_paths = + fml::jni::StringArrayToVector(env, jSearchPaths); + + // Use dlopen here to directly check if handle is nullptr before creating a + // NativeLibrary. + void* handle = nullptr; + while (handle == nullptr && !search_paths.empty()) { + std::string path = search_paths.back(); + handle = ::dlopen(path.c_str(), RTLD_NOW); + search_paths.pop_back(); + } + if (handle == nullptr) { + LoadLoadingUnitFailure(loading_unit_id, + "No lib .so found for provided search paths.", true); + return; + } + fml::RefPtr native_lib = + fml::NativeLibrary::CreateWithHandle(handle, false); + + // Resolve symbols. + std::unique_ptr data_mapping = + std::make_unique( + native_lib, DartSnapshot::kIsolateDataSymbol); + std::unique_ptr instructions_mapping = + std::make_unique( + native_lib, DartSnapshot::kIsolateInstructionsSymbol); + + ANDROID_SHELL_HOLDER->GetPlatformView()->LoadDartDeferredLibrary( + loading_unit_id, std::move(data_mapping), + std::move(instructions_mapping)); +} + +static void UpdateJavaAssetManager(JNIEnv* env, + jobject obj, + jlong shell_holder, + jobject jAssetManager, + jstring jAssetBundlePath) { + auto asset_resolver = std::make_unique( + env, // jni environment + jAssetManager, // asset manager + fml::jni::JavaStringToString(env, jAssetBundlePath)); // apk asset dir + + ANDROID_SHELL_HOLDER->GetPlatformView()->UpdateAssetResolverByType( + std::move(asset_resolver), + AssetResolver::AssetResolverType::kApkAssetProvider); +} + +bool RegisterApi(JNIEnv* env) { + static const JNINativeMethod flutter_jni_methods[] = { + // Start of methods from FlutterJNI + { + .name = "nativeAttach", + .signature = "(Lio/flutter/embedding/engine/FlutterJNI;)J", + .fnPtr = reinterpret_cast(&AttachJNI), + }, + { + .name = "nativeDestroy", + .signature = "(J)V", + .fnPtr = reinterpret_cast(&DestroyJNI), + }, + { + .name = "nativeSpawn", + .signature = "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/" + "String;Ljava/util/List;J)Lio/flutter/" + "embedding/engine/FlutterJNI;", + .fnPtr = reinterpret_cast(&SpawnJNI), + }, + { + .name = "nativeRunBundleAndSnapshotFromLibrary", + .signature = "(JLjava/lang/String;Ljava/lang/String;" + "Ljava/lang/String;Landroid/content/res/" + "AssetManager;Ljava/util/List;J)V", + .fnPtr = reinterpret_cast(&RunBundleAndSnapshotFromLibrary), + }, + { + .name = "nativeDispatchEmptyPlatformMessage", + .signature = "(JLjava/lang/String;I)V", + .fnPtr = reinterpret_cast(&DispatchEmptyPlatformMessage), + }, + { + .name = "nativeCleanupMessageData", + .signature = "(J)V", + .fnPtr = reinterpret_cast(&CleanupMessageData), + }, + { + .name = "nativeDispatchPlatformMessage", + .signature = "(JLjava/lang/String;Ljava/nio/ByteBuffer;II)V", + .fnPtr = reinterpret_cast(&DispatchPlatformMessage), + }, + { + .name = "nativeInvokePlatformMessageResponseCallback", + .signature = "(JILjava/nio/ByteBuffer;I)V", + .fnPtr = + reinterpret_cast(&InvokePlatformMessageResponseCallback), + }, + { + .name = "nativeInvokePlatformMessageEmptyResponseCallback", + .signature = "(JI)V", + .fnPtr = reinterpret_cast( + &InvokePlatformMessageEmptyResponseCallback), + }, + { + .name = "nativeNotifyLowMemoryWarning", + .signature = "(J)V", + .fnPtr = reinterpret_cast(&NotifyLowMemoryWarning), + }, + + // Start of methods from FlutterView + { + .name = "nativeGetBitmap", + .signature = "(J)Landroid/graphics/Bitmap;", + .fnPtr = reinterpret_cast(&GetBitmap), + }, + { + .name = "nativeSurfaceCreated", + .signature = "(JLandroid/view/Surface;)V", + .fnPtr = reinterpret_cast(&SurfaceCreated), + }, + { + .name = "nativeSurfaceWindowChanged", + .signature = "(JLandroid/view/Surface;)V", + .fnPtr = reinterpret_cast(&SurfaceWindowChanged), + }, + { + .name = "nativeSurfaceChanged", + .signature = "(JII)V", + .fnPtr = reinterpret_cast(&SurfaceChanged), + }, + { + .name = "nativeSurfaceDestroyed", + .signature = "(J)V", + .fnPtr = reinterpret_cast(&SurfaceDestroyed), + }, + { + .name = "nativeSetViewportMetrics", + .signature = "(JFIIIIIIIIIIIIIII[I[I[I)V", + .fnPtr = reinterpret_cast(&SetViewportMetrics), + }, + { + .name = "nativeDispatchPointerDataPacket", + .signature = "(JLjava/nio/ByteBuffer;I)V", + .fnPtr = reinterpret_cast(&DispatchPointerDataPacket), + }, + { + .name = "nativeDispatchSemanticsAction", + .signature = "(JIILjava/nio/ByteBuffer;I)V", + .fnPtr = reinterpret_cast(&DispatchSemanticsAction), + }, + { + .name = "nativeSetSemanticsEnabled", + .signature = "(JZ)V", + .fnPtr = reinterpret_cast(&SetSemanticsEnabled), + }, + { + .name = "nativeSetAccessibilityFeatures", + .signature = "(JI)V", + .fnPtr = reinterpret_cast(&SetAccessibilityFeatures), + }, + { + .name = "nativeGetIsSoftwareRenderingEnabled", + .signature = "()Z", + .fnPtr = reinterpret_cast(&GetIsSoftwareRendering), + }, + { + .name = "nativeRegisterTexture", + .signature = "(JJLjava/lang/ref/" + "WeakReference;)V", + .fnPtr = reinterpret_cast(&RegisterTexture), + }, + { + .name = "nativeRegisterImageTexture", + .signature = "(JJLjava/lang/ref/" + "WeakReference;Z)V", + .fnPtr = reinterpret_cast(&RegisterImageTexture), + }, + { + .name = "nativeMarkTextureFrameAvailable", + .signature = "(JJ)V", + .fnPtr = reinterpret_cast(&MarkTextureFrameAvailable), + }, + { + .name = "nativeScheduleFrame", + .signature = "(J)V", + .fnPtr = reinterpret_cast(&ScheduleFrame), + }, + { + .name = "nativeUnregisterTexture", + .signature = "(JJ)V", + .fnPtr = reinterpret_cast(&UnregisterTexture), + }, + // Methods for Dart callback functionality. + { + .name = "nativeLookupCallbackInformation", + .signature = "(J)Lio/flutter/view/FlutterCallbackInformation;", + .fnPtr = reinterpret_cast(&LookupCallbackInformation), + }, + + // Start of methods for FlutterTextUtils + { + .name = "nativeFlutterTextUtilsIsEmoji", + .signature = "(I)Z", + .fnPtr = reinterpret_cast(&FlutterTextUtilsIsEmoji), + }, + { + .name = "nativeFlutterTextUtilsIsEmojiModifier", + .signature = "(I)Z", + .fnPtr = reinterpret_cast(&FlutterTextUtilsIsEmojiModifier), + }, + { + .name = "nativeFlutterTextUtilsIsEmojiModifierBase", + .signature = "(I)Z", + .fnPtr = + reinterpret_cast(&FlutterTextUtilsIsEmojiModifierBase), + }, + { + .name = "nativeFlutterTextUtilsIsVariationSelector", + .signature = "(I)Z", + .fnPtr = + reinterpret_cast(&FlutterTextUtilsIsVariationSelector), + }, + { + .name = "nativeFlutterTextUtilsIsRegionalIndicator", + .signature = "(I)Z", + .fnPtr = + reinterpret_cast(&FlutterTextUtilsIsRegionalIndicator), + }, + { + .name = "nativeLoadDartDeferredLibrary", + .signature = "(JI[Ljava/lang/String;)V", + .fnPtr = reinterpret_cast(&LoadDartDeferredLibrary), + }, + { + .name = "nativeUpdateJavaAssetManager", + .signature = + "(JLandroid/content/res/AssetManager;Ljava/lang/String;)V", + .fnPtr = reinterpret_cast(&UpdateJavaAssetManager), + }, + { + .name = "nativeDeferredComponentInstallFailure", + .signature = "(ILjava/lang/String;Z)V", + .fnPtr = reinterpret_cast(&DeferredComponentInstallFailure), + }, + { + .name = "nativeUpdateDisplayMetrics", + .signature = "(J)V", + .fnPtr = reinterpret_cast(&UpdateDisplayMetrics), + }, + { + .name = "nativeIsSurfaceControlEnabled", + .signature = "(J)Z", + .fnPtr = reinterpret_cast(&IsSurfaceControlEnabled), + }}; + + if (env->RegisterNatives(g_flutter_jni_class->obj(), flutter_jni_methods, + std::size(flutter_jni_methods)) != 0) { + FML_LOG(ERROR) << "Failed to RegisterNatives with FlutterJNI"; + return false; + } + + g_jni_shell_holder_field = env->GetFieldID( + g_flutter_jni_class->obj(), "nativeShellHolderId", "Ljava/lang/Long;"); + + if (g_jni_shell_holder_field == nullptr) { + FML_LOG(ERROR) << "Could not locate FlutterJNI's nativeShellHolderId field"; + return false; + } + + g_jni_constructor = + env->GetMethodID(g_flutter_jni_class->obj(), "", "()V"); + + if (g_jni_constructor == nullptr) { + FML_LOG(ERROR) << "Could not locate FlutterJNI's constructor"; + return false; + } + + g_long_constructor = env->GetStaticMethodID(g_java_long_class->obj(), + "valueOf", "(J)Ljava/lang/Long;"); + if (g_long_constructor == nullptr) { + FML_LOG(ERROR) << "Could not locate Long's constructor"; + return false; + } + + FLUTTER_FOR_EACH_JNI_METHOD(FLUTTER_BIND_JNI) + + fml::jni::ScopedJavaLocalRef overlay_surface_class( + env, env->FindClass("io/flutter/embedding/engine/FlutterOverlaySurface")); + if (overlay_surface_class.is_null()) { + FML_LOG(ERROR) << "Could not locate FlutterOverlaySurface class"; + return false; + } + g_overlay_surface_id_method = + env->GetMethodID(overlay_surface_class.obj(), "getId", "()I"); + if (g_overlay_surface_id_method == nullptr) { + FML_LOG(ERROR) << "Could not locate FlutterOverlaySurface#getId() method"; + return false; + } + g_overlay_surface_surface_method = env->GetMethodID( + overlay_surface_class.obj(), "getSurface", "()Landroid/view/Surface;"); + if (g_overlay_surface_surface_method == nullptr) { + FML_LOG(ERROR) + << "Could not locate FlutterOverlaySurface#getSurface() method"; + return false; + } + + g_bitmap_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("android/graphics/Bitmap")); + if (g_bitmap_class->is_null()) { + FML_LOG(ERROR) << "Could not locate Bitmap Class"; + return false; + } + + g_bitmap_create_bitmap_method = env->GetStaticMethodID( + g_bitmap_class->obj(), "createBitmap", + "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;"); + if (g_bitmap_create_bitmap_method == nullptr) { + FML_LOG(ERROR) << "Could not locate Bitmap.createBitmap method"; + return false; + } + + g_bitmap_copy_pixels_from_buffer_method = env->GetMethodID( + g_bitmap_class->obj(), "copyPixelsFromBuffer", "(Ljava/nio/Buffer;)V"); + if (g_bitmap_copy_pixels_from_buffer_method == nullptr) { + FML_LOG(ERROR) << "Could not locate Bitmap.copyPixelsFromBuffer method"; + return false; + } + + g_bitmap_config_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("android/graphics/Bitmap$Config")); + if (g_bitmap_config_class->is_null()) { + FML_LOG(ERROR) << "Could not locate Bitmap.Config Class"; + return false; + } + + g_bitmap_config_value_of = env->GetStaticMethodID( + g_bitmap_config_class->obj(), "valueOf", + "(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;"); + if (g_bitmap_config_value_of == nullptr) { + FML_LOG(ERROR) << "Could not locate Bitmap.Config.valueOf method"; + return false; + } + + return true; +} + +bool PlatformViewAndroid::Register(JNIEnv* env) { + if (env == nullptr) { + FML_LOG(ERROR) << "No JNIEnv provided"; + return false; + } + + g_flutter_callback_info_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("io/flutter/view/FlutterCallbackInformation")); + if (g_flutter_callback_info_class->is_null()) { + FML_LOG(ERROR) << "Could not locate FlutterCallbackInformation class"; + return false; + } + + g_flutter_callback_info_constructor = env->GetMethodID( + g_flutter_callback_info_class->obj(), "", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); + if (g_flutter_callback_info_constructor == nullptr) { + FML_LOG(ERROR) << "Could not locate FlutterCallbackInformation constructor"; + return false; + } + + g_flutter_jni_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("io/flutter/embedding/engine/FlutterJNI")); + if (g_flutter_jni_class->is_null()) { + FML_LOG(ERROR) << "Failed to find FlutterJNI Class."; + return false; + } + + g_mutators_stack_class = new fml::jni::ScopedJavaGlobalRef( + env, + env->FindClass( + "io/flutter/embedding/engine/mutatorsstack/FlutterMutatorsStack")); + if (g_mutators_stack_class == nullptr) { + FML_LOG(ERROR) << "Could not locate FlutterMutatorsStack"; + return false; + } + + g_mutators_stack_init_method = + env->GetMethodID(g_mutators_stack_class->obj(), "", "()V"); + if (g_mutators_stack_init_method == nullptr) { + FML_LOG(ERROR) << "Could not locate FlutterMutatorsStack.init method"; + return false; + } + + g_mutators_stack_push_transform_method = + env->GetMethodID(g_mutators_stack_class->obj(), "pushTransform", "([F)V"); + if (g_mutators_stack_push_transform_method == nullptr) { + FML_LOG(ERROR) + << "Could not locate FlutterMutatorsStack.pushTransform method"; + return false; + } + + g_mutators_stack_push_cliprect_method = env->GetMethodID( + g_mutators_stack_class->obj(), "pushClipRect", "(IIII)V"); + if (g_mutators_stack_push_cliprect_method == nullptr) { + FML_LOG(ERROR) + << "Could not locate FlutterMutatorsStack.pushClipRect method"; + return false; + } + + g_mutators_stack_push_cliprrect_method = env->GetMethodID( + g_mutators_stack_class->obj(), "pushClipRRect", "(IIII[F)V"); + if (g_mutators_stack_push_cliprrect_method == nullptr) { + FML_LOG(ERROR) + << "Could not locate FlutterMutatorsStack.pushClipRRect method"; + return false; + } + + g_mutators_stack_push_opacity_method = + env->GetMethodID(g_mutators_stack_class->obj(), "pushOpacity", "(F)V"); + if (g_mutators_stack_push_opacity_method == nullptr) { + FML_LOG(ERROR) + << "Could not locate FlutterMutatorsStack.pushOpacity method"; + return false; + } + + g_mutators_stack_push_clippath_method = + env->GetMethodID(g_mutators_stack_class->obj(), "pushClipPath", + "(Landroid/graphics/Path;)V"); + if (g_mutators_stack_push_clippath_method == nullptr) { + FML_LOG(ERROR) + << "Could not locate FlutterMutatorsStack.pushClipPath method"; + return false; + } + + g_java_weak_reference_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("java/lang/ref/WeakReference")); + if (g_java_weak_reference_class->is_null()) { + FML_LOG(ERROR) << "Could not locate WeakReference class"; + return false; + } + + g_java_weak_reference_get_method = env->GetMethodID( + g_java_weak_reference_class->obj(), "get", "()Ljava/lang/Object;"); + if (g_java_weak_reference_get_method == nullptr) { + FML_LOG(ERROR) << "Could not locate WeakReference.get method"; + return false; + } + + g_texture_wrapper_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass( + "io/flutter/embedding/engine/renderer/SurfaceTextureWrapper")); + if (g_texture_wrapper_class->is_null()) { + FML_LOG(ERROR) << "Could not locate SurfaceTextureWrapper class"; + return false; + } + + g_attach_to_gl_context_method = env->GetMethodID( + g_texture_wrapper_class->obj(), "attachToGLContext", "(I)V"); + + if (g_attach_to_gl_context_method == nullptr) { + FML_LOG(ERROR) << "Could not locate attachToGlContext method"; + return false; + } + + g_surface_texture_wrapper_should_update = + env->GetMethodID(g_texture_wrapper_class->obj(), "shouldUpdate", "()Z"); + + if (g_surface_texture_wrapper_should_update == nullptr) { + FML_LOG(ERROR) + << "Could not locate SurfaceTextureWrapper.shouldUpdate method"; + return false; + } + + g_update_tex_image_method = + env->GetMethodID(g_texture_wrapper_class->obj(), "updateTexImage", "()V"); + + if (g_update_tex_image_method == nullptr) { + FML_LOG(ERROR) << "Could not locate updateTexImage method"; + return false; + } + + g_get_transform_matrix_method = env->GetMethodID( + g_texture_wrapper_class->obj(), "getTransformMatrix", "([F)V"); + + if (g_get_transform_matrix_method == nullptr) { + FML_LOG(ERROR) << "Could not locate getTransformMatrix method"; + return false; + } + + g_detach_from_gl_context_method = env->GetMethodID( + g_texture_wrapper_class->obj(), "detachFromGLContext", "()V"); + + if (g_detach_from_gl_context_method == nullptr) { + FML_LOG(ERROR) << "Could not locate detachFromGlContext method"; + return false; + } + g_image_consumer_texture_registry_interface = + new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("io/flutter/view/TextureRegistry$ImageConsumer")); + if (g_image_consumer_texture_registry_interface->is_null()) { + FML_LOG(ERROR) << "Could not locate TextureRegistry.ImageConsumer class"; + return false; + } + + g_acquire_latest_image_method = + env->GetMethodID(g_image_consumer_texture_registry_interface->obj(), + "acquireLatestImage", "()Landroid/media/Image;"); + if (g_acquire_latest_image_method == nullptr) { + FML_LOG(ERROR) << "Could not locate acquireLatestImage on " + "TextureRegistry.ImageConsumer class"; + return false; + } + + g_image_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("android/media/Image")); + if (g_image_class->is_null()) { + FML_LOG(ERROR) << "Could not locate Image class"; + return false; + } + + // Ensure we don't have any pending exceptions. + FML_CHECK(fml::jni::CheckException(env)); + + g_image_get_hardware_buffer_method = + env->GetMethodID(g_image_class->obj(), "getHardwareBuffer", + "()Landroid/hardware/HardwareBuffer;"); + + if (g_image_get_hardware_buffer_method == nullptr) { + // Continue on as this method may not exist at API <= 29. + fml::jni::ClearException(env, true); + } + + g_image_close_method = env->GetMethodID(g_image_class->obj(), "close", "()V"); + + if (g_image_close_method == nullptr) { + FML_LOG(ERROR) << "Could not locate close on Image class"; + return false; + } + + // Ensure we don't have any pending exceptions. + FML_CHECK(fml::jni::CheckException(env)); + g_hardware_buffer_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("android/hardware/HardwareBuffer")); + + if (!g_hardware_buffer_class->is_null()) { + g_hardware_buffer_close_method = + env->GetMethodID(g_hardware_buffer_class->obj(), "close", "()V"); + if (g_hardware_buffer_close_method == nullptr) { + // Continue on as this class may not exist at API <= 26. + fml::jni::ClearException(env, true); + } + } else { + // Continue on as this class may not exist at API <= 26. + fml::jni::ClearException(env, true); + } + + g_compute_platform_resolved_locale_method = env->GetMethodID( + g_flutter_jni_class->obj(), "computePlatformResolvedLocale", + "([Ljava/lang/String;)[Ljava/lang/String;"); + + if (g_compute_platform_resolved_locale_method == nullptr) { + FML_LOG(ERROR) << "Could not locate computePlatformResolvedLocale method"; + return false; + } + + g_request_dart_deferred_library_method = env->GetMethodID( + g_flutter_jni_class->obj(), "requestDartDeferredLibrary", "(I)V"); + + if (g_request_dart_deferred_library_method == nullptr) { + FML_LOG(ERROR) << "Could not locate requestDartDeferredLibrary method"; + return false; + } + + g_java_long_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("java/lang/Long")); + if (g_java_long_class->is_null()) { + FML_LOG(ERROR) << "Could not locate java.lang.Long class"; + return false; + } + + // Android path class and methods. + path_class = new fml::jni::ScopedJavaGlobalRef( + env, env->FindClass("android/graphics/Path")); + if (path_class->is_null()) { + FML_LOG(ERROR) << "Could not locate android.graphics.Path class"; + return false; + } + + path_constructor = env->GetMethodID(path_class->obj(), "", "()V"); + if (path_constructor == nullptr) { + FML_LOG(ERROR) << "Could not locate android.graphics.Path constructor"; + return false; + } + + path_move_to_method = env->GetMethodID(path_class->obj(), "moveTo", "(FF)V"); + if (path_move_to_method == nullptr) { + FML_LOG(ERROR) << "Could not locate android.graphics.Path.moveTo method"; + return false; + } + path_line_to_method = env->GetMethodID(path_class->obj(), "lineTo", "(FF)V"); + if (path_line_to_method == nullptr) { + FML_LOG(ERROR) << "Could not locate android.graphics.Path.lineTo method"; + return false; + } + path_quad_to_method = + env->GetMethodID(path_class->obj(), "quadTo", "(FFFF)V"); + if (path_quad_to_method == nullptr) { + FML_LOG(ERROR) << "Could not locate android.graphics.Path.quadTo method"; + return false; + } + path_cubic_to_method = + env->GetMethodID(path_class->obj(), "cubicTo", "(FFFFFF)V"); + if (path_cubic_to_method == nullptr) { + FML_LOG(ERROR) << "Could not locate android.graphics.Path.cubicTo method"; + return false; + } + // Ensure we don't have any pending exceptions. + FML_CHECK(fml::jni::CheckException(env)); + + path_conic_to_method = + env->GetMethodID(path_class->obj(), "conicTo", "(FFFFF)V"); + if (path_conic_to_method == nullptr) { + // Continue on as this method may not exist at API <= 34. + fml::jni::ClearException(env, true); + } + path_close_method = env->GetMethodID(path_class->obj(), "close", "()V"); + if (path_close_method == nullptr) { + FML_LOG(ERROR) << "Could not locate android.graphics.Path.close method"; + return false; + } + + return RegisterApi(env); +} + +PlatformViewAndroidJNIImpl::PlatformViewAndroidJNIImpl( + const fml::jni::JavaObjectWeakGlobalRef& java_object) + : java_object_(java_object) {} + +PlatformViewAndroidJNIImpl::~PlatformViewAndroidJNIImpl() = default; + +void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessage( + std::unique_ptr message, + int responseId) { + // Called from any thread. + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + fml::jni::ScopedJavaLocalRef java_channel = + fml::jni::StringToJavaString(env, message->channel()); + + if (message->hasData()) { + fml::jni::ScopedJavaLocalRef message_array( + env, env->NewDirectByteBuffer( + const_cast(message->data().GetMapping()), + message->data().GetSize())); + // Message data is deleted in CleanupMessageData. + fml::MallocMapping mapping = message->releaseData(); + env->CallVoidMethod(java_object.obj(), g_handle_platform_message_method, + java_channel.obj(), message_array.obj(), responseId, + reinterpret_cast(mapping.Release())); + } else { + env->CallVoidMethod(java_object.obj(), g_handle_platform_message_method, + java_channel.obj(), nullptr, responseId, nullptr); + } + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessageResponse( + int responseId, + std::unique_ptr data) { + // We are on the platform thread. Attempt to get the strong reference to + // the Java object. + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + // The Java object was collected before this message response got to + // it. Drop the response on the floor. + return; + } + if (data == nullptr) { // Empty response. + env->CallVoidMethod(java_object.obj(), + g_handle_platform_message_response_method, responseId, + nullptr); + } else { + // Convert the vector to a Java byte array. + fml::jni::ScopedJavaLocalRef data_array( + env, env->NewDirectByteBuffer(const_cast(data->GetMapping()), + data->GetSize())); + + env->CallVoidMethod(java_object.obj(), + g_handle_platform_message_response_method, responseId, + data_array.obj()); + } + + FML_CHECK(fml::jni::CheckException(env)); +} + +double PlatformViewAndroidJNIImpl::FlutterViewGetScaledFontSize( + double font_size, + int configuration_id) const { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return -3; + } + + const jfloat scaledSize = env->CallFloatMethod( + java_object.obj(), g_get_scaled_font_size_method, + static_cast(font_size), static_cast(configuration_id)); + FML_CHECK(fml::jni::CheckException(env)); + return static_cast(scaledSize); +} + +void PlatformViewAndroidJNIImpl::FlutterViewUpdateSemantics( + std::vector buffer, + std::vector strings, + std::vector> string_attribute_args) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + fml::jni::ScopedJavaLocalRef direct_buffer( + env, env->NewDirectByteBuffer(buffer.data(), buffer.size())); + fml::jni::ScopedJavaLocalRef jstrings = + fml::jni::VectorToStringArray(env, strings); + fml::jni::ScopedJavaLocalRef jstring_attribute_args = + fml::jni::VectorToBufferArray(env, string_attribute_args); + + env->CallVoidMethod(java_object.obj(), g_update_semantics_method, + direct_buffer.obj(), jstrings.obj(), + jstring_attribute_args.obj()); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::FlutterViewUpdateCustomAccessibilityActions( + std::vector actions_buffer, + std::vector strings) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + fml::jni::ScopedJavaLocalRef direct_actions_buffer( + env, + env->NewDirectByteBuffer(actions_buffer.data(), actions_buffer.size())); + + fml::jni::ScopedJavaLocalRef jstrings = + fml::jni::VectorToStringArray(env, strings); + + env->CallVoidMethod(java_object.obj(), + g_update_custom_accessibility_actions_method, + direct_actions_buffer.obj(), jstrings.obj()); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::FlutterViewOnFirstFrame() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_on_first_frame_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::FlutterViewOnPreEngineRestart() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_on_engine_restart_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::SurfaceTextureAttachToGLContext( + JavaLocalRef surface_texture, + int textureId) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + if (surface_texture.is_null()) { + return; + } + + fml::jni::ScopedJavaLocalRef surface_texture_local_ref( + env, env->CallObjectMethod(surface_texture.obj(), + g_java_weak_reference_get_method)); + + if (surface_texture_local_ref.is_null()) { + return; + } + + env->CallVoidMethod(surface_texture_local_ref.obj(), + g_attach_to_gl_context_method, textureId); + + FML_CHECK(fml::jni::CheckException(env)); +} + +bool PlatformViewAndroidJNIImpl::SurfaceTextureShouldUpdate( + JavaLocalRef surface_texture) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + if (surface_texture.is_null()) { + return false; + } + + fml::jni::ScopedJavaLocalRef surface_texture_local_ref( + env, env->CallObjectMethod(surface_texture.obj(), + g_java_weak_reference_get_method)); + if (surface_texture_local_ref.is_null()) { + return false; + } + + jboolean shouldUpdate = env->CallBooleanMethod( + surface_texture_local_ref.obj(), g_surface_texture_wrapper_should_update); + + FML_CHECK(fml::jni::CheckException(env)); + + return shouldUpdate; +} + +void PlatformViewAndroidJNIImpl::SurfaceTextureUpdateTexImage( + JavaLocalRef surface_texture) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + if (surface_texture.is_null()) { + return; + } + + fml::jni::ScopedJavaLocalRef surface_texture_local_ref( + env, env->CallObjectMethod(surface_texture.obj(), + g_java_weak_reference_get_method)); + if (surface_texture_local_ref.is_null()) { + return; + } + + env->CallVoidMethod(surface_texture_local_ref.obj(), + g_update_tex_image_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +SkM44 PlatformViewAndroidJNIImpl::SurfaceTextureGetTransformMatrix( + JavaLocalRef surface_texture) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + if (surface_texture.is_null()) { + return {}; + } + + fml::jni::ScopedJavaLocalRef surface_texture_local_ref( + env, env->CallObjectMethod(surface_texture.obj(), + g_java_weak_reference_get_method)); + if (surface_texture_local_ref.is_null()) { + return {}; + } + + fml::jni::ScopedJavaLocalRef transformMatrix( + env, env->NewFloatArray(16)); + + env->CallVoidMethod(surface_texture_local_ref.obj(), + g_get_transform_matrix_method, transformMatrix.obj()); + FML_CHECK(fml::jni::CheckException(env)); + + float* m = env->GetFloatArrayElements(transformMatrix.obj(), nullptr); + + static_assert(sizeof(SkScalar) == sizeof(float)); + const auto transform = SkM44::ColMajor(m); + + env->ReleaseFloatArrayElements(transformMatrix.obj(), m, JNI_ABORT); + + return transform; +} + +void PlatformViewAndroidJNIImpl::SurfaceTextureDetachFromGLContext( + JavaLocalRef surface_texture) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + if (surface_texture.is_null()) { + return; + } + + fml::jni::ScopedJavaLocalRef surface_texture_local_ref( + env, env->CallObjectMethod(surface_texture.obj(), + g_java_weak_reference_get_method)); + if (surface_texture_local_ref.is_null()) { + return; + } + + env->CallVoidMethod(surface_texture_local_ref.obj(), + g_detach_from_gl_context_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +JavaLocalRef +PlatformViewAndroidJNIImpl::ImageProducerTextureEntryAcquireLatestImage( + JavaLocalRef image_producer_texture_entry) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + if (image_producer_texture_entry.is_null()) { + // Return null. + return JavaLocalRef(); + } + + // Convert the weak reference to ImageTextureEntry into a strong local + // reference. + fml::jni::ScopedJavaLocalRef image_producer_texture_entry_local_ref( + env, env->CallObjectMethod(image_producer_texture_entry.obj(), + g_java_weak_reference_get_method)); + + if (image_producer_texture_entry_local_ref.is_null()) { + // Return null. + return JavaLocalRef(); + } + + JavaLocalRef r = JavaLocalRef( + env, env->CallObjectMethod(image_producer_texture_entry_local_ref.obj(), + g_acquire_latest_image_method)); + if (fml::jni::CheckException(env)) { + return r; + } + // Return null. + return JavaLocalRef(); +} + +JavaLocalRef PlatformViewAndroidJNIImpl::ImageGetHardwareBuffer( + JavaLocalRef image) { + FML_CHECK(g_image_get_hardware_buffer_method != nullptr); + JNIEnv* env = fml::jni::AttachCurrentThread(); + if (image.is_null()) { + // Return null. + return JavaLocalRef(); + } + JavaLocalRef r = JavaLocalRef( + env, + env->CallObjectMethod(image.obj(), g_image_get_hardware_buffer_method)); + FML_CHECK(fml::jni::CheckException(env)); + return r; +} + +void PlatformViewAndroidJNIImpl::ImageClose(JavaLocalRef image) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + if (image.is_null()) { + return; + } + env->CallVoidMethod(image.obj(), g_image_close_method); + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::HardwareBufferClose( + JavaLocalRef hardware_buffer) { + FML_CHECK(g_hardware_buffer_close_method != nullptr); + JNIEnv* env = fml::jni::AttachCurrentThread(); + if (hardware_buffer.is_null()) { + return; + } + env->CallVoidMethod(hardware_buffer.obj(), g_hardware_buffer_close_method); + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::FlutterViewOnDisplayPlatformView( + int view_id, + int x, + int y, + int width, + int height, + int viewWidth, + int viewHeight, + MutatorsStack mutators_stack) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + jobject mutatorsStack = env->NewObject(g_mutators_stack_class->obj(), + g_mutators_stack_init_method); + + std::vector>::const_iterator iter = + mutators_stack.Begin(); + while (iter != mutators_stack.End()) { + switch ((*iter)->GetType()) { + case MutatorType::kTransform: { + const DlMatrix& matrix = (*iter)->GetMatrix(); + DlScalar matrix_array[9]{ + matrix.m[0], matrix.m[4], matrix.m[12], // + matrix.m[1], matrix.m[5], matrix.m[13], // + matrix.m[3], matrix.m[7], matrix.m[15], + }; + fml::jni::ScopedJavaLocalRef transformMatrix( + env, env->NewFloatArray(9)); + + env->SetFloatArrayRegion(transformMatrix.obj(), 0, 9, matrix_array); + env->CallVoidMethod(mutatorsStack, + g_mutators_stack_push_transform_method, + transformMatrix.obj()); + break; + } + case MutatorType::kClipRect: { + const DlRect& rect = (*iter)->GetRect(); + env->CallVoidMethod(mutatorsStack, + g_mutators_stack_push_cliprect_method, + static_cast(rect.GetLeft()), // + static_cast(rect.GetTop()), // + static_cast(rect.GetRight()), // + static_cast(rect.GetBottom())); + break; + } + case MutatorType::kClipRRect: { + const DlRoundRect& rrect = (*iter)->GetRRect(); + const DlRect& rect = rrect.GetBounds(); + const DlRoundingRadii radii = rrect.GetRadii(); + SkScalar radiis[8] = { + radii.top_left.width, radii.top_left.height, + radii.top_right.width, radii.top_right.height, + radii.bottom_right.width, radii.bottom_right.height, + radii.bottom_left.width, radii.bottom_left.height, + }; + fml::jni::ScopedJavaLocalRef radiisArray( + env, env->NewFloatArray(8)); + env->SetFloatArrayRegion(radiisArray.obj(), 0, 8, radiis); + env->CallVoidMethod(mutatorsStack, + g_mutators_stack_push_cliprrect_method, + static_cast(rect.GetLeft()), // + static_cast(rect.GetTop()), // + static_cast(rect.GetRight()), // + static_cast(rect.GetBottom()), // + radiisArray.obj()); + break; + } + case MutatorType::kClipRSE: { + const DlRoundRect& rrect = (*iter)->GetRSEApproximation(); + const DlRect& rect = rrect.GetBounds(); + const DlRoundingRadii radii = rrect.GetRadii(); + SkScalar radiis[8] = { + radii.top_left.width, radii.top_left.height, + radii.top_right.width, radii.top_right.height, + radii.bottom_right.width, radii.bottom_right.height, + radii.bottom_left.width, radii.bottom_left.height, + }; + fml::jni::ScopedJavaLocalRef radiisArray( + env, env->NewFloatArray(8)); + env->SetFloatArrayRegion(radiisArray.obj(), 0, 8, radiis); + env->CallVoidMethod(mutatorsStack, + g_mutators_stack_push_cliprrect_method, + static_cast(rect.GetLeft()), // + static_cast(rect.GetTop()), // + static_cast(rect.GetRight()), // + static_cast(rect.GetBottom()), // + radiisArray.obj()); + break; + } + // TODO(cyanglaz): Implement other mutators. + // https://github.com/flutter/flutter/issues/58426 + case MutatorType::kClipPath: + case MutatorType::kOpacity: + case MutatorType::kBackdropFilter: + break; + } + ++iter; + } + + env->CallVoidMethod(java_object.obj(), g_on_display_platform_view_method, + view_id, x, y, width, height, viewWidth, viewHeight, + mutatorsStack); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::FlutterViewDisplayOverlaySurface( + int surface_id, + int x, + int y, + int width, + int height) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_on_display_overlay_surface_method, + surface_id, x, y, width, height); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::FlutterViewBeginFrame() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_on_begin_frame_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::FlutterViewEndFrame() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_on_end_frame_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +std::unique_ptr +PlatformViewAndroidJNIImpl::FlutterViewCreateOverlaySurface() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return nullptr; + } + + fml::jni::ScopedJavaLocalRef overlay( + env, env->CallObjectMethod(java_object.obj(), + g_create_overlay_surface_method)); + FML_CHECK(fml::jni::CheckException(env)); + + if (overlay.is_null()) { + return std::make_unique(0, + nullptr); + } + + jint overlay_id = + env->CallIntMethod(overlay.obj(), g_overlay_surface_id_method); + + jobject overlay_surface = + env->CallObjectMethod(overlay.obj(), g_overlay_surface_surface_method); + + auto overlay_window = fml::MakeRefCounted( + ANativeWindow_fromSurface(env, overlay_surface)); + + return std::make_unique( + overlay_id, std::move(overlay_window)); +} + +void PlatformViewAndroidJNIImpl::FlutterViewDestroyOverlaySurfaces() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_destroy_overlay_surfaces_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +std::unique_ptr> +PlatformViewAndroidJNIImpl::FlutterViewComputePlatformResolvedLocale( + std::vector supported_locales_data) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + std::unique_ptr> out = + std::make_unique>(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return out; + } + fml::jni::ScopedJavaLocalRef j_locales_data = + fml::jni::VectorToStringArray(env, supported_locales_data); + jobjectArray result = static_cast(env->CallObjectMethod( + java_object.obj(), g_compute_platform_resolved_locale_method, + j_locales_data.obj())); + + FML_CHECK(fml::jni::CheckException(env)); + + int length = env->GetArrayLength(result); + for (int i = 0; i < length; i++) { + out->emplace_back(fml::jni::JavaStringToString( + env, static_cast(env->GetObjectArrayElement(result, i)))); + } + return out; +} + +double PlatformViewAndroidJNIImpl::GetDisplayRefreshRate() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return kUnknownDisplayRefreshRate; + } + + fml::jni::ScopedJavaLocalRef clazz( + env, env->GetObjectClass(java_object.obj())); + if (clazz.is_null()) { + return kUnknownDisplayRefreshRate; + } + + jfieldID fid = env->GetStaticFieldID(clazz.obj(), "refreshRateFPS", "F"); + return static_cast(env->GetStaticFloatField(clazz.obj(), fid)); +} + +double PlatformViewAndroidJNIImpl::GetDisplayWidth() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return -1; + } + + fml::jni::ScopedJavaLocalRef clazz( + env, env->GetObjectClass(java_object.obj())); + if (clazz.is_null()) { + return -1; + } + + jfieldID fid = env->GetStaticFieldID(clazz.obj(), "displayWidth", "F"); + return static_cast(env->GetStaticFloatField(clazz.obj(), fid)); +} + +double PlatformViewAndroidJNIImpl::GetDisplayHeight() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return -1; + } + + fml::jni::ScopedJavaLocalRef clazz( + env, env->GetObjectClass(java_object.obj())); + if (clazz.is_null()) { + return -1; + } + + jfieldID fid = env->GetStaticFieldID(clazz.obj(), "displayHeight", "F"); + return static_cast(env->GetStaticFloatField(clazz.obj(), fid)); +} + +double PlatformViewAndroidJNIImpl::GetDisplayDensity() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return -1; + } + + fml::jni::ScopedJavaLocalRef clazz( + env, env->GetObjectClass(java_object.obj())); + if (clazz.is_null()) { + return -1; + } + + jfieldID fid = env->GetStaticFieldID(clazz.obj(), "displayDensity", "F"); + return static_cast(env->GetStaticFloatField(clazz.obj(), fid)); +} + +bool PlatformViewAndroidJNIImpl::RequestDartDeferredLibrary( + int loading_unit_id) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return true; + } + + env->CallVoidMethod(java_object.obj(), g_request_dart_deferred_library_method, + loading_unit_id); + + FML_CHECK(fml::jni::CheckException(env)); + return true; +} + +// New Platform View Support. + +ASurfaceTransaction* PlatformViewAndroidJNIImpl::createTransaction() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return nullptr; + } + + fml::jni::ScopedJavaLocalRef transaction( + env, + env->CallObjectMethod(java_object.obj(), g_create_transaction_method)); + if (transaction.is_null()) { + return nullptr; + } + FML_CHECK(fml::jni::CheckException(env)); + + return impeller::android::GetProcTable().ASurfaceTransaction_fromJava( + env, transaction.obj()); +} + +void PlatformViewAndroidJNIImpl::swapTransaction() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_swap_transaction_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::applyTransaction() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_apply_transaction_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +std::unique_ptr +PlatformViewAndroidJNIImpl::createOverlaySurface2() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return nullptr; + } + + fml::jni::ScopedJavaLocalRef overlay( + env, env->CallObjectMethod(java_object.obj(), + g_create_overlay_surface2_method)); + FML_CHECK(fml::jni::CheckException(env)); + + if (overlay.is_null()) { + return std::make_unique(0, + nullptr); + } + + jint overlay_id = + env->CallIntMethod(overlay.obj(), g_overlay_surface_id_method); + + jobject overlay_surface = + env->CallObjectMethod(overlay.obj(), g_overlay_surface_surface_method); + + auto overlay_window = fml::MakeRefCounted( + ANativeWindow_fromSurface(env, overlay_surface)); + + return std::make_unique( + overlay_id, std::move(overlay_window)); +} + +void PlatformViewAndroidJNIImpl::destroyOverlaySurface2() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_destroy_overlay_surface2_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +namespace { +class AndroidPathReceiver final : public DlPathReceiver { + public: + explicit AndroidPathReceiver(JNIEnv* env) + : env_(env), + android_path_(env->NewObject(path_class->obj(), path_constructor)) {} + + void SetPathInfo(DlPathFillType type, bool is_convex) override { + // Need to convert the fill type to the Android enum and + // call setFillType on the path... + // see https://github.com/flutter/flutter/issues/164808 + } + void MoveTo(const DlPoint& p2) override { + env_->CallVoidMethod(android_path_, path_move_to_method, p2.x, p2.y); + } + void LineTo(const DlPoint& p2) override { + env_->CallVoidMethod(android_path_, path_line_to_method, p2.x, p2.y); + } + void QuadTo(const DlPoint& cp, const DlPoint& p2) override { + env_->CallVoidMethod(android_path_, path_quad_to_method, // + cp.x, cp.y, p2.x, p2.y); + } + bool ConicTo(const DlPoint& cp, const DlPoint& p2, DlScalar weight) override { + if (!path_conic_to_method) { + return false; + } + env_->CallVoidMethod(android_path_, path_conic_to_method, // + cp.x, cp.y, p2.x, p2.y, weight); + return true; + }; + void CubicTo(const DlPoint& cp1, + const DlPoint& cp2, + const DlPoint& p2) override { + env_->CallVoidMethod(android_path_, path_cubic_to_method, // + cp1.x, cp1.y, cp2.x, cp2.y, p2.x, p2.y); + } + void Close() override { + env_->CallVoidMethod(android_path_, path_close_method); + } + + jobject TakePath() { return android_path_; } + + private: + JNIEnv* env_; + jobject android_path_; +}; +} // namespace + +void PlatformViewAndroidJNIImpl::onDisplayPlatformView2( + int32_t view_id, + int32_t x, + int32_t y, + int32_t width, + int32_t height, + int32_t viewWidth, + int32_t viewHeight, + MutatorsStack mutators_stack) { + JNIEnv* env = fml::jni::AttachCurrentThread(); + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + jobject mutatorsStack = env->NewObject(g_mutators_stack_class->obj(), + g_mutators_stack_init_method); + + std::vector>::const_iterator iter = + mutators_stack.Begin(); + while (iter != mutators_stack.End()) { + switch ((*iter)->GetType()) { + case MutatorType::kTransform: { + const DlMatrix& matrix = (*iter)->GetMatrix(); + DlScalar matrix_array[9]{ + matrix.m[0], matrix.m[4], matrix.m[12], // + matrix.m[1], matrix.m[5], matrix.m[13], // + matrix.m[3], matrix.m[7], matrix.m[15], + }; + fml::jni::ScopedJavaLocalRef transformMatrix( + env, env->NewFloatArray(9)); + + env->SetFloatArrayRegion(transformMatrix.obj(), 0, 9, matrix_array); + env->CallVoidMethod(mutatorsStack, + g_mutators_stack_push_transform_method, + transformMatrix.obj()); + break; + } + case MutatorType::kClipRect: { + const DlRect& rect = (*iter)->GetRect(); + env->CallVoidMethod(mutatorsStack, + g_mutators_stack_push_cliprect_method, + static_cast(rect.GetLeft()), // + static_cast(rect.GetTop()), // + static_cast(rect.GetRight()), // + static_cast(rect.GetBottom())); + break; + } + case MutatorType::kClipRRect: { + const DlRoundRect& rrect = (*iter)->GetRRect(); + const DlRect& rect = rrect.GetBounds(); + const DlRoundingRadii& radii = rrect.GetRadii(); + SkScalar radiis[8] = { + radii.top_left.width, radii.top_left.height, + radii.top_right.width, radii.top_right.height, + radii.bottom_right.width, radii.bottom_right.height, + radii.bottom_left.width, radii.bottom_left.height, + }; + fml::jni::ScopedJavaLocalRef radiisArray( + env, env->NewFloatArray(8)); + env->SetFloatArrayRegion(radiisArray.obj(), 0, 8, radiis); + env->CallVoidMethod(mutatorsStack, + g_mutators_stack_push_cliprrect_method, + static_cast(rect.GetLeft()), // + static_cast(rect.GetTop()), // + static_cast(rect.GetRight()), // + static_cast(rect.GetBottom()), // + radiisArray.obj()); + break; + } + case MutatorType::kClipRSE: { + const DlRoundRect& rrect = (*iter)->GetRSEApproximation(); + const DlRect& rect = rrect.GetBounds(); + const DlRoundingRadii& radii = rrect.GetRadii(); + SkScalar radiis[8] = { + radii.top_left.width, radii.top_left.height, + radii.top_right.width, radii.top_right.height, + radii.bottom_right.width, radii.bottom_right.height, + radii.bottom_left.width, radii.bottom_left.height, + }; + fml::jni::ScopedJavaLocalRef radiisArray( + env, env->NewFloatArray(8)); + env->SetFloatArrayRegion(radiisArray.obj(), 0, 8, radiis); + env->CallVoidMethod(mutatorsStack, + g_mutators_stack_push_cliprrect_method, + static_cast(rect.GetLeft()), // + static_cast(rect.GetTop()), // + static_cast(rect.GetRight()), // + static_cast(rect.GetBottom()), // + radiisArray.obj()); + break; + } + case MutatorType::kOpacity: { + float opacity = (*iter)->GetAlphaFloat(); + env->CallVoidMethod(mutatorsStack, g_mutators_stack_push_opacity_method, + opacity); + break; + } + case MutatorType::kClipPath: { + auto& dlPath = (*iter)->GetPath(); + // The layer mutator mechanism should have already caught and + // redirected these simplified path cases, which is important because + // the conics they generate (in the case of oval and rrect) will + // not match the results of an impeller path conversion very closely. + FML_DCHECK(!dlPath.IsRect()); + FML_DCHECK(!dlPath.IsOval()); + FML_DCHECK(!dlPath.IsRoundRect()); + + // Define and populate an Android Path with data from the DlPath + AndroidPathReceiver receiver(env); + + dlPath.Dispatch(receiver); + + env->CallVoidMethod(mutatorsStack, + g_mutators_stack_push_clippath_method, + receiver.TakePath()); + break; + } + // TODO(cyanglaz): Implement other mutators. + // https://github.com/flutter/flutter/issues/58426 + case MutatorType::kBackdropFilter: + break; + } + ++iter; + } + + env->CallVoidMethod(java_object.obj(), g_on_display_platform_view2_method, + view_id, x, y, width, height, viewWidth, viewHeight, + mutatorsStack); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::onEndFrame2() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_on_end_frame2_method); + + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::showOverlaySurface2() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_show_overlay_surface2_method); + FML_CHECK(fml::jni::CheckException(env)); +} + +void PlatformViewAndroidJNIImpl::hideOverlaySurface2() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + + auto java_object = java_object_.get(env); + if (java_object.is_null()) { + return; + } + + env->CallVoidMethod(java_object.obj(), g_hide_overlay_surface2_method); + FML_CHECK(fml::jni::CheckException(env)); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.h b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..06be3d01c1f824cbf677e44d6b00993c44811578 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.h @@ -0,0 +1,142 @@ +// 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_ANDROID_PLATFORM_VIEW_ANDROID_JNI_IMPL_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_JNI_IMPL_H_ + +#include "flutter/fml/platform/android/jni_weak_ref.h" +#include "flutter/shell/platform/android/jni/platform_view_android_jni.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Concrete implementation of `PlatformViewAndroidJNI` that is +/// compiled with the Android toolchain. +/// +class PlatformViewAndroidJNIImpl final : public PlatformViewAndroidJNI { + public: + explicit PlatformViewAndroidJNIImpl( + const fml::jni::JavaObjectWeakGlobalRef& java_object); + + ~PlatformViewAndroidJNIImpl() override; + + void FlutterViewHandlePlatformMessage( + std::unique_ptr message, + int responseId) override; + + void FlutterViewHandlePlatformMessageResponse( + int responseId, + std::unique_ptr data) override; + + void FlutterViewUpdateSemantics( + std::vector buffer, + std::vector strings, + std::vector> string_attribute_args) override; + + void FlutterViewUpdateCustomAccessibilityActions( + std::vector actions_buffer, + std::vector strings) override; + + void FlutterViewOnFirstFrame() override; + + void FlutterViewOnPreEngineRestart() override; + + void SurfaceTextureAttachToGLContext(JavaLocalRef surface_texture, + int textureId) override; + + bool SurfaceTextureShouldUpdate(JavaLocalRef surface_texture) override; + + void SurfaceTextureUpdateTexImage(JavaLocalRef surface_texture) override; + + SkM44 SurfaceTextureGetTransformMatrix(JavaLocalRef surface_texture) override; + + void SurfaceTextureDetachFromGLContext(JavaLocalRef surface_texture) override; + + JavaLocalRef ImageProducerTextureEntryAcquireLatestImage( + JavaLocalRef image_texture_entry) override; + + JavaLocalRef ImageGetHardwareBuffer(JavaLocalRef image) override; + + void ImageClose(JavaLocalRef image) override; + + void HardwareBufferClose(JavaLocalRef hardware_buffer) override; + + void FlutterViewOnDisplayPlatformView(int view_id, + int x, + int y, + int width, + int height, + int viewWidth, + int viewHeight, + MutatorsStack mutators_stack) override; + + void FlutterViewDisplayOverlaySurface(int surface_id, + int x, + int y, + int width, + int height) override; + + void FlutterViewBeginFrame() override; + + void FlutterViewEndFrame() override; + + std::unique_ptr + FlutterViewCreateOverlaySurface() override; + + void FlutterViewDestroyOverlaySurfaces() override; + + std::unique_ptr> + FlutterViewComputePlatformResolvedLocale( + std::vector supported_locales_data) override; + + double GetDisplayRefreshRate() override; + + double GetDisplayWidth() override; + + double GetDisplayHeight() override; + + double GetDisplayDensity() override; + + bool RequestDartDeferredLibrary(int loading_unit_id) override; + + double FlutterViewGetScaledFontSize(double unscaled_font_size, + int configuration_id) const override; + + // New Platform View Support. + ASurfaceTransaction* createTransaction() override; + + void swapTransaction() override; + + void applyTransaction() override; + + std::unique_ptr + createOverlaySurface2() override; + + void destroyOverlaySurface2() override; + + void onDisplayPlatformView2(int32_t view_id, + int32_t x, + int32_t y, + int32_t width, + int32_t height, + int32_t viewWidth, + int32_t viewHeight, + MutatorsStack mutators_stack) override; + + void showOverlaySurface2() override; + + void hideOverlaySurface2() override; + + void onEndFrame2() override; + + private: + // Reference to FlutterJNI object. + const fml::jni::JavaObjectWeakGlobalRef java_object_; + + FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewAndroidJNIImpl); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_JNI_IMPL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/platform_view_android_unittests.cc b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..94124428dfb3aee77e93a6f047353695e6f3c6fd --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/platform_view_android_unittests.cc @@ -0,0 +1,55 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "shell/platform/android/flutter_main.h" +#include "third_party/googletest/googlemock/include/gmock/gmock-nice-strict.h" + +namespace flutter { +namespace testing { + +// TODO(matanlurey): Re-enable. +// +// This test (and the entire suite) was skipped on CI (see +// https://github.com/flutter/flutter/issues/163742) and has since bit rotted +// (we fallback to OpenGLES on emulators for performance reasons); either fix +// the test, or remove it. +TEST(AndroidPlatformView, DISABLED_SelectsVulkanBasedOnApiLevel) { + Settings settings; + settings.enable_software_rendering = false; + settings.enable_impeller = true; + + EXPECT_EQ(FlutterMain::SelectedRenderingAPI(settings, 29), + AndroidRenderingAPI::kImpellerVulkan); + EXPECT_EQ(FlutterMain::SelectedRenderingAPI(settings, 24), + AndroidRenderingAPI::kImpellerOpenGLES); +} + +TEST(AndroidPlatformView, SoftwareRenderingNotSupportedWithImpeller) { + Settings settings; + settings.enable_software_rendering = true; + settings.enable_impeller = true; + + ASSERT_DEATH(FlutterMain::SelectedRenderingAPI(settings, 29), ""); +} + +TEST(AndroidPlatformView, FallsBackToGLESonEmulator) { + std::string emulator_product = "gphone_x64"; + std::string device_product = "smg1234"; + + EXPECT_TRUE(FlutterMain::IsDeviceEmulator(emulator_product)); + EXPECT_FALSE(FlutterMain::IsDeviceEmulator(device_product)); +} + +TEST(AndroidPlatformView, FallsBackToGLESonMostExynos) { + std::string exynos_board = "exynos7870"; + std::string snap_board = "smg1234"; + + EXPECT_TRUE(FlutterMain::IsKnownBadSOC(exynos_board)); + EXPECT_FALSE(FlutterMain::IsKnownBadSOC(snap_board)); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture.cc b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture.cc new file mode 100644 index 0000000000000000000000000000000000000000..0fd7331ee1e851d4be97673857bb8bc8c88e055e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture.cc @@ -0,0 +1,145 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/surface_texture_external_texture.h" + +#include + +#include + +#include "flutter/display_list/effects/dl_color_source.h" +#include "third_party/skia/include/core/SkAlphaType.h" +#include "third_party/skia/include/core/SkColorSpace.h" +#include "third_party/skia/include/core/SkColorType.h" +#include "third_party/skia/include/core/SkImage.h" + +namespace flutter { + +SurfaceTextureExternalTexture::SurfaceTextureExternalTexture( + int64_t id, + const fml::jni::ScopedJavaGlobalRef& surface_texture, + const std::shared_ptr& jni_facade) + : Texture(id), + jni_facade_(jni_facade), + surface_texture_(surface_texture), + transform_(SkMatrix::I()) {} + +SurfaceTextureExternalTexture::~SurfaceTextureExternalTexture() {} + +void SurfaceTextureExternalTexture::OnGrContextCreated() { + state_ = AttachmentState::kUninitialized; +} + +void SurfaceTextureExternalTexture::MarkNewFrameAvailable() { + // NOOP. +} + +void SurfaceTextureExternalTexture::Paint(PaintContext& context, + const DlRect& bounds, + bool freeze, + const DlImageSampling sampling) { + if (state_ == AttachmentState::kDetached) { + return; + } + const bool should_process_frame = + !freeze || ShouldUpdate() || dl_image_ == nullptr; + if (should_process_frame) { + ProcessFrame(context, ToSkRect(bounds)); + } + // If process frame failed, this may not be in attached state. + if (state_ != AttachmentState::kAttached) { + return; + } + + if (!dl_image_) { + FML_LOG(WARNING) + << "No DlImage available for SurfaceTextureExternalTexture to paint."; + return; + } + + DrawFrame(context, ToSkRect(bounds), sampling); +} + +void SurfaceTextureExternalTexture::DrawFrame( + PaintContext& context, + const SkRect& bounds, + const DlImageSampling sampling) const { + auto transform = ToDlMatrix(GetCurrentUVTransformation()); + + // Android's SurfaceTexture transform matrix works on texture coordinate + // lookups in the range 0.0-1.0, while Skia's Shader transform matrix works on + // the image itself, as if it were inscribed inside a clip rect. + // An Android transform that scales lookup by 0.5 (displaying 50% of the + // texture) is the same as a Skia transform by 2.0 (scaling 50% of the image + // outside of the virtual "clip rect"), so we invert the incoming matrix. + + if (transform.IsIdentity()) { + context.canvas->DrawImage(dl_image_, DlPoint{0, 0}, sampling, + context.paint); + return; + } + + if (!transform.IsInvertible()) { + FML_LOG(FATAL) + << "Invalid (not invertable) SurfaceTexture transformation matrix"; + } + transform = transform.Invert(); + + DlAutoCanvasRestore autoRestore(context.canvas, true); + + // The incoming texture is vertically flipped, so we flip it + // back. OpenGL's coordinate system has Positive Y equivalent to up, while + // Skia's coordinate system has Negative Y equvalent to up. + context.canvas->Translate(bounds.x(), bounds.y() + bounds.height()); + context.canvas->Scale(bounds.width(), -bounds.height()); + + auto source = DlColorSource::MakeImage( + dl_image_, DlTileMode::kClamp, DlTileMode::kClamp, sampling, &transform); + + DlPaint paintWithShader; + if (context.paint) { + paintWithShader = *context.paint; + } + paintWithShader.setColorSource(source); + context.canvas->DrawRect(DlRect::MakeWH(1, 1), paintWithShader); +} + +void SurfaceTextureExternalTexture::OnGrContextDestroyed() { + if (state_ == AttachmentState::kAttached) { + Detach(); + } + state_ = AttachmentState::kDetached; +} + +void SurfaceTextureExternalTexture::OnTextureUnregistered() {} + +void SurfaceTextureExternalTexture::Detach() { + jni_facade_->SurfaceTextureDetachFromGLContext( + fml::jni::ScopedJavaLocalRef(surface_texture_)); + dl_image_.reset(); +} + +void SurfaceTextureExternalTexture::Attach(int gl_tex_id) { + jni_facade_->SurfaceTextureAttachToGLContext( + fml::jni::ScopedJavaLocalRef(surface_texture_), gl_tex_id); + state_ = AttachmentState::kAttached; +} + +bool SurfaceTextureExternalTexture::ShouldUpdate() { + return jni_facade_->SurfaceTextureShouldUpdate( + fml::jni::ScopedJavaLocalRef(surface_texture_)); +} + +void SurfaceTextureExternalTexture::Update() { + jni_facade_->SurfaceTextureUpdateTexImage( + fml::jni::ScopedJavaLocalRef(surface_texture_)); + transform_ = jni_facade_->SurfaceTextureGetTransformMatrix( + fml::jni::ScopedJavaLocalRef(surface_texture_)); +} + +const SkM44& SurfaceTextureExternalTexture::GetCurrentUVTransformation() const { + return transform_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture.h b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture.h new file mode 100644 index 0000000000000000000000000000000000000000..97ba37ee90f849bc0df468d19a2cef099710defc --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture.h @@ -0,0 +1,140 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_H_ + +#include + +#include "flutter/common/graphics/texture.h" +#include "flutter/shell/platform/android/platform_view_android_jni_impl.h" +#include "flutter/third_party/skia/include/core/SkM44.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Instances of external textures peered to +/// `android.graphics.SurfaceTexture`. +/// +/// SurfaceTextures are used on older versions of Android (API < +/// 29). On newer versions, the Android Hardware Buffer backend +/// `flutter::ImageExternalTexture` instances are used instead. +/// +/// Due to the way surface textures are designed, it is not possible +/// to have a Vulkan renderer interoperate with such textures. +/// Consequently, both Skia and Impeller only have OpenGL +/// implementations for these kinds of textures. +/// +/// This is an abstract base class. Minimally, subclasses override +/// the pure virtual `ProcessFrame` method to bind the package +/// specific texture implementation to the surface texture. +/// +class SurfaceTextureExternalTexture : public flutter::Texture { + public: + SurfaceTextureExternalTexture( + int64_t id, + const fml::jni::ScopedJavaGlobalRef& surface_texture, + const std::shared_ptr& jni_facade); + + // |Texture| + ~SurfaceTextureExternalTexture() override; + + protected: + //---------------------------------------------------------------------------- + /// @brief Subclasses override this method to bind the OpenGL texture + /// resource represented by this surface texture to the package + /// specific texture (SkImage, impeller::Texture, etc...). + /// + /// @important The state of texture should be AttachmentState::kAttached + /// after a call to this method. That is the responsibility of the + /// subclass. + /// + /// @param context The context. + /// @param[in] bounds The bounds of the texture. + /// + virtual void ProcessFrame(PaintContext& context, const SkRect& bounds) = 0; + + virtual void DrawFrame(PaintContext& context, + const SkRect& bounds, + const DlImageSampling sampling) const; + + //---------------------------------------------------------------------------- + /// @brief Get the transformation that should be applied to the UV + /// texture coordinates when sampling from this texture. + /// + /// @return The current uv transformation. + /// + const SkM44& GetCurrentUVTransformation() const; + + //---------------------------------------------------------------------------- + /// @brief Provides an opportunity for the subclasses to sever the + /// connection between the OpenGL texture resource represented by + /// this surface texture and the underlying package handle + /// (SkImage, impeller::Texture, etc...). + /// + /// @important It is the responsibility of the subclass to ensure that a + /// context is current when this call is made. Subclass can do + /// this by overriding this method, making the context current in + /// the implementation and calling the base class method. + /// + virtual void Detach(); + + //---------------------------------------------------------------------------- + /// @brief Attaches the given OpenGL texture handle to the surface + /// texture via a bind operation. + /// + /// @important It is the responsibility of the subclass to ensure that a + /// context is current when this call is made. Subclass can do + /// this by overriding this method, making the context current in + /// the implementation and calling the base class method. + /// + /// @param[in] gl_tex_id The gl tex identifier + /// + void Attach(int gl_tex_id); + + bool ShouldUpdate(); + + //---------------------------------------------------------------------------- + /// @brief Update the surface texture contents and transformation matrix. + /// + void Update(); + + //---------------------------------------------------------------------------- + /// @brief Specifies how this instance is bound to the underlying surface + /// texture. + /// + enum class AttachmentState { kUninitialized, kAttached, kDetached }; + + std::shared_ptr jni_facade_; + fml::jni::ScopedJavaGlobalRef surface_texture_; + AttachmentState state_ = AttachmentState::kUninitialized; + sk_sp dl_image_; + + private: + SkM44 transform_; + + // |Texture| + void Paint(PaintContext& context, + const DlRect& bounds, + bool freeze, + const DlImageSampling sampling) override; + + // |ContextListener| + void OnGrContextCreated() override; + + // |ContextListener| + void OnGrContextDestroyed() override; + + // |Texture| + void MarkNewFrameAvailable() override; + + // |Texture| + void OnTextureUnregistered() override; + + FML_DISALLOW_COPY_AND_ASSIGN(SurfaceTextureExternalTexture); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_impeller.cc b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..94eda0f6a2cb8d2b3773953f223316890b64b2ed --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_impeller.cc @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/surface_texture_external_texture_gl_impeller.h" + +#include "flutter/impeller/display_list/dl_image_impeller.h" + +namespace flutter { + +SurfaceTextureExternalTextureGLImpeller:: + SurfaceTextureExternalTextureGLImpeller( + const std::shared_ptr& context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& surface_texture, + const std::shared_ptr& jni_facade) + : SurfaceTextureExternalTexture(id, surface_texture, jni_facade), + impeller_context_(context) {} + +SurfaceTextureExternalTextureGLImpeller:: + ~SurfaceTextureExternalTextureGLImpeller() = default; + +void SurfaceTextureExternalTextureGLImpeller::ProcessFrame( + PaintContext& context, + const SkRect& bounds) { + if (state_ == AttachmentState::kUninitialized) { + // Generate the texture handle. + impeller::TextureDescriptor desc; + desc.type = impeller::TextureType::kTextureExternalOES; + desc.storage_mode = impeller::StorageMode::kDevicePrivate; + desc.format = impeller::PixelFormat::kR8G8B8A8UNormInt; + desc.size = {1, 1}; + desc.mip_count = 1; + texture_ = std::make_shared( + impeller_context_->GetReactor(), desc); + // The contents will be initialized later in the call to `Attach` instead of + // by Impeller. + texture_->MarkContentsInitialized(); + texture_->SetCoordinateSystem( + impeller::TextureCoordinateSystem::kUploadFromHost); + auto maybe_handle = texture_->GetGLHandle(); + if (!maybe_handle.has_value()) { + FML_LOG(ERROR) << "Could not get GL handle from impeller::TextureGLES!"; + return; + } + Attach(maybe_handle.value()); + } + FML_CHECK(state_ == AttachmentState::kAttached); + + // Updates the texture contents and transformation matrix. + Update(); + + dl_image_ = impeller::DlImageImpeller::Make(texture_); +} + +void SurfaceTextureExternalTextureGLImpeller::Detach() { + SurfaceTextureExternalTexture::Detach(); + texture_.reset(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_impeller.h b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..bd291f827fe33a6f0899abb8bd79824dfab4686f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_impeller.h @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_GL_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_GL_IMPELLER_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/impeller/renderer/backend/gles/context_gles.h" +#include "flutter/impeller/renderer/backend/gles/texture_gles.h" +#include "flutter/shell/platform/android/surface_texture_external_texture.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Binds the surface texture to an Impeller texture. +/// +class SurfaceTextureExternalTextureGLImpeller + : public SurfaceTextureExternalTexture { + public: + SurfaceTextureExternalTextureGLImpeller( + const std::shared_ptr& context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& surface_texture, + const std::shared_ptr& jni_facade); + + // |SurfaceTextureExternalTexture| + ~SurfaceTextureExternalTextureGLImpeller() override; + + private: + // |SurfaceTextureExternalTexture| + virtual void ProcessFrame(PaintContext& context, + const SkRect& bounds) override; + + // |SurfaceTextureExternalTexture| + virtual void Detach() override; + + const std::shared_ptr impeller_context_; + std::shared_ptr texture_; + + FML_DISALLOW_COPY_AND_ASSIGN(SurfaceTextureExternalTextureGLImpeller); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_GL_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_skia.cc b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..dfa5797e50cc52751fb70be72ac59fd71d89cffa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_skia.cc @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/surface_texture_external_texture_gl_skia.h" + +#include +#define GL_GLEXT_PROTOTYPES +#include + +#include "flutter/third_party/skia/include/core/SkColorSpace.h" +#include "flutter/third_party/skia/include/gpu/ganesh/GrBackendSurface.h" +#include "flutter/third_party/skia/include/gpu/ganesh/GrDirectContext.h" +#include "flutter/third_party/skia/include/gpu/ganesh/SkImageGanesh.h" +#include "flutter/third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" +#include "flutter/third_party/skia/include/gpu/ganesh/gl/GrGLTypes.h" + +namespace flutter { + +SurfaceTextureExternalTextureGLSkia::SurfaceTextureExternalTextureGLSkia( + int64_t id, + const fml::jni::ScopedJavaGlobalRef& surface_texture, + const std::shared_ptr& jni_facade) + : SurfaceTextureExternalTexture(id, surface_texture, jni_facade) {} + +SurfaceTextureExternalTextureGLSkia::~SurfaceTextureExternalTextureGLSkia() { + if (texture_name_ != 0) { + glDeleteTextures(1, &texture_name_); + } +} + +void SurfaceTextureExternalTextureGLSkia::ProcessFrame(PaintContext& context, + const SkRect& bounds) { + if (state_ == AttachmentState::kUninitialized) { + // Generate the texture handle. + glGenTextures(1, &texture_name_); + Attach(texture_name_); + } + FML_CHECK(state_ == AttachmentState::kAttached); + + // Updates the texture contents and transformation matrix. + Update(); + + GrGLTextureInfo textureInfo = {GL_TEXTURE_EXTERNAL_OES, texture_name_, + GL_RGBA8_OES}; + auto backendTexture = + GrBackendTextures::MakeGL(1, 1, skgpu::Mipmapped::kNo, textureInfo); + dl_image_ = DlImage::Make(SkImages::BorrowTextureFrom( + context.gr_context, backendTexture, kTopLeft_GrSurfaceOrigin, + kRGBA_8888_SkColorType, kPremul_SkAlphaType, nullptr)); +} + +void SurfaceTextureExternalTextureGLSkia::Detach() { + SurfaceTextureExternalTexture::Detach(); + if (texture_name_ != 0) { + glDeleteTextures(1, &texture_name_); + texture_name_ = 0; + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_skia.h b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..75ddfe637cecdf23435dd2edb1316b55d8e374e6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_gl_skia.h @@ -0,0 +1,43 @@ +// 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_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_GL_SKIA_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_GL_SKIA_H_ + +#include + +#include "flutter/shell/platform/android/surface_texture_external_texture.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Binds the surface texture to a Skia SkImage. +/// +class SurfaceTextureExternalTextureGLSkia + : public SurfaceTextureExternalTexture { + public: + SurfaceTextureExternalTextureGLSkia( + int64_t id, + const fml::jni::ScopedJavaGlobalRef& surface_texture, + const std::shared_ptr& jni_facade); + + // |SurfaceTextureExternalTexture| + ~SurfaceTextureExternalTextureGLSkia() override; + + private: + // |SurfaceTextureExternalTexture| + virtual void ProcessFrame(PaintContext& context, + const SkRect& bounds) override; + + // |SurfaceTextureExternalTexture| + virtual void Detach() override; + + GLuint texture_name_ = 0; + + FML_DISALLOW_COPY_AND_ASSIGN(SurfaceTextureExternalTextureGLSkia); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_GL_SKIA_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_vk_impeller.cc b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_vk_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..89a5edd36628548bfc829cab98011f44194f69ea --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_vk_impeller.cc @@ -0,0 +1,233 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/surface_texture_external_texture_vk_impeller.h" + +#include + +#include +#define GL_GLEXT_PROTOTYPES +#include + +#include "flutter/fml/trace_event.h" +#include "flutter/impeller/display_list/dl_image_impeller.h" +#include "flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "flutter/impeller/renderer/backend/vulkan/surface_context_vk.h" +#include "flutter/impeller/renderer/backend/vulkan/texture_vk.h" +#include "flutter/impeller/toolkit/android/hardware_buffer.h" + +namespace flutter { + +using namespace impeller; + +SurfaceTextureExternalTextureVKImpeller:: + SurfaceTextureExternalTextureVKImpeller( + std::shared_ptr context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& surface_texture, + const std::shared_ptr& jni_facade) + : SurfaceTextureExternalTexture(id, surface_texture, jni_facade), + context_(std::move(context)), + trampoline_(std::make_shared()) { + is_valid_ = trampoline_->IsValid(); +} + +SurfaceTextureExternalTextureVKImpeller:: + ~SurfaceTextureExternalTextureVKImpeller() = default; + +enum class LayoutUpdateMode { + kSync, + kAsync, +}; + +static bool SetTextureLayout(const ContextVK& context, + const TextureSourceVK* texture, + vk::ImageLayout layout, + LayoutUpdateMode mode) { + TRACE_EVENT0("flutter", __FUNCTION__); + if (!texture) { + return true; + } + auto command_buffer = context.CreateCommandBuffer(); + if (!command_buffer) { + VALIDATION_LOG + << "Could not create command buffer for texture layout update."; + return false; + } + command_buffer->SetLabel("GLVKTextureLayoutUpdateCB"); + const CommandBufferVK& encoder = CommandBufferVK::Cast(*command_buffer); + const auto command_buffer_vk = encoder.GetCommandBuffer(); + + BarrierVK barrier; + barrier.cmd_buffer = command_buffer_vk; + barrier.new_layout = layout; + barrier.src_stage = vk::PipelineStageFlagBits::eColorAttachmentOutput | + impeller::vk::PipelineStageFlagBits::eFragmentShader; + barrier.src_access = vk::AccessFlagBits::eColorAttachmentWrite | + vk::AccessFlagBits::eShaderRead; + barrier.dst_stage = impeller::vk::PipelineStageFlagBits::eFragmentShader; + barrier.dst_access = vk::AccessFlagBits::eShaderRead; + + if (!texture->SetLayout(barrier).ok()) { + VALIDATION_LOG << "Could not encoder layout transition."; + return false; + } + + encoder.EndCommandBuffer(); + + vk::SubmitInfo submit_info; + submit_info.setCommandBuffers(command_buffer_vk); + + // There is no need to track the fence in the encoder since we are going to do + // a sync wait for completion. + vk::UniqueFence fence; + + if (mode == LayoutUpdateMode::kSync) { + auto fence_pair = + context.GetDevice().createFenceUnique(vk::FenceCreateFlags{}); + if (fence_pair.result != impeller::vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create fence."; + return false; + } + fence = std::move(fence_pair.value); + } + + if (context.GetGraphicsQueue()->Submit(submit_info, fence.get()) != + impeller::vk::Result::eSuccess) { + VALIDATION_LOG << "Could not submit layout transition fence."; + return false; + } + + using namespace std::chrono_literals; + + if (fence && + context.GetDevice().waitForFences( + fence.get(), // + VK_TRUE, // + std::chrono::duration_cast(1s).count() // + ) != impeller::vk::Result::eSuccess) { + VALIDATION_LOG << "Could not perform sync wait on fence."; + return false; + } + + return true; +} + +// |SurfaceTextureExternalTexture| +void SurfaceTextureExternalTextureVKImpeller::ProcessFrame( + PaintContext& context, + const SkRect& bounds) { + if (!is_valid_ || !context.aiks_context) { + VALIDATION_LOG << "Invalid external texture."; + return; + } + DlMatrix matrix = context.canvas->GetMatrix(); + DlRect mapped_bounds = ToDlRect(bounds).TransformAndClipBounds(matrix); + + const auto& surface_context = + SurfaceContextVK::Cast(*context.aiks_context->GetContext()); + const auto& context_vk = ContextVK::Cast(*surface_context.GetParent()); + + auto dst_texture = GetCachedTextureSource( + surface_context.GetParent(), // + ISize::MakeWH(mapped_bounds.GetWidth(), mapped_bounds.GetHeight()) // + ); + if (!dst_texture || !dst_texture->IsValid()) { + VALIDATION_LOG << "Could not fetch trampoline texture target."; + return; + } + + auto current_context = trampoline_->MakeCurrentContext(); + + GLuint src_gl_texture = {}; + glGenTextures(1u, &src_gl_texture); + Attach(src_gl_texture); + Update(); + + SetTextureLayout(context_vk, dst_texture.get(), + vk::ImageLayout::eColorAttachmentOptimal, + LayoutUpdateMode::kSync); + + impeller::Matrix uv_transformation; + GetCurrentUVTransformation().getColMajor( + reinterpret_cast(&uv_transformation)); + + glvk::Trampoline::GLTextureInfo src_texture; + src_texture.texture = src_gl_texture; + src_texture.target = GL_TEXTURE_EXTERNAL_OES; + src_texture.uv_transformation = uv_transformation; + + if (!trampoline_->BlitTextureOpenGLToVulkan(src_texture, *dst_texture)) { + VALIDATION_LOG << "Texture copy failed."; + } + + SetTextureLayout(context_vk, dst_texture.get(), + vk::ImageLayout::eShaderReadOnlyOptimal, + LayoutUpdateMode::kAsync); + + glDeleteTextures(1u, &src_gl_texture); + + dl_image_ = DlImageImpeller::Make( + std::make_shared(surface_context.GetParent(), dst_texture)); +} + +// |SurfaceTextureExternalTexture| +void SurfaceTextureExternalTextureVKImpeller::Detach() { + // Detaching from the underlying surface texture requires a context to be + // current. On the other hand, the texture source is a pure Vulkan construct + // and has no EGL related requirements. + auto context = trampoline_->MakeCurrentContext(); + SurfaceTextureExternalTexture::Detach(); + cached_texture_source_.reset(); +} + +std::shared_ptr +SurfaceTextureExternalTextureVKImpeller::GetCachedTextureSource( + const std::shared_ptr& context, + const impeller::ISize& size) { + if (cached_texture_source_ && + cached_texture_source_->GetTextureDescriptor().size == size) { + return cached_texture_source_; + } + cached_texture_source_ = nullptr; + + android::HardwareBufferDescriptor ahb_descriptor; + ahb_descriptor.format = android::HardwareBufferFormat::kR8G8B8A8UNormInt; + ahb_descriptor.size = size.Max(ISize{1u, 1u}); + ahb_descriptor.usage = + android::HardwareBufferUsageFlags::kFrameBufferAttachment | + android::HardwareBufferUsageFlags::kSampledImage; + + if (!ahb_descriptor.IsAllocatable()) { + VALIDATION_LOG << "Invalid hardware buffer texture descriptor."; + return nullptr; + } + + auto ahb = std::make_unique(ahb_descriptor); + if (!ahb->IsValid()) { + VALIDATION_LOG << "Could not allocate hardware buffer."; + return nullptr; + } + + auto texture_source = + std::make_shared(context, std::move(ahb), false); + + if (!texture_source->IsValid()) { + VALIDATION_LOG << "Could not create trampoline texture source."; + return nullptr; + } + cached_texture_source_ = std::move(texture_source); + return cached_texture_source_; +} + +// |SurfaceTextureExternalTexture| +void SurfaceTextureExternalTextureVKImpeller::DrawFrame( + PaintContext& context, + const SkRect& bounds, + const DlImageSampling sampling) const { + context.canvas->DrawImageRect(dl_image_, ToDlRect(bounds), sampling, + context.paint); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_vk_impeller.h b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_vk_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..1df76aa6ef20b9f238c97b37c9b3fa531cf24da8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/surface_texture_external_texture_vk_impeller.h @@ -0,0 +1,80 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_VK_IMPELLER_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_VK_IMPELLER_H_ + +#include + +#include "flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h" +#include "flutter/impeller/renderer/backend/vulkan/context_vk.h" +#include "flutter/impeller/toolkit/egl/context.h" +#include "flutter/impeller/toolkit/egl/display.h" +#include "flutter/impeller/toolkit/egl/surface.h" +#include "flutter/impeller/toolkit/glvk/trampoline.h" +#include "flutter/shell/platform/android/surface_texture_external_texture.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief An external texture implementation for Vulkan that uses OpenGL +/// to Vulkan texture interop to read SurfaceTexture based image +/// data and render it into a Vulkan texture. +/// +/// Unlike other zero-copy implementations, the OpenGL to Vulkan +/// texture interop has the additional overhead of one device-device +/// copy and allocates one offscreen texture. For this reason, one +/// of the "Image" based external texture implementations are a +/// recommended replacement for this class. For example +/// `ImageExternalTextureVKImpeller`. +/// +/// This implementation is used only as a fallback during the +/// migration away from the SurfaceTexture based plugin APIs. For +/// more information about the plugin API migration, see +/// https://docs.flutter.dev/release/breaking-changes/android-surface-plugins. +/// +/// @see `ImageExternalTextureVKImpeller` +/// +class SurfaceTextureExternalTextureVKImpeller final + : public SurfaceTextureExternalTexture { + public: + SurfaceTextureExternalTextureVKImpeller( + std::shared_ptr context, + int64_t id, + const fml::jni::ScopedJavaGlobalRef& surface_texture, + const std::shared_ptr& jni_facade); + + ~SurfaceTextureExternalTextureVKImpeller() override; + + SurfaceTextureExternalTextureVKImpeller( + const SurfaceTextureExternalTextureVKImpeller&) = delete; + + SurfaceTextureExternalTextureVKImpeller& operator=( + const SurfaceTextureExternalTextureVKImpeller&) = delete; + + private: + std::shared_ptr context_; + std::shared_ptr trampoline_; + std::shared_ptr cached_texture_source_; + bool is_valid_ = false; + + // |SurfaceTextureExternalTexture| + void ProcessFrame(PaintContext& context, const SkRect& bounds) override; + + // |SurfaceTextureExternalTexture| + void Detach() override; + + // |SurfaceTextureExternalTexture| + void DrawFrame(PaintContext& context, + const SkRect& bounds, + const DlImageSampling sampling) const override; + + std::shared_ptr GetCachedTextureSource( + const std::shared_ptr& context, + const impeller::ISize& size); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_TEXTURE_EXTERNAL_TEXTURE_VK_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/android/vsync_waiter_android.cc b/flutter/engine/src/flutter/shell/platform/android/vsync_waiter_android.cc new file mode 100644 index 0000000000000000000000000000000000000000..1c46b7dbf317571e87bd93b9e0e7f14bdd4a0648 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/vsync_waiter_android.cc @@ -0,0 +1,152 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/android/vsync_waiter_android.h" + +#include +#include + +#include "flutter/common/task_runners.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/platform/android/jni_util.h" +#include "flutter/fml/platform/android/scoped_java_ref.h" +#include "flutter/fml/trace_event.h" +#include "impeller/toolkit/android/choreographer.h" + +namespace flutter { + +static fml::jni::ScopedJavaGlobalRef* g_vsync_waiter_class = nullptr; +static jmethodID g_async_wait_for_vsync_method_ = nullptr; +static std::atomic_uint g_refresh_rate_ = 60; + +VsyncWaiterAndroid::VsyncWaiterAndroid(const flutter::TaskRunners& task_runners) + : VsyncWaiter(task_runners) {} + +VsyncWaiterAndroid::~VsyncWaiterAndroid() = default; + +// |VsyncWaiter| +void VsyncWaiterAndroid::AwaitVSync() { + const static bool use_choreographer = + impeller::android::Choreographer::IsAvailableOnPlatform(); + if (use_choreographer) { + auto* weak_this = new std::weak_ptr(shared_from_this()); + fml::TaskRunner::RunNowOrPostTask( + task_runners_.GetUITaskRunner(), [weak_this]() { + const auto& choreographer = + impeller::android::Choreographer::GetInstance(); + choreographer.PostFrameCallback([weak_this](auto time) { + auto time_ns = + std::chrono::time_point_cast(time) + .time_since_epoch() + .count(); + OnVsyncFromNDK(time_ns, weak_this); + }); + }); + } else { + // TODO(99798): Remove it when we drop support for API level < 29 and 32-bit + // devices. + auto* weak_this = new std::weak_ptr(shared_from_this()); + jlong java_baton = reinterpret_cast(weak_this); + task_runners_.GetPlatformTaskRunner()->PostTask([java_baton]() { + JNIEnv* env = fml::jni::AttachCurrentThread(); + env->CallStaticVoidMethod(g_vsync_waiter_class->obj(), // + g_async_wait_for_vsync_method_, // + java_baton // + ); + }); + } +} + +// static +void VsyncWaiterAndroid::OnVsyncFromNDK(int64_t frame_nanos, void* data) { + auto frame_time = fml::TimePoint::FromEpochDelta( + fml::TimeDelta::FromNanoseconds(frame_nanos)); + auto now = fml::TimePoint::Now(); + if (frame_time > now) { + frame_time = now; + } + auto target_time = frame_time + fml::TimeDelta::FromNanoseconds( + 1000000000.0 / g_refresh_rate_); + + TRACE_EVENT2_INT("flutter", "PlatformVsync", "frame_start_time", + frame_time.ToEpochDelta().ToMicroseconds(), + "frame_target_time", + target_time.ToEpochDelta().ToMicroseconds()); + + auto* weak_this = reinterpret_cast*>(data); + ConsumePendingCallback(weak_this, frame_time, target_time); +} + +// static +void VsyncWaiterAndroid::OnVsyncFromJava(JNIEnv* env, + jclass jcaller, + jlong frameDelayNanos, + jlong refreshPeriodNanos, + jlong java_baton) { + auto frame_time = + fml::TimePoint::Now() - fml::TimeDelta::FromNanoseconds(frameDelayNanos); + auto target_time = + frame_time + fml::TimeDelta::FromNanoseconds(refreshPeriodNanos); + + TRACE_EVENT2_INT("flutter", "PlatformVsync", "frame_start_time", + frame_time.ToEpochDelta().ToMicroseconds(), + "frame_target_time", + target_time.ToEpochDelta().ToMicroseconds()); + + auto* weak_this = reinterpret_cast*>(java_baton); + ConsumePendingCallback(weak_this, frame_time, target_time); +} + +// static +void VsyncWaiterAndroid::ConsumePendingCallback( + std::weak_ptr* weak_this, + fml::TimePoint frame_start_time, + fml::TimePoint frame_target_time) { + auto shared_this = weak_this->lock(); + delete weak_this; + + if (shared_this) { + shared_this->FireCallback(frame_start_time, frame_target_time); + } +} + +// static +void VsyncWaiterAndroid::OnUpdateRefreshRate(JNIEnv* env, + jclass jcaller, + jfloat refresh_rate) { + FML_DCHECK(refresh_rate > 0); + g_refresh_rate_ = static_cast(refresh_rate); +} + +// static +bool VsyncWaiterAndroid::Register(JNIEnv* env) { + static const JNINativeMethod methods[] = { + { + .name = "nativeOnVsync", + .signature = "(JJJ)V", + .fnPtr = reinterpret_cast(&OnVsyncFromJava), + }, + { + .name = "nativeUpdateRefreshRate", + .signature = "(F)V", + .fnPtr = reinterpret_cast(&OnUpdateRefreshRate), + }}; + + jclass clazz = env->FindClass("io/flutter/embedding/engine/FlutterJNI"); + + if (clazz == nullptr) { + return false; + } + + g_vsync_waiter_class = new fml::jni::ScopedJavaGlobalRef(env, clazz); + FML_CHECK(!g_vsync_waiter_class->is_null()); + + g_async_wait_for_vsync_method_ = env->GetStaticMethodID( + g_vsync_waiter_class->obj(), "asyncWaitForVsync", "(J)V"); + FML_CHECK(g_async_wait_for_vsync_method_ != nullptr); + + return env->RegisterNatives(clazz, methods, std::size(methods)) == 0; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/android/vsync_waiter_android.h b/flutter/engine/src/flutter/shell/platform/android/vsync_waiter_android.h new file mode 100644 index 0000000000000000000000000000000000000000..7129bb94305e2394bbb867b88448e5663bce4927 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/android/vsync_waiter_android.h @@ -0,0 +1,52 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_VSYNC_WAITER_ANDROID_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_VSYNC_WAITER_ANDROID_H_ + +#include + +#include + +#include "flutter/fml/macros.h" +#include "flutter/shell/common/vsync_waiter.h" + +namespace flutter { + +class AndroidChoreographer; + +class VsyncWaiterAndroid final : public VsyncWaiter { + public: + static bool Register(JNIEnv* env); + + explicit VsyncWaiterAndroid(const flutter::TaskRunners& task_runners); + + ~VsyncWaiterAndroid() override; + + private: + // |VsyncWaiter| + void AwaitVSync() override; + + static void OnVsyncFromNDK(int64_t frame_nanos, void* data); + + static void OnVsyncFromJava(JNIEnv* env, + jclass jcaller, + jlong frameDelayNanos, + jlong refreshPeriodNanos, + jlong java_baton); + + static void ConsumePendingCallback(std::weak_ptr* weak_this, + fml::TimePoint frame_start_time, + fml::TimePoint frame_target_time); + + static void OnUpdateRefreshRate(JNIEnv* env, + jclass jcaller, + jfloat refresh_rate); + + FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiterAndroid); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_VSYNC_WAITER_ANDROID_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/BUILD.gn b/flutter/engine/src/flutter/shell/platform/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5ebfb2236d2c5ba202338ff9ce58ad7efcdb43d0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/BUILD.gn @@ -0,0 +1,215 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/common/config.gni") +import("//flutter/testing/testing.gni") + +config("desktop_library_implementation") { + defines = [ "FLUTTER_DESKTOP_LIBRARY" ] +} + +_public_headers = [ + "public/flutter_export.h", + "public/flutter_macros.h", + "public/flutter_messenger.h", + "public/flutter_plugin_registrar.h", + "public/flutter_texture_registrar.h", +] + +# Any files that are built by clients (client_wrapper code, library headers for +# implementations using this shared code, etc.) include the public headers +# assuming they are in the include path. This configuration should be added to +# any such code that is also built by GN to make the includes work. +config("relative_flutter_library_headers") { + include_dirs = [ "public" ] +} + +# The headers are a separate source set since the client wrapper is allowed +# to depend on the public headers, but none of the rest of the code. +source_set("common_cpp_library_headers") { + public = _public_headers + + configs += [ ":desktop_library_implementation" ] +} + +copy("publish_headers") { + sources = _public_headers + outputs = [ "$root_out_dir/{{source_file_part}}" ] +} + +source_set("common_cpp_input") { + public = [ + "text_editing_delta.h", + "text_input_model.h", + "text_range.h", + ] + + sources = [ + "text_editing_delta.cc", + "text_input_model.cc", + ] + + configs += [ ":desktop_library_implementation" ] + + public_configs = [ "//flutter:config" ] + + deps = [ "//flutter/fml:fml" ] +} + +source_set("common_cpp_enums") { + public = [ + "app_lifecycle_state.h", + "platform_provided_menu.h", + ] + + public_configs = [ + "//flutter:config", + "//flutter/common:flutter_config", + ] +} + +source_set("common_cpp_switches") { + public = [ "engine_switches.h" ] + + sources = [ "engine_switches.cc" ] + + public_configs = [ + "//flutter:config", + "//flutter/common:flutter_config", + ] +} + +source_set("common_cpp_accessibility") { + public = [ + "accessibility_bridge.h", + "alert_platform_node_delegate.h", + "flutter_platform_node_delegate.h", + ] + + sources = [ + "accessibility_bridge.cc", + "alert_platform_node_delegate.cc", + "flutter_platform_node_delegate.cc", + ] + + public_configs = + [ "//flutter/third_party/accessibility:accessibility_config" ] + + public_deps = [ + "//flutter/fml:fml", + "//flutter/shell/platform/embedder:embedder_as_internal_library", + "//flutter/third_party/accessibility", + ] +} + +source_set("common_cpp") { + public = [ + "incoming_message_dispatcher.h", + "json_message_codec.h", + "json_method_codec.h", + ] + + # TODO: Refactor flutter_glfw.cc to move the implementations corresponding + # to the _public_headers above into this target. + sources = [ + "incoming_message_dispatcher.cc", + "json_message_codec.cc", + "json_method_codec.cc", + ] + + configs += [ ":desktop_library_implementation" ] + + public_configs = [ "//flutter:config" ] + + deps = [ + ":common_cpp_library_headers", + "//flutter/shell/platform/common/client_wrapper:client_wrapper", + "//flutter/shell/platform/embedder:embedder_as_internal_library", + ] + + public_deps = [ + ":common_cpp_core", + "//flutter/third_party/rapidjson", + ] +} + +# The portion of common_cpp that has no dependencies on the public/ +# headers. This division should be revisited once the Linux GTK +# embedding is further along and it's clearer how much, if any, shared +# API surface there will be. +source_set("common_cpp_core") { + public = [ + "geometry.h", + "path_utils.h", + ] + + sources = [ "path_utils.cc" ] + + public_configs = [ "//flutter:config" ] +} + +if (enable_unittests) { + test_fixtures("common_cpp_core_fixtures") { + fixtures = [] + } + + executable("common_cpp_core_unittests") { + testonly = true + + sources = [ "path_utils_unittests.cc" ] + + deps = [ + ":common_cpp_core", + ":common_cpp_core_fixtures", + "$dart_src/runtime:libdart_jit", + "//flutter/testing", + ] + + public_configs = [ "//flutter:config" ] + } + + test_fixtures("common_cpp_fixtures") { + fixtures = [] + } + + executable("common_cpp_unittests") { + testonly = true + + sources = [ + "engine_switches_unittests.cc", + "geometry_unittests.cc", + "incoming_message_dispatcher_unittests.cc", + "json_message_codec_unittests.cc", + "json_method_codec_unittests.cc", + "text_editing_delta_unittests.cc", + "text_input_model_unittests.cc", + "text_range_unittests.cc", + ] + + deps = [ + ":common_cpp", + ":common_cpp_fixtures", + ":common_cpp_input", + ":common_cpp_switches", + "//flutter/fml:string_conversion", + "//flutter/shell/platform/common/client_wrapper:client_wrapper", + "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", + "//flutter/testing", + ] + + # The accessibility bridge only supports MacOS for now. + if (is_mac || is_win) { + sources += [ + "accessibility_bridge_unittests.cc", + "flutter_platform_node_delegate_unittests.cc", + "test_accessibility_bridge.cc", + "test_accessibility_bridge.h", + ] + + deps += [ ":common_cpp_accessibility" ] + } + + public_configs = [ "//flutter:config" ] + } +} diff --git a/flutter/engine/src/flutter/shell/platform/common/accessibility_bridge.cc b/flutter/engine/src/flutter/shell/platform/common/accessibility_bridge.cc new file mode 100644 index 0000000000000000000000000000000000000000..1913a580c509e2e89a5efcd624fc469774693f3d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/accessibility_bridge.cc @@ -0,0 +1,738 @@ +// 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 "accessibility_bridge.h" + +#include +#include + +#include "flutter/third_party/accessibility/ax/ax_tree_manager_map.h" +#include "flutter/third_party/accessibility/ax/ax_tree_update.h" +#include "flutter/third_party/accessibility/base/logging.h" + +namespace flutter { // namespace + +constexpr int kHasScrollingAction = + FlutterSemanticsAction::kFlutterSemanticsActionScrollLeft | + FlutterSemanticsAction::kFlutterSemanticsActionScrollRight | + FlutterSemanticsAction::kFlutterSemanticsActionScrollUp | + FlutterSemanticsAction::kFlutterSemanticsActionScrollDown; + +// AccessibilityBridge +AccessibilityBridge::AccessibilityBridge() + : tree_(std::make_unique()) { + event_generator_.SetTree(tree_.get()); + tree_->AddObserver(static_cast(this)); + ui::AXTreeData data = tree_->data(); + data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); + tree_->UpdateData(data); + ui::AXTreeManagerMap::GetInstance().AddTreeManager(tree_->GetAXTreeID(), + this); +} + +AccessibilityBridge::~AccessibilityBridge() { + event_generator_.ReleaseTree(); + tree_->RemoveObserver(static_cast(this)); +} + +void AccessibilityBridge::AddFlutterSemanticsNodeUpdate( + const FlutterSemanticsNode2& node) { + pending_semantics_node_updates_[node.id] = FromFlutterSemanticsNode(node); +} + +void AccessibilityBridge::AddFlutterSemanticsCustomActionUpdate( + const FlutterSemanticsCustomAction2& action) { + pending_semantics_custom_action_updates_[action.id] = + FromFlutterSemanticsCustomAction(action); +} + +void AccessibilityBridge::CommitUpdates() { + // AXTree cannot move a node in a single update. + // This must be split across two updates: + // + // * Update 1: remove nodes from their old parents. + // * Update 2: re-add nodes (including their children) to their new parents. + // + // First, start by removing nodes if necessary. + std::optional remove_reparented = + CreateRemoveReparentedNodesUpdate(); + if (remove_reparented.has_value()) { + tree_->Unserialize(remove_reparented.value()); + + std::string error = tree_->error(); + if (!error.empty()) { + FML_LOG(ERROR) << "Failed to update ui::AXTree, error: " << error; + assert(false); + return; + } + } + + // Second, apply the pending node updates. This also moves reparented nodes to + // their new parents if needed. + ui::AXTreeUpdate update{.tree_data = tree_->data()}; + + // Figure out update order, ui::AXTree only accepts update in tree order, + // where parent node must come before the child node in + // ui::AXTreeUpdate.nodes. We start with picking a random node and turn the + // entire subtree into a list. We pick another node from the remaining update, + // and keep doing so until the update map is empty. We then concatenate the + // lists in the reversed order, this guarantees parent updates always come + // before child updates. If the root is in the update, it is guaranteed to + // be the first node of the last list. + std::vector> results; + while (!pending_semantics_node_updates_.empty()) { + auto begin = pending_semantics_node_updates_.begin(); + SemanticsNode target = begin->second; + std::vector sub_tree_list; + GetSubTreeList(target, sub_tree_list); + results.push_back(sub_tree_list); + pending_semantics_node_updates_.erase(begin); + } + + for (size_t i = results.size(); i > 0; i--) { + for (const SemanticsNode& node : results[i - 1]) { + ConvertFlutterUpdate(node, update); + } + } + + // The first update must set the tree's root, which is guaranteed to be the + // last list's first node. A tree's root node never changes, though it can be + // modified. + if (!results.empty() && GetRootAsAXNode()->id() == ui::AXNode::kInvalidAXID) { + FML_DCHECK(!results.back().empty()); + + update.root_id = results.back().front().id; + } + + tree_->Unserialize(update); + pending_semantics_node_updates_.clear(); + pending_semantics_custom_action_updates_.clear(); + + std::string error = tree_->error(); + if (!error.empty()) { + FML_LOG(ERROR) << "Failed to update ui::AXTree, error: " << error; + return; + } + // Handles accessibility events as the result of the semantics update. + for (const auto& targeted_event : event_generator_) { + auto event_target = + GetFlutterPlatformNodeDelegateFromID(targeted_event.node->id()); + if (event_target.expired()) { + continue; + } + + OnAccessibilityEvent(targeted_event); + } + event_generator_.ClearEvents(); +} + +std::weak_ptr +AccessibilityBridge::GetFlutterPlatformNodeDelegateFromID( + AccessibilityNodeId id) const { + const auto iter = id_wrapper_map_.find(id); + if (iter != id_wrapper_map_.end()) { + return iter->second; + } + + return std::weak_ptr(); +} + +const ui::AXTreeData& AccessibilityBridge::GetAXTreeData() const { + return tree_->data(); +} + +const std::vector +AccessibilityBridge::GetPendingEvents() const { + std::vector result( + event_generator_.begin(), event_generator_.end()); + return result; +} + +void AccessibilityBridge::OnNodeWillBeDeleted(ui::AXTree* tree, + ui::AXNode* node) {} + +void AccessibilityBridge::OnSubtreeWillBeDeleted(ui::AXTree* tree, + ui::AXNode* node) {} + +void AccessibilityBridge::OnNodeReparented(ui::AXTree* tree, ui::AXNode* node) { +} + +void AccessibilityBridge::OnRoleChanged(ui::AXTree* tree, + ui::AXNode* node, + ax::mojom::Role old_role, + ax::mojom::Role new_role) {} + +void AccessibilityBridge::OnNodeDataChanged( + ui::AXTree* tree, + const ui::AXNodeData& old_node_data, + const ui::AXNodeData& new_node_data) { + auto platform_view = + GetFlutterPlatformNodeDelegateFromID(new_node_data.id).lock(); + if (platform_view) { + platform_view->NodeDataChanged(old_node_data, new_node_data); + } +} + +void AccessibilityBridge::OnNodeCreated(ui::AXTree* tree, ui::AXNode* node) { + BASE_DCHECK(node); + id_wrapper_map_[node->id()] = CreateFlutterPlatformNodeDelegate(); + id_wrapper_map_[node->id()]->Init( + std::static_pointer_cast( + shared_from_this()), + node); +} + +void AccessibilityBridge::OnNodeDeleted(ui::AXTree* tree, + AccessibilityNodeId node_id) { + BASE_DCHECK(node_id != ui::AXNode::kInvalidAXID); + if (id_wrapper_map_.find(node_id) != id_wrapper_map_.end()) { + id_wrapper_map_.erase(node_id); + } +} + +void AccessibilityBridge::OnAtomicUpdateFinished( + ui::AXTree* tree, + bool root_changed, + const std::vector& changes) { + // The Flutter semantics update does not include child->parent relationship + // We have to update the relative bound offset container id here in order + // to calculate the screen bound correctly. + for (const auto& change : changes) { + ui::AXNode* node = change.node; + const ui::AXNodeData& data = node->data(); + AccessibilityNodeId offset_container_id = -1; + if (node->parent()) { + offset_container_id = node->parent()->id(); + } + node->SetLocation(offset_container_id, data.relative_bounds.bounds, + data.relative_bounds.transform.get()); + } +} + +std::optional +AccessibilityBridge::CreateRemoveReparentedNodesUpdate() { + std::unordered_map updates; + + for (const auto& node_update : pending_semantics_node_updates_) { + for (int32_t child_id : node_update.second.children_in_traversal_order) { + // Skip nodes that don't exist or have a parent in the current tree. + ui::AXNode* child = tree_->GetFromId(child_id); + if (!child) { + continue; + } + + // Flutter's root node should never be reparented. + assert(child->parent()); + + // Skip nodes whose parents are unchanged. + if (child->parent()->id() == node_update.second.id) { + continue; + } + + // This pending update moves the current child node. + // That new child must have a corresponding pending update. + assert(pending_semantics_node_updates_.find(child_id) != + pending_semantics_node_updates_.end()); + + // Create an update to remove the child from its previous parent. + int32_t parent_id = child->parent()->id(); + if (updates.find(parent_id) == updates.end()) { + updates[parent_id] = tree_->GetFromId(parent_id)->data(); + } + + ui::AXNodeData* parent = &updates[parent_id]; + auto iter = std::find(parent->child_ids.begin(), parent->child_ids.end(), + child_id); + + assert(iter != parent->child_ids.end()); + parent->child_ids.erase(iter); + } + } + + if (updates.empty()) { + return std::nullopt; + } + + ui::AXTreeUpdate update{ + .tree_data = tree_->data(), + .nodes = std::vector(), + }; + + for (std::pair data : updates) { + update.nodes.push_back(std::move(data.second)); + } + + return update; +} + +// Private method. +void AccessibilityBridge::GetSubTreeList(const SemanticsNode& target, + std::vector& result) { + result.push_back(target); + for (int32_t child : target.children_in_traversal_order) { + auto iter = pending_semantics_node_updates_.find(child); + if (iter != pending_semantics_node_updates_.end()) { + SemanticsNode node = iter->second; + GetSubTreeList(node, result); + pending_semantics_node_updates_.erase(iter); + } + } +} + +void AccessibilityBridge::ConvertFlutterUpdate(const SemanticsNode& node, + ui::AXTreeUpdate& tree_update) { + ui::AXNodeData node_data; + node_data.id = node.id; + SetRoleFromFlutterUpdate(node_data, node); + SetStateFromFlutterUpdate(node_data, node); + SetActionsFromFlutterUpdate(node_data, node); + SetBooleanAttributesFromFlutterUpdate(node_data, node); + SetIntAttributesFromFlutterUpdate(node_data, node); + SetIntListAttributesFromFlutterUpdate(node_data, node); + SetStringListAttributesFromFlutterUpdate(node_data, node); + SetNameFromFlutterUpdate(node_data, node); + SetValueFromFlutterUpdate(node_data, node); + SetTooltipFromFlutterUpdate(node_data, node); + node_data.relative_bounds.bounds.SetRect(node.rect.left, node.rect.top, + node.rect.right - node.rect.left, + node.rect.bottom - node.rect.top); + node_data.relative_bounds.transform = std::make_unique( + node.transform.scaleX, node.transform.skewX, node.transform.transX, 0, + node.transform.skewY, node.transform.scaleY, node.transform.transY, 0, + node.transform.pers0, node.transform.pers1, node.transform.pers2, 0, 0, 0, + 0, 0); + for (auto child : node.children_in_traversal_order) { + node_data.child_ids.push_back(child); + } + SetTreeData(node, tree_update); + tree_update.nodes.push_back(node_data); +} + +void AccessibilityBridge::SetRoleFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node) { + FlutterSemanticsFlag flags = node.flags; + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsButton) { + node_data.role = ax::mojom::Role::kButton; + return; + } + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && + !(flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly)) { + node_data.role = ax::mojom::Role::kTextField; + return; + } + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsHeader) { + node_data.role = ax::mojom::Role::kHeader; + return; + } + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsImage) { + node_data.role = ax::mojom::Role::kImage; + return; + } + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsLink) { + node_data.role = ax::mojom::Role::kLink; + return; + } + + if (flags & kFlutterSemanticsFlagIsInMutuallyExclusiveGroup && + flags & kFlutterSemanticsFlagHasCheckedState) { + node_data.role = ax::mojom::Role::kRadioButton; + return; + } + if (flags & kFlutterSemanticsFlagHasCheckedState) { + node_data.role = ax::mojom::Role::kCheckBox; + return; + } + if (flags & kFlutterSemanticsFlagHasToggledState) { + node_data.role = ax::mojom::Role::kSwitch; + return; + } + if (flags & kFlutterSemanticsFlagIsSlider) { + node_data.role = ax::mojom::Role::kSlider; + return; + } + // If the state cannot be derived from the flutter flags, we fallback to group + // or static text. + if (node.children_in_traversal_order.empty()) { + node_data.role = ax::mojom::Role::kStaticText; + } else { + node_data.role = ax::mojom::Role::kGroup; + } +} + +void AccessibilityBridge::SetStateFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node) { + FlutterSemanticsFlag flags = node.flags; + FlutterSemanticsAction actions = node.actions; + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagHasExpandedState && + flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsExpanded) { + node_data.AddState(ax::mojom::State::kExpanded); + } else if (flags & + FlutterSemanticsFlag::kFlutterSemanticsFlagHasExpandedState) { + node_data.AddState(ax::mojom::State::kCollapsed); + } + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && + (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly) == 0) { + node_data.AddState(ax::mojom::State::kEditable); + } + if (node_data.role == ax::mojom::Role::kStaticText && + (actions & kHasScrollingAction) == 0 && node.value.empty() && + node.label.empty() && node.hint.empty()) { + node_data.AddState(ax::mojom::State::kIgnored); + } else { + // kFlutterSemanticsFlagIsFocusable means a keyboard focusable, it is + // different from semantics focusable. + // TODO(chunhtai): figure out whether something is not semantics focusable. + node_data.AddState(ax::mojom::State::kFocusable); + } +} + +void AccessibilityBridge::SetActionsFromFlutterUpdate( + ui::AXNodeData& node_data, + const SemanticsNode& node) { + FlutterSemanticsAction actions = node.actions; + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionTap) { + node_data.AddAction(ax::mojom::Action::kDoDefault); + } + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionScrollLeft) { + node_data.AddAction(ax::mojom::Action::kScrollLeft); + } + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionScrollRight) { + node_data.AddAction(ax::mojom::Action::kScrollRight); + } + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionScrollUp) { + node_data.AddAction(ax::mojom::Action::kScrollUp); + } + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionScrollDown) { + node_data.AddAction(ax::mojom::Action::kScrollDown); + } + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionIncrease) { + node_data.AddAction(ax::mojom::Action::kIncrement); + } + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionDecrease) { + node_data.AddAction(ax::mojom::Action::kDecrement); + } + // Every node has show on screen action. + node_data.AddAction(ax::mojom::Action::kScrollToMakeVisible); + + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionSetSelection) { + node_data.AddAction(ax::mojom::Action::kSetSelection); + } + if (actions & FlutterSemanticsAction:: + kFlutterSemanticsActionDidGainAccessibilityFocus) { + node_data.AddAction(ax::mojom::Action::kSetAccessibilityFocus); + } + if (actions & FlutterSemanticsAction:: + kFlutterSemanticsActionDidLoseAccessibilityFocus) { + node_data.AddAction(ax::mojom::Action::kClearAccessibilityFocus); + } + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionCustomAction) { + node_data.AddAction(ax::mojom::Action::kCustomAction); + } +} + +void AccessibilityBridge::SetBooleanAttributesFromFlutterUpdate( + ui::AXNodeData& node_data, + const SemanticsNode& node) { + FlutterSemanticsAction actions = node.actions; + FlutterSemanticsFlag flags = node.flags; + node_data.AddBoolAttribute(ax::mojom::BoolAttribute::kScrollable, + actions & kHasScrollingAction); + node_data.AddBoolAttribute( + ax::mojom::BoolAttribute::kClickable, + actions & FlutterSemanticsAction::kFlutterSemanticsActionTap); + // TODO(chunhtai): figure out if there is a node that does not clip overflow. + node_data.AddBoolAttribute(ax::mojom::BoolAttribute::kClipsChildren, + !node.children_in_traversal_order.empty()); + node_data.AddBoolAttribute( + ax::mojom::BoolAttribute::kSelected, + flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsSelected); + node_data.AddBoolAttribute( + ax::mojom::BoolAttribute::kEditableRoot, + flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && + (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly) == 0); + // Mark nodes as line breaking so that screen readers don't + // merge all consecutive objects into one. + // TODO(schectman): When should a node have this attribute set? + // https://github.com/flutter/flutter/issues/118184 + node_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject, + true); +} + +void AccessibilityBridge::SetIntAttributesFromFlutterUpdate( + ui::AXNodeData& node_data, + const SemanticsNode& node) { + FlutterSemanticsFlag flags = node.flags; + node_data.AddIntAttribute(ax::mojom::IntAttribute::kTextDirection, + node.text_direction); + + int sel_start = node.text_selection_base; + int sel_end = node.text_selection_extent; + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && + (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly) == 0 && + !node.value.empty()) { + // By default the text field selection should be at the end. + sel_start = sel_start == -1 ? node.value.length() : sel_start; + sel_end = sel_end == -1 ? node.value.length() : sel_end; + } + node_data.AddIntAttribute(ax::mojom::IntAttribute::kTextSelStart, sel_start); + node_data.AddIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, sel_end); + + if (node_data.role == ax::mojom::Role::kRadioButton || + node_data.role == ax::mojom::Role::kCheckBox) { + node_data.AddIntAttribute( + ax::mojom::IntAttribute::kCheckedState, + static_cast( + flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsCheckStateMixed + ? ax::mojom::CheckedState::kMixed + : flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsChecked + ? ax::mojom::CheckedState::kTrue + : ax::mojom::CheckedState::kFalse)); + } else if (node_data.role == ax::mojom::Role::kSwitch) { + node_data.AddIntAttribute( + ax::mojom::IntAttribute::kCheckedState, + static_cast( + flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsToggled + ? ax::mojom::CheckedState::kTrue + : ax::mojom::CheckedState::kFalse)); + } +} + +void AccessibilityBridge::SetIntListAttributesFromFlutterUpdate( + ui::AXNodeData& node_data, + const SemanticsNode& node) { + FlutterSemanticsAction actions = node.actions; + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionCustomAction) { + std::vector custom_action_ids; + for (size_t i = 0; i < node.custom_accessibility_actions.size(); i++) { + custom_action_ids.push_back(node.custom_accessibility_actions[i]); + } + node_data.AddIntListAttribute(ax::mojom::IntListAttribute::kCustomActionIds, + custom_action_ids); + } +} + +void AccessibilityBridge::SetStringListAttributesFromFlutterUpdate( + ui::AXNodeData& node_data, + const SemanticsNode& node) { + FlutterSemanticsAction actions = node.actions; + if (actions & FlutterSemanticsAction::kFlutterSemanticsActionCustomAction) { + std::vector custom_action_description; + for (size_t i = 0; i < node.custom_accessibility_actions.size(); i++) { + auto iter = pending_semantics_custom_action_updates_.find( + node.custom_accessibility_actions[i]); + BASE_DCHECK(iter != pending_semantics_custom_action_updates_.end()); + custom_action_description.push_back(iter->second.label); + } + node_data.AddStringListAttribute( + ax::mojom::StringListAttribute::kCustomActionDescriptions, + custom_action_description); + } +} + +void AccessibilityBridge::SetNameFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node) { + node_data.SetName(node.label); +} + +void AccessibilityBridge::SetValueFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node) { + node_data.SetValue(node.value); +} + +void AccessibilityBridge::SetTooltipFromFlutterUpdate( + ui::AXNodeData& node_data, + const SemanticsNode& node) { + node_data.SetTooltip(node.tooltip); +} + +void AccessibilityBridge::SetTreeData(const SemanticsNode& node, + ui::AXTreeUpdate& tree_update) { + FlutterSemanticsFlag flags = node.flags; + // Set selection of the focused node if: + // 1. this text field has a valid selection + // 2. this text field doesn't have a valid selection but had selection stored + // in the tree. + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && + flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocused) { + if (node.text_selection_base != -1) { + tree_update.tree_data.sel_anchor_object_id = node.id; + tree_update.tree_data.sel_anchor_offset = node.text_selection_base; + tree_update.tree_data.sel_focus_object_id = node.id; + tree_update.tree_data.sel_focus_offset = node.text_selection_extent; + tree_update.has_tree_data = true; + } else if (tree_update.tree_data.sel_anchor_object_id == node.id) { + tree_update.tree_data.sel_anchor_object_id = ui::AXNode::kInvalidAXID; + tree_update.tree_data.sel_anchor_offset = -1; + tree_update.tree_data.sel_focus_object_id = ui::AXNode::kInvalidAXID; + tree_update.tree_data.sel_focus_offset = -1; + tree_update.has_tree_data = true; + } + } + + if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocused && + tree_update.tree_data.focus_id != node.id) { + tree_update.tree_data.focus_id = node.id; + tree_update.has_tree_data = true; + } else if ((flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocused) == + 0 && + tree_update.tree_data.focus_id == node.id) { + tree_update.tree_data.focus_id = ui::AXNode::kInvalidAXID; + tree_update.has_tree_data = true; + } +} + +AccessibilityBridge::SemanticsNode +AccessibilityBridge::FromFlutterSemanticsNode( + const FlutterSemanticsNode2& flutter_node) { + SemanticsNode result; + result.id = flutter_node.id; + result.flags = flutter_node.flags; + result.actions = flutter_node.actions; + result.text_selection_base = flutter_node.text_selection_base; + result.text_selection_extent = flutter_node.text_selection_extent; + result.scroll_child_count = flutter_node.scroll_child_count; + result.scroll_index = flutter_node.scroll_index; + result.scroll_position = flutter_node.scroll_position; + result.scroll_extent_max = flutter_node.scroll_extent_max; + result.scroll_extent_min = flutter_node.scroll_extent_min; + result.elevation = flutter_node.elevation; + result.thickness = flutter_node.thickness; + if (flutter_node.label) { + result.label = std::string(flutter_node.label); + } + if (flutter_node.hint) { + result.hint = std::string(flutter_node.hint); + } + if (flutter_node.value) { + result.value = std::string(flutter_node.value); + } + if (flutter_node.increased_value) { + result.increased_value = std::string(flutter_node.increased_value); + } + if (flutter_node.decreased_value) { + result.decreased_value = std::string(flutter_node.decreased_value); + } + if (flutter_node.tooltip) { + result.tooltip = std::string(flutter_node.tooltip); + } + result.text_direction = flutter_node.text_direction; + result.rect = flutter_node.rect; + result.transform = flutter_node.transform; + if (flutter_node.child_count > 0) { + result.children_in_traversal_order = std::vector( + flutter_node.children_in_traversal_order, + flutter_node.children_in_traversal_order + flutter_node.child_count); + } + if (flutter_node.custom_accessibility_actions_count > 0) { + result.custom_accessibility_actions = std::vector( + flutter_node.custom_accessibility_actions, + flutter_node.custom_accessibility_actions + + flutter_node.custom_accessibility_actions_count); + } + return result; +} + +AccessibilityBridge::SemanticsCustomAction +AccessibilityBridge::FromFlutterSemanticsCustomAction( + const FlutterSemanticsCustomAction2& flutter_custom_action) { + SemanticsCustomAction result; + result.id = flutter_custom_action.id; + result.override_action = flutter_custom_action.override_action; + if (flutter_custom_action.label) { + result.label = std::string(flutter_custom_action.label); + } + if (flutter_custom_action.hint) { + result.hint = std::string(flutter_custom_action.hint); + } + return result; +} + +void AccessibilityBridge::SetLastFocusedId(AccessibilityNodeId node_id) { + if (last_focused_id_ != node_id) { + auto last_focused_child = + GetFlutterPlatformNodeDelegateFromID(last_focused_id_); + if (!last_focused_child.expired()) { + DispatchAccessibilityAction( + last_focused_id_, + FlutterSemanticsAction:: + kFlutterSemanticsActionDidLoseAccessibilityFocus, + {}); + } + last_focused_id_ = node_id; + } +} + +AccessibilityNodeId AccessibilityBridge::GetLastFocusedId() { + return last_focused_id_; +} + +gfx::NativeViewAccessible AccessibilityBridge::GetNativeAccessibleFromId( + AccessibilityNodeId id) { + auto platform_node_delegate = GetFlutterPlatformNodeDelegateFromID(id).lock(); + if (!platform_node_delegate) { + return nullptr; + } + return platform_node_delegate->GetNativeViewAccessible(); +} + +gfx::RectF AccessibilityBridge::RelativeToGlobalBounds(const ui::AXNode* node, + bool& offscreen, + bool clip_bounds) { + return tree_->RelativeToTreeBounds(node, gfx::RectF(), &offscreen, + clip_bounds); +} + +ui::AXNode* AccessibilityBridge::GetNodeFromTree( + ui::AXTreeID tree_id, + ui::AXNode::AXID node_id) const { + return GetNodeFromTree(node_id); +} + +ui::AXNode* AccessibilityBridge::GetNodeFromTree( + ui::AXNode::AXID node_id) const { + return tree_->GetFromId(node_id); +} + +ui::AXTreeID AccessibilityBridge::GetTreeID() const { + return tree_->GetAXTreeID(); +} + +ui::AXTreeID AccessibilityBridge::GetParentTreeID() const { + return ui::AXTreeIDUnknown(); +} + +ui::AXNode* AccessibilityBridge::GetRootAsAXNode() const { + return tree_->root(); +} + +ui::AXNode* AccessibilityBridge::GetParentNodeFromParentTreeAsAXNode() const { + return nullptr; +} + +ui::AXTree* AccessibilityBridge::GetTree() const { + return tree_.get(); +} + +ui::AXPlatformNode* AccessibilityBridge::GetPlatformNodeFromTree( + const ui::AXNode::AXID node_id) const { + auto platform_delegate_weak = GetFlutterPlatformNodeDelegateFromID(node_id); + auto platform_delegate = platform_delegate_weak.lock(); + if (!platform_delegate) { + return nullptr; + } + return platform_delegate->GetPlatformNode(); +} + +ui::AXPlatformNode* AccessibilityBridge::GetPlatformNodeFromTree( + const ui::AXNode& node) const { + return GetPlatformNodeFromTree(node.id()); +} + +ui::AXPlatformNodeDelegate* AccessibilityBridge::RootDelegate() const { + return GetFlutterPlatformNodeDelegateFromID(GetRootAsAXNode()->id()) + .lock() + .get(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/accessibility_bridge.h b/flutter/engine/src/flutter/shell/platform/common/accessibility_bridge.h new file mode 100644 index 0000000000000000000000000000000000000000..8126c1ce7b65a5559931db3d1365eab0facaec59 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/accessibility_bridge.h @@ -0,0 +1,294 @@ +// 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_COMMON_ACCESSIBILITY_BRIDGE_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_ACCESSIBILITY_BRIDGE_H_ + +#include + +#include "flutter/fml/mapping.h" +#include "flutter/shell/platform/embedder/embedder.h" + +#include "flutter/third_party/accessibility/ax/ax_event_generator.h" +#include "flutter/third_party/accessibility/ax/ax_tree.h" +#include "flutter/third_party/accessibility/ax/ax_tree_observer.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_tree_manager.h" + +#include "flutter_platform_node_delegate.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// Use this class to maintain an accessibility tree. This class consumes +/// semantics updates from the embedder API and produces an accessibility tree +/// in the native format. +/// +/// The bridge creates an AXTree to hold the semantics data that comes from +/// Flutter semantics updates. The tree holds AXNode[s] which contain the +/// semantics information for semantics node. The AXTree resemble the Flutter +/// semantics tree in the Flutter framework. The bridge also uses +/// FlutterPlatformNodeDelegate to wrap each AXNode in order to provide +/// an accessibility tree in the native format. +/// +/// To use this class, one must subclass this class and provide their own +/// implementation of FlutterPlatformNodeDelegate. +/// +/// AccessibilityBridge must be created as a shared_ptr, since some methods +/// acquires its weak_ptr. +class AccessibilityBridge + : public std::enable_shared_from_this, + public FlutterPlatformNodeDelegate::OwnerBridge, + public ui::AXPlatformTreeManager, + private ui::AXTreeObserver { + public: + //----------------------------------------------------------------------------- + /// @brief Creates a new instance of a accessibility bridge. + AccessibilityBridge(); + virtual ~AccessibilityBridge(); + + //------------------------------------------------------------------------------ + /// @brief Adds a semantics node update to the pending semantics update. + /// Calling this method alone will NOT update the semantics tree. + /// To flush the pending updates, call the CommitUpdates(). + /// + /// @param[in] node A reference to the semantics node update. + void AddFlutterSemanticsNodeUpdate(const FlutterSemanticsNode2& node); + + //------------------------------------------------------------------------------ + /// @brief Adds a custom semantics action update to the pending semantics + /// update. Calling this method alone will NOT update the + /// semantics tree. To flush the pending updates, call the + /// CommitUpdates(). + /// + /// @param[in] action A reference to the custom semantics action + /// update. + void AddFlutterSemanticsCustomActionUpdate( + const FlutterSemanticsCustomAction2& action); + + //------------------------------------------------------------------------------ + /// @brief Flushes the pending updates and applies them to this + /// accessibility bridge. Calling this with no pending updates + /// does nothing, and callers should call this method at the end + /// of an atomic batch to avoid leaving the tree in a unstable + /// state. For example if a node reparents from A to B, callers + /// should only call this method when both removal from A and + /// addition to B are in the pending updates. + void CommitUpdates(); + + //------------------------------------------------------------------------------ + /// @brief Get the flutter platform node delegate with the given id from + /// this accessibility bridge. Returns expired weak_ptr if the + /// delegate associated with the id does not exist or has been + /// removed from the accessibility tree. + /// + /// @param[in] id The id of the flutter accessibility node you want + /// to retrieve. + std::weak_ptr + GetFlutterPlatformNodeDelegateFromID(AccessibilityNodeId id) const; + + //------------------------------------------------------------------------------ + /// @brief Get the ax tree data from this accessibility bridge. The tree + /// data contains information such as the id of the node that + /// has the keyboard focus or the text selection range. + const ui::AXTreeData& GetAXTreeData() const; + + //------------------------------------------------------------------------------ + /// @brief Gets all pending accessibility events generated during + /// semantics updates. This is useful when deciding how to handle + /// events in AccessibilityBridgeDelegate::OnAccessibilityEvent in + /// case one may decide to handle an event differently based on + /// all pending events. + const std::vector GetPendingEvents() + const; + + // |AXTreeManager| + ui::AXNode* GetNodeFromTree(const ui::AXTreeID tree_id, + const ui::AXNode::AXID node_id) const override; + + // |AXTreeManager| + ui::AXNode* GetNodeFromTree(const ui::AXNode::AXID node_id) const override; + + // |AXTreeManager| + ui::AXTreeID GetTreeID() const override; + + // |AXTreeManager| + ui::AXTreeID GetParentTreeID() const override; + + // |AXTreeManager| + ui::AXNode* GetRootAsAXNode() const override; + + // |AXTreeManager| + ui::AXNode* GetParentNodeFromParentTreeAsAXNode() const override; + + // |AXTreeManager| + ui::AXTree* GetTree() const override; + + // |AXPlatformTreeManager| + ui::AXPlatformNode* GetPlatformNodeFromTree( + const ui::AXNode::AXID node_id) const override; + + // |AXPlatformTreeManager| + ui::AXPlatformNode* GetPlatformNodeFromTree( + const ui::AXNode& node) const override; + + // |AXPlatformTreeManager| + ui::AXPlatformNodeDelegate* RootDelegate() const override; + + protected: + //--------------------------------------------------------------------------- + /// @brief Handle accessibility events generated due to accessibility + /// tree changes. These events are needed to be sent to native + /// accessibility system. See ui::AXEventGenerator::Event for + /// possible events. + /// + /// @param[in] targeted_event The object that contains both the + /// generated event and the event target. + virtual void OnAccessibilityEvent( + ui::AXEventGenerator::TargetedEvent targeted_event) = 0; + + //--------------------------------------------------------------------------- + /// @brief Creates a platform specific FlutterPlatformNodeDelegate. + /// Ownership passes to the caller. This method will be called + /// whenever a new AXNode is created in AXTree. Each platform + /// needs to implement this method in order to inject its + /// subclass into the accessibility bridge. + virtual std::shared_ptr + CreateFlutterPlatformNodeDelegate() = 0; + + private: + // See FlutterSemanticsNode in embedder.h + typedef struct { + int32_t id; + FlutterSemanticsFlag flags; + FlutterSemanticsAction actions; + int32_t text_selection_base; + int32_t text_selection_extent; + int32_t scroll_child_count; + int32_t scroll_index; + double scroll_position; + double scroll_extent_max; + double scroll_extent_min; + double elevation; + double thickness; + std::string label; + std::string hint; + std::string value; + std::string increased_value; + std::string decreased_value; + std::string tooltip; + FlutterTextDirection text_direction; + FlutterRect rect; + FlutterTransformation transform; + std::vector children_in_traversal_order; + std::vector custom_accessibility_actions; + } SemanticsNode; + + // See FlutterSemanticsCustomAction in embedder.h + typedef struct { + int32_t id; + FlutterSemanticsAction override_action; + std::string label; + std::string hint; + } SemanticsCustomAction; + + std::unordered_map> + id_wrapper_map_; + std::unique_ptr tree_; + ui::AXEventGenerator event_generator_; + std::unordered_map pending_semantics_node_updates_; + std::unordered_map + pending_semantics_custom_action_updates_; + AccessibilityNodeId last_focused_id_ = ui::AXNode::kInvalidAXID; + + void InitAXTree(const ui::AXTreeUpdate& initial_state); + + // Create an update that removes any nodes that will be reparented by + // pending_semantics_updates_. Returns std::nullopt if none are reparented. + std::optional CreateRemoveReparentedNodesUpdate(); + + void GetSubTreeList(const SemanticsNode& target, + std::vector& result); + void ConvertFlutterUpdate(const SemanticsNode& node, + ui::AXTreeUpdate& tree_update); + void SetRoleFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetStateFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetActionsFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetBooleanAttributesFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetIntAttributesFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetIntListAttributesFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetStringListAttributesFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetNameFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetValueFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetTooltipFromFlutterUpdate(ui::AXNodeData& node_data, + const SemanticsNode& node); + void SetTreeData(const SemanticsNode& node, ui::AXTreeUpdate& tree_update); + SemanticsNode FromFlutterSemanticsNode( + const FlutterSemanticsNode2& flutter_node); + SemanticsCustomAction FromFlutterSemanticsCustomAction( + const FlutterSemanticsCustomAction2& flutter_custom_action); + + // |AXTreeObserver| + void OnNodeWillBeDeleted(ui::AXTree* tree, ui::AXNode* node) override; + + // |AXTreeObserver| + void OnSubtreeWillBeDeleted(ui::AXTree* tree, ui::AXNode* node) override; + + // |AXTreeObserver| + void OnNodeCreated(ui::AXTree* tree, ui::AXNode* node) override; + + // |AXTreeObserver| + void OnNodeDeleted(ui::AXTree* tree, AccessibilityNodeId node_id) override; + + // |AXTreeObserver| + void OnNodeReparented(ui::AXTree* tree, ui::AXNode* node) override; + + // |AXTreeObserver| + void OnRoleChanged(ui::AXTree* tree, + ui::AXNode* node, + ax::mojom::Role old_role, + ax::mojom::Role new_role) override; + + // |AXTreeObserver| + void OnNodeDataChanged(ui::AXTree* tree, + const ui::AXNodeData& old_node_data, + const ui::AXNodeData& new_node_data) override; + + // |AXTreeObserver| + void OnAtomicUpdateFinished( + ui::AXTree* tree, + bool root_changed, + const std::vector& changes) override; + + // |FlutterPlatformNodeDelegate::OwnerBridge| + void SetLastFocusedId(AccessibilityNodeId node_id) override; + + // |FlutterPlatformNodeDelegate::OwnerBridge| + AccessibilityNodeId GetLastFocusedId() override; + + // |FlutterPlatformNodeDelegate::OwnerBridge| + gfx::NativeViewAccessible GetNativeAccessibleFromId( + AccessibilityNodeId id) override; + + // |FlutterPlatformNodeDelegate::OwnerBridge| + gfx::RectF RelativeToGlobalBounds(const ui::AXNode* node, + bool& offscreen, + bool clip_bounds) override; + + BASE_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_ACCESSIBILITY_BRIDGE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/accessibility_bridge_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/accessibility_bridge_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..796670e3ab9b085f9b010ebc6dd8ec8fff2b9f6d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/accessibility_bridge_unittests.cc @@ -0,0 +1,576 @@ +// 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 "accessibility_bridge.h" + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include "flutter/third_party/accessibility/ax/ax_tree_manager_map.h" +#include "test_accessibility_bridge.h" + +namespace flutter { +namespace testing { + +using ::testing::Contains; + +FlutterSemanticsNode2 CreateSemanticsNode( + int32_t id, + const char* label, + const std::vector* children = nullptr) { + return { + .id = id, + .flags = static_cast(0), + .actions = static_cast(0), + .text_selection_base = -1, + .text_selection_extent = -1, + .label = label, + .hint = "", + .value = "", + .increased_value = "", + .decreased_value = "", + .child_count = children ? children->size() : 0, + .children_in_traversal_order = children ? children->data() : nullptr, + .custom_accessibility_actions_count = 0, + .tooltip = "", + }; +} + +TEST(AccessibilityBridgeTest, BasicTest) { + std::shared_ptr bridge = + std::make_shared(); + + std::vector children{1, 2}; + FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root", &children); + FlutterSemanticsNode2 child1 = CreateSemanticsNode(1, "child 1"); + FlutterSemanticsNode2 child2 = CreateSemanticsNode(2, "child 2"); + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(child1); + bridge->AddFlutterSemanticsNodeUpdate(child2); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + auto child2_node = bridge->GetFlutterPlatformNodeDelegateFromID(2).lock(); + EXPECT_EQ(root_node->GetChildCount(), 2); + EXPECT_EQ(root_node->GetData().child_ids[0], 1); + EXPECT_EQ(root_node->GetData().child_ids[1], 2); + EXPECT_EQ(root_node->GetName(), "root"); + + EXPECT_EQ(child1_node->GetChildCount(), 0); + EXPECT_EQ(child1_node->GetName(), "child 1"); + + EXPECT_EQ(child2_node->GetChildCount(), 0); + EXPECT_EQ(child2_node->GetName(), "child 2"); +} + +// Flutter used to assume that the accessibility root had ID 0. +// In a multi-view world, each view has its own accessibility root +// with a globally unique node ID. +TEST(AccessibilityBridgeTest, AccessibilityRootId) { + std::shared_ptr bridge = + std::make_shared(); + + std::vector children{456, 789}; + FlutterSemanticsNode2 root = CreateSemanticsNode(123, "root", &children); + FlutterSemanticsNode2 child1 = CreateSemanticsNode(456, "child 1"); + FlutterSemanticsNode2 child2 = CreateSemanticsNode(789, "child 2"); + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(child1); + bridge->AddFlutterSemanticsNodeUpdate(child2); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(123).lock(); + auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(456).lock(); + auto child2_node = bridge->GetFlutterPlatformNodeDelegateFromID(789).lock(); + auto fake_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + + EXPECT_EQ(bridge->GetRootAsAXNode()->id(), 123); + EXPECT_EQ(bridge->RootDelegate()->GetName(), "root"); + + EXPECT_EQ(root_node->GetChildCount(), 2); + EXPECT_EQ(root_node->GetData().child_ids[0], 456); + EXPECT_EQ(root_node->GetData().child_ids[1], 789); + EXPECT_EQ(root_node->GetName(), "root"); + + EXPECT_EQ(child1_node->GetChildCount(), 0); + EXPECT_EQ(child1_node->GetName(), "child 1"); + + EXPECT_EQ(child2_node->GetChildCount(), 0); + EXPECT_EQ(child2_node->GetName(), "child 2"); + + ASSERT_FALSE(fake_delegate); +} + +// Semantic nodes can be added in any order. +TEST(AccessibilityBridgeTest, AddOrder) { + std::shared_ptr bridge = + std::make_shared(); + + std::vector root_children{34, 56}; + std::vector child2_children{78}; + std::vector child3_children{90}; + FlutterSemanticsNode2 root = CreateSemanticsNode(12, "root", &root_children); + FlutterSemanticsNode2 child1 = CreateSemanticsNode(34, "child 1"); + FlutterSemanticsNode2 child2 = + CreateSemanticsNode(56, "child 2", &child2_children); + FlutterSemanticsNode2 child3 = + CreateSemanticsNode(78, "child 3", &child3_children); + FlutterSemanticsNode2 child4 = CreateSemanticsNode(90, "child 4"); + + bridge->AddFlutterSemanticsNodeUpdate(child3); + bridge->AddFlutterSemanticsNodeUpdate(child2); + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(child1); + bridge->AddFlutterSemanticsNodeUpdate(child4); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(12).lock(); + auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(34).lock(); + auto child2_node = bridge->GetFlutterPlatformNodeDelegateFromID(56).lock(); + auto child3_node = bridge->GetFlutterPlatformNodeDelegateFromID(78).lock(); + auto child4_node = bridge->GetFlutterPlatformNodeDelegateFromID(90).lock(); + + EXPECT_EQ(bridge->GetRootAsAXNode()->id(), 12); + EXPECT_EQ(bridge->RootDelegate()->GetName(), "root"); + + EXPECT_EQ(root_node->GetChildCount(), 2); + EXPECT_EQ(root_node->GetData().child_ids[0], 34); + EXPECT_EQ(root_node->GetData().child_ids[1], 56); + EXPECT_EQ(root_node->GetName(), "root"); + + EXPECT_EQ(child1_node->GetChildCount(), 0); + EXPECT_EQ(child1_node->GetName(), "child 1"); + + EXPECT_EQ(child2_node->GetChildCount(), 1); + EXPECT_EQ(child2_node->GetData().child_ids[0], 78); + EXPECT_EQ(child2_node->GetName(), "child 2"); + + EXPECT_EQ(child3_node->GetChildCount(), 1); + EXPECT_EQ(child3_node->GetData().child_ids[0], 90); + EXPECT_EQ(child3_node->GetName(), "child 3"); + + EXPECT_EQ(child4_node->GetChildCount(), 0); + EXPECT_EQ(child4_node->GetName(), "child 4"); +} + +TEST(AccessibilityBridgeTest, CanFireChildrenChangedCorrectly) { + std::shared_ptr bridge = + std::make_shared(); + + std::vector children{1}; + FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root", &children); + FlutterSemanticsNode2 child1 = CreateSemanticsNode(1, "child 1"); + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(child1); + + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + EXPECT_EQ(root_node->GetChildCount(), 1); + EXPECT_EQ(root_node->GetData().child_ids[0], 1); + EXPECT_EQ(root_node->GetName(), "root"); + + EXPECT_EQ(child1_node->GetChildCount(), 0); + EXPECT_EQ(child1_node->GetName(), "child 1"); + bridge->accessibility_events.clear(); + + // Add a child to root. + root.child_count = 2; + int32_t new_children[] = {1, 2}; + root.children_in_traversal_order = new_children; + + FlutterSemanticsNode2 child2 = CreateSemanticsNode(2, "child 2"); + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(child2); + bridge->CommitUpdates(); + + root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + + EXPECT_EQ(root_node->GetChildCount(), 2); + EXPECT_EQ(root_node->GetData().child_ids[0], 1); + EXPECT_EQ(root_node->GetData().child_ids[1], 2); + EXPECT_EQ(bridge->accessibility_events.size(), size_t{2}); + std::set actual_event{ + bridge->accessibility_events.begin(), bridge->accessibility_events.end()}; + EXPECT_THAT(actual_event, + Contains(ui::AXEventGenerator::Event::CHILDREN_CHANGED)); + EXPECT_THAT(actual_event, + Contains(ui::AXEventGenerator::Event::SUBTREE_CREATED)); +} + +TEST(AccessibilityBridgeTest, CanHandleSelectionChangeCorrectly) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); + root.flags = static_cast( + FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField | + FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocused); + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->CommitUpdates(); + + const ui::AXTreeData& tree = bridge->GetAXTreeData(); + EXPECT_EQ(tree.sel_anchor_object_id, ui::AXNode::kInvalidAXID); + bridge->accessibility_events.clear(); + + // Update the selection. + root.text_selection_base = 0; + root.text_selection_extent = 5; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + + EXPECT_EQ(tree.sel_anchor_object_id, 0); + EXPECT_EQ(tree.sel_anchor_offset, 0); + EXPECT_EQ(tree.sel_focus_object_id, 0); + EXPECT_EQ(tree.sel_focus_offset, 5); + ASSERT_EQ(bridge->accessibility_events.size(), size_t{2}); + EXPECT_EQ(bridge->accessibility_events[0], + ui::AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED); + EXPECT_EQ(bridge->accessibility_events[1], + ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED); +} + +TEST(AccessibilityBridgeTest, DoesNotAssignEditableRootToSelectableText) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); + root.flags = static_cast( + FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField | + FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly); + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + + EXPECT_FALSE(root_node->GetData().GetBoolAttribute( + ax::mojom::BoolAttribute::kEditableRoot)); +} + +TEST(AccessibilityBridgeTest, SwitchHasSwitchRole) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); + root.flags = static_cast( + FlutterSemanticsFlag::kFlutterSemanticsFlagHasToggledState | + FlutterSemanticsFlag::kFlutterSemanticsFlagHasEnabledState | + FlutterSemanticsFlag::kFlutterSemanticsFlagIsEnabled); + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kSwitch); +} + +TEST(AccessibilityBridgeTest, SliderHasSliderRole) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); + root.flags = static_cast( + FlutterSemanticsFlag::kFlutterSemanticsFlagIsSlider | + FlutterSemanticsFlag::kFlutterSemanticsFlagHasEnabledState | + FlutterSemanticsFlag::kFlutterSemanticsFlagIsEnabled | + FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocusable); + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kSlider); +} + +// Ensure that checkboxes have their checked status set apropriately +// Previously, only Radios could have this flag updated +// Resulted in the issue seen at +// https://github.com/flutter/flutter/issues/96218 +// As this fix involved code run on all platforms, it is included here. +TEST(AccessibilityBridgeTest, CanSetCheckboxChecked) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root"); + root.flags = static_cast( + FlutterSemanticsFlag::kFlutterSemanticsFlagHasCheckedState | + FlutterSemanticsFlag::kFlutterSemanticsFlagIsChecked); + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kCheckBox); + EXPECT_EQ(root_node->GetData().GetCheckedState(), + ax::mojom::CheckedState::kTrue); +} + +// Verify that a node can be moved from one parent to another. +TEST(AccessibilityBridgeTest, CanReparentNode) { + std::shared_ptr bridge = + std::make_shared(); + + std::vector root_children{1}; + std::vector child1_children{2}; + FlutterSemanticsNode2 root = CreateSemanticsNode(0, "root", &root_children); + FlutterSemanticsNode2 child1 = + CreateSemanticsNode(1, "child 1", &child1_children); + FlutterSemanticsNode2 child2 = CreateSemanticsNode(2, "child 2"); + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(child1); + bridge->AddFlutterSemanticsNodeUpdate(child2); + bridge->CommitUpdates(); + bridge->accessibility_events.clear(); + + // Reparent child2 from child1 to the root. + child1.child_count = 0; + child1.children_in_traversal_order = nullptr; + + int32_t new_root_children[] = {1, 2}; + root.child_count = 2; + root.children_in_traversal_order = new_root_children; + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(child1); + bridge->AddFlutterSemanticsNodeUpdate(child2); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + auto child2_node = bridge->GetFlutterPlatformNodeDelegateFromID(2).lock(); + + EXPECT_EQ(root_node->GetChildCount(), 2); + EXPECT_EQ(root_node->GetData().child_ids[0], 1); + EXPECT_EQ(root_node->GetData().child_ids[1], 2); + EXPECT_EQ(root_node->GetName(), "root"); + + EXPECT_EQ(child1_node->GetChildCount(), 0); + EXPECT_EQ(child1_node->GetName(), "child 1"); + + EXPECT_EQ(child2_node->GetChildCount(), 0); + EXPECT_EQ(child2_node->GetName(), "child 2"); + + ASSERT_EQ(bridge->accessibility_events.size(), size_t{5}); + + // Child2 is moved from child1 to root. + EXPECT_THAT(bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::CHILDREN_CHANGED).Times(2)); + EXPECT_THAT(bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::SUBTREE_CREATED).Times(1)); + + // Child1 is no longer a parent. It loses its group role and disables its + // 'clip children' attribute. + EXPECT_THAT( + bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED).Times(1)); + EXPECT_THAT(bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::ROLE_CHANGED).Times(1)); +} + +// Verify that multiple nodes can be moved to new parents. +TEST(AccessibilityBridgeTest, CanReparentMultipleNodes) { + std::shared_ptr bridge = + std::make_shared(); + + int32_t root_id = 0; + int32_t intermediary1_id = 1; + int32_t intermediary2_id = 2; + int32_t leaf1_id = 3; + int32_t leaf2_id = 4; + int32_t leaf3_id = 5; + + std::vector root_children{intermediary1_id, intermediary2_id}; + std::vector intermediary1_children{leaf1_id}; + std::vector intermediary2_children{leaf2_id, leaf3_id}; + FlutterSemanticsNode2 root = + CreateSemanticsNode(root_id, "root", &root_children); + FlutterSemanticsNode2 intermediary1 = CreateSemanticsNode( + intermediary1_id, "intermediary 1", &intermediary1_children); + FlutterSemanticsNode2 intermediary2 = CreateSemanticsNode( + intermediary2_id, "intermediary 2", &intermediary2_children); + FlutterSemanticsNode2 leaf1 = CreateSemanticsNode(leaf1_id, "leaf 1"); + FlutterSemanticsNode2 leaf2 = CreateSemanticsNode(leaf2_id, "leaf 2"); + FlutterSemanticsNode2 leaf3 = CreateSemanticsNode(leaf3_id, "leaf 3"); + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(intermediary1); + bridge->AddFlutterSemanticsNodeUpdate(intermediary2); + bridge->AddFlutterSemanticsNodeUpdate(leaf1); + bridge->AddFlutterSemanticsNodeUpdate(leaf2); + bridge->AddFlutterSemanticsNodeUpdate(leaf3); + bridge->CommitUpdates(); + bridge->accessibility_events.clear(); + + // Swap intermediary 1's and intermediary2's children. + int32_t new_intermediary1_children[] = {leaf2_id, leaf3_id}; + intermediary1.child_count = 2; + intermediary1.children_in_traversal_order = new_intermediary1_children; + + int32_t new_intermediary2_children[] = {leaf1_id}; + intermediary2.child_count = 1; + intermediary2.children_in_traversal_order = new_intermediary2_children; + + bridge->AddFlutterSemanticsNodeUpdate(intermediary1); + bridge->AddFlutterSemanticsNodeUpdate(intermediary2); + bridge->AddFlutterSemanticsNodeUpdate(leaf1); + bridge->AddFlutterSemanticsNodeUpdate(leaf2); + bridge->AddFlutterSemanticsNodeUpdate(leaf3); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(root_id).lock(); + auto intermediary1_node = + bridge->GetFlutterPlatformNodeDelegateFromID(intermediary1_id).lock(); + auto intermediary2_node = + bridge->GetFlutterPlatformNodeDelegateFromID(intermediary2_id).lock(); + auto leaf1_node = + bridge->GetFlutterPlatformNodeDelegateFromID(leaf1_id).lock(); + auto leaf2_node = + bridge->GetFlutterPlatformNodeDelegateFromID(leaf2_id).lock(); + auto leaf3_node = + bridge->GetFlutterPlatformNodeDelegateFromID(leaf3_id).lock(); + + EXPECT_EQ(root_node->GetChildCount(), 2); + EXPECT_EQ(root_node->GetData().child_ids[0], intermediary1_id); + EXPECT_EQ(root_node->GetData().child_ids[1], intermediary2_id); + EXPECT_EQ(root_node->GetName(), "root"); + + EXPECT_EQ(intermediary1_node->GetChildCount(), 2); + EXPECT_EQ(intermediary1_node->GetData().child_ids[0], leaf2_id); + EXPECT_EQ(intermediary1_node->GetData().child_ids[1], leaf3_id); + EXPECT_EQ(intermediary1_node->GetName(), "intermediary 1"); + + EXPECT_EQ(intermediary2_node->GetChildCount(), 1); + EXPECT_EQ(intermediary2_node->GetData().child_ids[0], leaf1_id); + EXPECT_EQ(intermediary2_node->GetName(), "intermediary 2"); + + EXPECT_EQ(leaf1_node->GetChildCount(), 0); + EXPECT_EQ(leaf1_node->GetName(), "leaf 1"); + + EXPECT_EQ(leaf2_node->GetChildCount(), 0); + EXPECT_EQ(leaf2_node->GetName(), "leaf 2"); + + EXPECT_EQ(leaf3_node->GetChildCount(), 0); + EXPECT_EQ(leaf3_node->GetName(), "leaf 3"); + + // Intermediary 1 and intermediary 2 have new children. + // Leaf 1, 2, and 3 are all moved. + ASSERT_EQ(bridge->accessibility_events.size(), size_t{5}); + EXPECT_THAT(bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::CHILDREN_CHANGED).Times(2)); + EXPECT_THAT(bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::SUBTREE_CREATED).Times(3)); +} + +// Verify that a node with a child can be moved from one parent to another. +TEST(AccessibilityBridgeTest, CanReparentNodeWithChild) { + std::shared_ptr bridge = + std::make_shared(); + + int32_t root_id = 0; + int32_t intermediary1_id = 1; + int32_t intermediary2_id = 2; + int32_t leaf1_id = 3; + + std::vector root_children{intermediary1_id, intermediary2_id}; + std::vector intermediary1_children{leaf1_id}; + FlutterSemanticsNode2 root = + CreateSemanticsNode(root_id, "root", &root_children); + FlutterSemanticsNode2 intermediary1 = CreateSemanticsNode( + intermediary1_id, "intermediary 1", &intermediary1_children); + FlutterSemanticsNode2 intermediary2 = + CreateSemanticsNode(intermediary2_id, "intermediary 2"); + FlutterSemanticsNode2 leaf1 = CreateSemanticsNode(leaf1_id, "leaf 1"); + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(intermediary1); + bridge->AddFlutterSemanticsNodeUpdate(intermediary2); + bridge->AddFlutterSemanticsNodeUpdate(leaf1); + bridge->CommitUpdates(); + bridge->accessibility_events.clear(); + + // Move intermediary1 from root to intermediary 2. + int32_t new_root_children[] = {intermediary2_id}; + root.child_count = 1; + root.children_in_traversal_order = new_root_children; + + int32_t new_intermediary2_children[] = {intermediary1_id}; + intermediary2.child_count = 1; + intermediary2.children_in_traversal_order = new_intermediary2_children; + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->AddFlutterSemanticsNodeUpdate(intermediary1); + bridge->AddFlutterSemanticsNodeUpdate(intermediary2); + bridge->AddFlutterSemanticsNodeUpdate(leaf1); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(root_id).lock(); + auto intermediary1_node = + bridge->GetFlutterPlatformNodeDelegateFromID(intermediary1_id).lock(); + auto intermediary2_node = + bridge->GetFlutterPlatformNodeDelegateFromID(intermediary2_id).lock(); + auto leaf1_node = + bridge->GetFlutterPlatformNodeDelegateFromID(leaf1_id).lock(); + + EXPECT_EQ(root_node->GetChildCount(), 1); + EXPECT_EQ(root_node->GetData().child_ids[0], intermediary2_id); + EXPECT_EQ(root_node->GetName(), "root"); + + EXPECT_EQ(intermediary2_node->GetChildCount(), 1); + EXPECT_EQ(intermediary2_node->GetData().child_ids[0], intermediary1_id); + EXPECT_EQ(intermediary2_node->GetName(), "intermediary 2"); + + EXPECT_EQ(intermediary1_node->GetChildCount(), 1); + EXPECT_EQ(intermediary1_node->GetData().child_ids[0], leaf1_id); + EXPECT_EQ(intermediary1_node->GetName(), "intermediary 1"); + + EXPECT_EQ(leaf1_node->GetChildCount(), 0); + EXPECT_EQ(leaf1_node->GetName(), "leaf 1"); + + ASSERT_EQ(bridge->accessibility_events.size(), size_t{5}); + + EXPECT_THAT(bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::CHILDREN_CHANGED).Times(2)); + EXPECT_THAT(bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::SUBTREE_CREATED).Times(1)); + + // Intermediary 2 becomes a parent node. It updates to group role and enables + // its 'clip children' attribute. + EXPECT_THAT( + bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED).Times(1)); + EXPECT_THAT(bridge->accessibility_events, + Contains(ui::AXEventGenerator::Event::ROLE_CHANGED).Times(1)); +} + +TEST(AccessibilityBridgeTest, AXTreeManagerTest) { + std::shared_ptr bridge = + std::make_shared(); + + ui::AXTreeID tree_id = bridge->GetTreeID(); + ui::AXTreeManager* manager = + ui::AXTreeManagerMap::GetInstance().GetManager(tree_id); + ASSERT_EQ(manager, static_cast(bridge.get())); +} + +TEST(AccessibilityBridgeTest, LineBreakingObjectTest) { + std::shared_ptr bridge = + std::make_shared(); + + const int32_t root_id = 0; + + FlutterSemanticsNode2 root = CreateSemanticsNode(root_id, "root", {}); + + bridge->AddFlutterSemanticsNodeUpdate(root); + bridge->CommitUpdates(); + + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(root_id).lock(); + auto root_data = root_node->GetData(); + EXPECT_TRUE(root_data.HasBoolAttribute( + ax::mojom::BoolAttribute::kIsLineBreakingObject)); + EXPECT_TRUE(root_data.GetBoolAttribute( + ax::mojom::BoolAttribute::kIsLineBreakingObject)); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/alert_platform_node_delegate.cc b/flutter/engine/src/flutter/shell/platform/common/alert_platform_node_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..3208737eba9569774399805cceb6aa5a85a12a36 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/alert_platform_node_delegate.cc @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "alert_platform_node_delegate.h" + +namespace flutter { + +AlertPlatformNodeDelegate::AlertPlatformNodeDelegate( + ui::AXPlatformNodeDelegate& parent_delegate) + : parent_delegate_(parent_delegate) { + data_.role = ax::mojom::Role::kAlert; + data_.id = id_.Get(); +} + +AlertPlatformNodeDelegate::~AlertPlatformNodeDelegate() {} + +gfx::AcceleratedWidget +AlertPlatformNodeDelegate::GetTargetForNativeAccessibilityEvent() { + return parent_delegate_.GetTargetForNativeAccessibilityEvent(); +} + +gfx::NativeViewAccessible AlertPlatformNodeDelegate::GetParent() { + return parent_delegate_.GetNativeViewAccessible(); +} + +const ui::AXUniqueId& AlertPlatformNodeDelegate::GetUniqueId() const { + return id_; +} + +const ui::AXNodeData& AlertPlatformNodeDelegate::GetData() const { + return data_; +} + +void AlertPlatformNodeDelegate::SetText(const std::u16string& text) { + data_.SetName(text); + data_.SetDescription(text); + data_.SetValue(text); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/alert_platform_node_delegate.h b/flutter/engine/src/flutter/shell/platform/common/alert_platform_node_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..135b1d13f7ed18236d495a7dfa7e3e397a29f1f3 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/alert_platform_node_delegate.h @@ -0,0 +1,50 @@ +// 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_COMMON_ALERT_PLATFORM_NODE_DELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_ALERT_PLATFORM_NODE_DELEGATE_H_ + +#include "flutter/fml/macros.h" +#include "flutter/third_party/accessibility/ax/ax_node_data.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate_base.h" + +namespace flutter { + +// A delegate for a node that holds the text of an a11y alert that a +// screen-reader should announce. The delegate is used to construct an +// AXPlatformNode, and in order to serve as an alert, only needs to be able to +// hold a text announcement and make that text available to the platform node. +class AlertPlatformNodeDelegate : public ui::AXPlatformNodeDelegateBase { + public: + explicit AlertPlatformNodeDelegate( + ui::AXPlatformNodeDelegate& parent_delegate); + ~AlertPlatformNodeDelegate(); + + // Set the alert text of the node for which this is the delegate. + void SetText(const std::u16string& text); + + // |AXPlatformNodeDelegate| + gfx::NativeViewAccessible GetParent() override; + + private: + // AXPlatformNodeDelegate overrides. + gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() override; + const ui::AXUniqueId& GetUniqueId() const override; + const ui::AXNodeData& GetData() const override; + + // Delegate of the parent of this node. Returned by GetParent. + ui::AXPlatformNodeDelegate& parent_delegate_; + + // Node Data that contains the alert text. Returned by GetData. + ui::AXNodeData data_; + + // A unique ID used to identify this node. Returned by GetUniqueId. + ui::AXUniqueId id_; + + FML_DISALLOW_COPY_AND_ASSIGN(AlertPlatformNodeDelegate); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_ALERT_PLATFORM_NODE_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/app_lifecycle_state.h b/flutter/engine/src/flutter/shell/platform/common/app_lifecycle_state.h new file mode 100644 index 0000000000000000000000000000000000000000..fdce098b784781fb40856f2df7fe9dffb4b3c359 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/app_lifecycle_state.h @@ -0,0 +1,89 @@ +// 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_COMMON_APP_LIFECYCLE_STATE_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_APP_LIFECYCLE_STATE_H_ + +namespace flutter { + +/** + * These constants describe the possible lifecycle states of the application. + * They must be kept up to date with changes in the framework's + * AppLifecycleState enum. They are passed to the embedder's |SetLifecycleState| + * function. + * + * States not supported on a platform will be synthesized by the framework when + * transitioning between states which are supported, so that all implementations + * share the same state machine. + * + * Here is the state machine: + * + * +-----------+ +-----------+ + * | detached |------------------------------>| resumed | + * +-----------+ +-----------+ + * ^ ^ + * | | + * | v + * +-----------+ +--------------+ +-----------+ + * | paused |<------>| hidden |<----->| inactive | + * +-----------+ +--------------+ +-----------+ + */ +enum class AppLifecycleState { + /** + * Corresponds to the Framework's AppLifecycleState.detached: The initial + * state of the state machine. On Android, iOS, and web, also the final state + * of the state machine when all views are detached. Other platforms do not + * re-enter this state after initially leaving it. + */ + kDetached, + + /** + * Corresponds to the Framework's AppLifecycleState.resumed: The nominal + * "running" state of the application. The application is visible, has input + * focus, and is running. + */ + kResumed, + + /** + * Corresponds to the Framework's AppLifecycleState.inactive: At least one + * view of the application is visible, but none have input focus. The + * application is otherwise running normally. + */ + kInactive, + + /** + * Corresponds to the Framework's AppLifecycleState.hidden: All views of an + * application are hidden, either because the application is being stopped (on + * iOS and Android), or because it is being minimized or on a desktop that is + * no longer visible (on desktop), or on a tab that is no longer visible (on + * web). + */ + kHidden, + + /** + * Corresponds to the Framework's AppLifecycleState.paused: The application is + * not running, and can be detached or started again at any time. This state + * is typically only entered into on iOS and Android. + */ + kPaused, +}; + +constexpr const char* AppLifecycleStateToString(AppLifecycleState state) { + switch (state) { + case AppLifecycleState::kDetached: + return "AppLifecycleState.detached"; + case AppLifecycleState::kResumed: + return "AppLifecycleState.resumed"; + case AppLifecycleState::kInactive: + return "AppLifecycleState.inactive"; + case AppLifecycleState::kHidden: + return "AppLifecycleState.hidden"; + case AppLifecycleState::kPaused: + return "AppLifecycleState.paused"; + } +} + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_APP_LIFECYCLE_STATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/engine_switches.cc b/flutter/engine/src/flutter/shell/platform/common/engine_switches.cc new file mode 100644 index 0000000000000000000000000000000000000000..37b98fae47f634a6c1382d85b3cf6daf6873ceb4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/engine_switches.cc @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/engine_switches.h" + +#include +#include +#include +#include + +namespace flutter { + +std::vector GetSwitchesFromEnvironment() { + std::vector switches; + // Read engine switches from the environment in debug/profile. If release mode + // support is needed in the future, it should likely use a whitelist. +#ifndef FLUTTER_RELEASE + const char* switch_count_key = "FLUTTER_ENGINE_SWITCHES"; + const int kMaxSwitchCount = 50; + const char* switch_count_string = std::getenv(switch_count_key); + if (!switch_count_string) { + return switches; + } + int switch_count = std::min(kMaxSwitchCount, atoi(switch_count_string)); + for (int i = 1; i <= switch_count; ++i) { + std::ostringstream switch_key; + switch_key << "FLUTTER_ENGINE_SWITCH_" << i; + const char* switch_value = std::getenv(switch_key.str().c_str()); + if (switch_value) { + std::ostringstream switch_value_as_flag; + switch_value_as_flag << "--" << switch_value; + switches.push_back(switch_value_as_flag.str()); + } else { + std::cerr << switch_count << " keys expected from " << switch_count_key + << ", but " << switch_key.str() << " is missing." << std::endl; + } + } +#endif // !FLUTTER_RELEASE + return switches; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/engine_switches.h b/flutter/engine/src/flutter/shell/platform/common/engine_switches.h new file mode 100644 index 0000000000000000000000000000000000000000..029eb16ec4e558624a780456e8cf9d697b3851d4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/engine_switches.h @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_COMMON_ENGINE_SWITCHES_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_ENGINE_SWITCHES_H_ + +#include +#include + +namespace flutter { + +// Returns an array of engine switches suitable to pass to the embedder API +// in FlutterProjectArgs, based on parsing variables from the environment in +// the form: +// FLUTTER_ENGINE_SWITCHES= +// FLUTTER_ENGINE_SWITCH_1=... +// FLUTTER_ENGINE_SWITCH_2=... +// ... +// Values should match those in shell/common/switches.h +// +// The returned array does not include the initial dummy argument expected by +// the embedder API, so command_line_argv should not be set directly from it. +// +// In release mode, not all switches from the environment will necessarily be +// returned. See the implementation for details. +std::vector GetSwitchesFromEnvironment(); + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_ENGINE_SWITCHES_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/engine_switches_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/engine_switches_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ac7b01ded500315927f3e09ae751158b7184b15b --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/engine_switches_unittests.cc @@ -0,0 +1,88 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/engine_switches.h" + +#include "gtest/gtest.h" + +namespace flutter { + +namespace { +// Sets |key=value| in the environment of this process. +void SetEnvironmentVariable(const char* key, const char* value) { +#ifdef _WIN32 + _putenv_s(key, value); +#else + setenv(key, value, 1); +#endif +} + +// Removes |key| from the environment of this process, if present. +void ClearEnvironmentVariable(const char* key) { +#ifdef _WIN32 + _putenv_s(key, ""); +#else + unsetenv(key); +#endif +} +} // namespace + +TEST(FlutterProjectBundle, SwitchesEmpty) { + // Clear the main environment variable, since test order is not guaranteed. + ClearEnvironmentVariable("FLUTTER_ENGINE_SWITCHES"); + + EXPECT_EQ(GetSwitchesFromEnvironment().size(), 0U); +} + +#ifdef FLUTTER_RELEASE +TEST(FlutterProjectBundle, SwitchesIgnoredInRelease) { + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCHES", "2"); + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCH_1", "abc"); + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCH_2", "foo=\"bar, baz\""); + + std::vector switches = GetSwitchesFromEnvironment(); + EXPECT_EQ(switches.size(), 0U); +} +#endif // FLUTTER_RELEASE + +#ifndef FLUTTER_RELEASE +TEST(FlutterProjectBundle, Switches) { + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCHES", "2"); + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCH_1", "abc"); + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCH_2", "foo=\"bar, baz\""); + + std::vector switches = GetSwitchesFromEnvironment(); + EXPECT_EQ(switches.size(), 2U); + EXPECT_EQ(switches[0], "--abc"); + EXPECT_EQ(switches[1], "--foo=\"bar, baz\""); +} + +TEST(FlutterProjectBundle, SwitchesExtraValues) { + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCHES", "1"); + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCH_1", "abc"); + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCH_2", "foo=\"bar, baz\""); + + std::vector switches = GetSwitchesFromEnvironment(); + EXPECT_EQ(switches.size(), 1U); + EXPECT_EQ(switches[0], "--abc"); +} + +TEST(FlutterProjectBundle, SwitchesMissingValues) { + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCHES", "4"); + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCH_1", "abc"); + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCH_2", "foo=\"bar, baz\""); + ClearEnvironmentVariable("FLUTTER_ENGINE_SWITCH_3"); + SetEnvironmentVariable("FLUTTER_ENGINE_SWITCH_4", "oops"); + + std::vector switches = GetSwitchesFromEnvironment(); + EXPECT_EQ(switches.size(), 3U); + EXPECT_EQ(switches[0], "--abc"); + EXPECT_EQ(switches[1], "--foo=\"bar, baz\""); + // The missing switch should be skipped, leaving SWITCH_4 as the third + // switch in the array. + EXPECT_EQ(switches[2], "--oops"); +} +#endif // !FLUTTER_RELEASE + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.cc b/flutter/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e4e8a4a2b1114626e40552432a19fb6c321e5b8 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.cc @@ -0,0 +1,165 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter_platform_node_delegate.h" + +#include + +#include "flutter/shell/platform/common/accessibility_bridge.h" +#include "flutter/third_party/accessibility/ax/ax_action_data.h" +#include "flutter/third_party/accessibility/ax/ax_tree_manager_map.h" +#include "flutter/third_party/accessibility/gfx/geometry/rect_conversions.h" + +namespace flutter { + +FlutterPlatformNodeDelegate::FlutterPlatformNodeDelegate() = default; + +FlutterPlatformNodeDelegate::~FlutterPlatformNodeDelegate() = default; + +void FlutterPlatformNodeDelegate::Init(std::weak_ptr bridge, + ui::AXNode* node) { + bridge_ = std::move(bridge); + ax_node_ = node; +} + +ui::AXNode* FlutterPlatformNodeDelegate::GetAXNode() const { + return ax_node_; +} + +bool FlutterPlatformNodeDelegate::AccessibilityPerformAction( + const ui::AXActionData& data) { + AccessibilityNodeId target = ax_node_->id(); + auto bridge_ptr = bridge_.lock(); + BASE_DCHECK(bridge_ptr); + switch (data.action) { + case ax::mojom::Action::kDoDefault: + bridge_ptr->DispatchAccessibilityAction( + target, FlutterSemanticsAction::kFlutterSemanticsActionTap, {}); + return true; + case ax::mojom::Action::kFocus: + bridge_ptr->SetLastFocusedId(target); + bridge_ptr->DispatchAccessibilityAction( + target, + FlutterSemanticsAction:: + kFlutterSemanticsActionDidGainAccessibilityFocus, + {}); + return true; + case ax::mojom::Action::kScrollToMakeVisible: + bridge_ptr->DispatchAccessibilityAction( + target, FlutterSemanticsAction::kFlutterSemanticsActionShowOnScreen, + {}); + return true; + // TODO(chunhtai): support more actions. + default: + return false; + } + return false; +} + +const ui::AXNodeData& FlutterPlatformNodeDelegate::GetData() const { + return ax_node_->data(); +} + +gfx::NativeViewAccessible FlutterPlatformNodeDelegate::GetParent() { + if (!ax_node_->parent()) { + return nullptr; + } + auto bridge_ptr = bridge_.lock(); + BASE_DCHECK(bridge_ptr); + return bridge_ptr->GetNativeAccessibleFromId(ax_node_->parent()->id()); +} + +gfx::NativeViewAccessible FlutterPlatformNodeDelegate::GetFocus() { + auto bridge_ptr = bridge_.lock(); + BASE_DCHECK(bridge_ptr); + AccessibilityNodeId last_focused = bridge_ptr->GetLastFocusedId(); + if (last_focused == ui::AXNode::kInvalidAXID) { + return nullptr; + } + return bridge_ptr->GetNativeAccessibleFromId(last_focused); +} + +int FlutterPlatformNodeDelegate::GetChildCount() const { + return static_cast(ax_node_->GetUnignoredChildCount()); +} + +gfx::NativeViewAccessible FlutterPlatformNodeDelegate::ChildAtIndex(int index) { + auto bridge_ptr = bridge_.lock(); + BASE_DCHECK(bridge_ptr); + AccessibilityNodeId child = ax_node_->GetUnignoredChildAtIndex(index)->id(); + return bridge_ptr->GetNativeAccessibleFromId(child); +} + +gfx::Rect FlutterPlatformNodeDelegate::GetBoundsRect( + const ui::AXCoordinateSystem coordinate_system, + const ui::AXClippingBehavior clipping_behavior, + ui::AXOffscreenResult* offscreen_result) const { + auto bridge_ptr = bridge_.lock(); + BASE_DCHECK(bridge_ptr); + // TODO(chunhtai): We need to apply screen dpr in here. + // https://github.com/flutter/flutter/issues/74283 + const bool clip_bounds = + clipping_behavior == ui::AXClippingBehavior::kClipped; + bool offscreen = false; + gfx::RectF bounds = + bridge_ptr->RelativeToGlobalBounds(ax_node_, offscreen, clip_bounds); + if (offscreen_result != nullptr) { + *offscreen_result = offscreen ? ui::AXOffscreenResult::kOffscreen + : ui::AXOffscreenResult::kOnscreen; + } + return gfx::ToEnclosingRect(bounds); +} + +std::weak_ptr +FlutterPlatformNodeDelegate::GetOwnerBridge() const { + return bridge_; +} + +ui::AXPlatformNode* FlutterPlatformNodeDelegate::GetPlatformNode() const { + return nullptr; +} + +gfx::NativeViewAccessible +FlutterPlatformNodeDelegate::GetLowestPlatformAncestor() const { + auto bridge_ptr = bridge_.lock(); + BASE_DCHECK(bridge_ptr); + auto lowest_platform_ancestor = ax_node_->GetLowestPlatformAncestor(); + if (lowest_platform_ancestor) { + return bridge_ptr->GetNativeAccessibleFromId( + ax_node_->GetLowestPlatformAncestor()->id()); + } + return nullptr; +} + +ui::AXNodePosition::AXPositionInstance +FlutterPlatformNodeDelegate::CreateTextPositionAt(int offset) const { + return ui::AXNodePosition::CreatePosition(*ax_node_, offset); +} + +ui::AXPlatformNode* FlutterPlatformNodeDelegate::GetFromNodeID( + int32_t node_id) { + ui::AXTreeManager* tree_manager = + ui::AXTreeManagerMap::GetInstance().GetManager( + ax_node_->tree()->GetAXTreeID()); + AccessibilityBridge* platform_manager = + static_cast(tree_manager); + return platform_manager->GetPlatformNodeFromTree(node_id); +} + +ui::AXPlatformNode* FlutterPlatformNodeDelegate::GetFromTreeIDAndNodeID( + const ui::AXTreeID& tree_id, + int32_t node_id) { + ui::AXTreeManager* tree_manager = + ui::AXTreeManagerMap::GetInstance().GetManager(tree_id); + AccessibilityBridge* platform_manager = + static_cast(tree_manager); + return platform_manager->GetPlatformNodeFromTree(node_id); +} + +const ui::AXTree::Selection FlutterPlatformNodeDelegate::GetUnignoredSelection() + const { + return ax_node_->GetUnignoredSelection(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.h b/flutter/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..9c90d5a953fd3cd13ebe4f438e0cdddb77920e40 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate.h @@ -0,0 +1,182 @@ +// 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_COMMON_FLUTTER_PLATFORM_NODE_DELEGATE_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_FLUTTER_PLATFORM_NODE_DELEGATE_H_ + +#include "flutter/fml/mapping.h" +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/third_party/accessibility/ax/ax_event_generator.h" +#include "flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate_base.h" + +namespace flutter { + +typedef ui::AXNode::AXID AccessibilityNodeId; + +//------------------------------------------------------------------------------ +/// The platform node delegate to be used in accessibility bridge. This +/// class is responsible for providing native accessibility object with +/// appropriate information, such as accessibility label/value/bounds. +/// +/// While most methods have default implementations and are ready to be used +/// as-is, the subclasses must override the GetNativeViewAccessible to return +/// native accessibility objects. To do that, subclasses should create and +/// maintain AXPlatformNode[s] which delegate their accessibility attributes to +/// this class. +/// +/// For desktop platforms, subclasses also need to override the GetBoundsRect +/// to apply window-to-screen transform. +/// +/// This class transforms bounds assuming the device pixel ratio is 1.0. See +/// the https://github.com/flutter/flutter/issues/74283 for more information. +class FlutterPlatformNodeDelegate : public ui::AXPlatformNodeDelegateBase { + public: + //---------------------------------------------------------------------------- + /// The required interface to be able to own the flutter platform node + /// delegate. + class OwnerBridge { + public: + virtual ~OwnerBridge() = default; + + //--------------------------------------------------------------------------- + /// @brief Gets the rectangular bounds of the ax node relative to + /// global coordinate + /// + /// @param[in] node The ax node to look up. + /// @param[in] offscreen the bool reference to hold the result whether + /// the ax node is outside of its ancestors' bounds. + /// @param[in] clip_bounds whether to clip the result if the ax node cannot + /// be fully contained in its ancestors' bounds. + virtual gfx::RectF RelativeToGlobalBounds(const ui::AXNode* node, + bool& offscreen, + bool clip_bounds) = 0; + + protected: + friend class FlutterPlatformNodeDelegate; + + //--------------------------------------------------------------------------- + /// @brief Dispatch accessibility action back to the Flutter framework. + /// These actions are generated in the native accessibility + /// system when users interact with the assistive technologies. + /// For example, a + /// FlutterSemanticsAction::kFlutterSemanticsActionTap is + /// fired when user click or touch the screen. + /// + /// @param[in] target The semantics node id of the action + /// target. + /// @param[in] action The generated flutter semantics action. + /// @param[in] data Additional data associated with the + /// action. + virtual void DispatchAccessibilityAction(AccessibilityNodeId target, + FlutterSemanticsAction action, + fml::MallocMapping data) = 0; + + //--------------------------------------------------------------------------- + /// @brief Get the native accessibility node with the given id. + /// + /// @param[in] id The id of the native accessibility node you + /// want to retrieve. + virtual gfx::NativeViewAccessible GetNativeAccessibleFromId( + AccessibilityNodeId id) = 0; + + //--------------------------------------------------------------------------- + /// @brief Get the last id of the node that received accessibility + /// focus. + virtual AccessibilityNodeId GetLastFocusedId() = 0; + + //--------------------------------------------------------------------------- + /// @brief Update the id of the node that is currently foucsed by the + /// native accessibility system. + /// + /// @param[in] node_id The id of the focused node. + virtual void SetLastFocusedId(AccessibilityNodeId node_id) = 0; + }; + + FlutterPlatformNodeDelegate(); + + // |ui::AXPlatformNodeDelegateBase| + virtual ~FlutterPlatformNodeDelegate() override; + + // |ui::AXPlatformNodeDelegateBase| + const ui::AXUniqueId& GetUniqueId() const override { return unique_id_; } + + // |ui::AXPlatformNodeDelegateBase| + const ui::AXNodeData& GetData() const override; + + // |ui::AXPlatformNodeDelegateBase| + bool AccessibilityPerformAction(const ui::AXActionData& data) override; + + // |ui::AXPlatformNodeDelegateBase| + gfx::NativeViewAccessible GetParent() override; + + // |ui::AXPlatformNodeDelegateBase| + gfx::NativeViewAccessible GetFocus() override; + + // |ui::AXPlatformNodeDelegateBase| + int GetChildCount() const override; + + // |ui::AXPlatformNodeDelegateBase| + gfx::NativeViewAccessible ChildAtIndex(int index) override; + + // |ui::AXPlatformNodeDelegateBase| + gfx::Rect GetBoundsRect( + const ui::AXCoordinateSystem coordinate_system, + const ui::AXClippingBehavior clipping_behavior, + ui::AXOffscreenResult* offscreen_result) const override; + + // |ui::AXPlatformNodeDelegateBase| + gfx::NativeViewAccessible GetLowestPlatformAncestor() const override; + + // |ui::AXPlatformNodeDelegateBase| + ui::AXNodePosition::AXPositionInstance CreateTextPositionAt( + int offset) const override; + + //------------------------------------------------------------------------------ + /// @brief Called only once, immediately after construction. The + /// constructor doesn't take any arguments because in the Windows + /// subclass we use a special function to construct a COM object. + /// Subclasses must call super. + virtual void Init(std::weak_ptr bridge, ui::AXNode* node); + + //------------------------------------------------------------------------------ + // @brief Called when node was updated. Subclasses can override this + // to update platform nodes. + virtual void NodeDataChanged(const ui::AXNodeData& old_node_data, + const ui::AXNodeData& new_node_data) {} + + //------------------------------------------------------------------------------ + /// @brief Gets the underlying ax node for this platform node delegate. + ui::AXNode* GetAXNode() const; + + //------------------------------------------------------------------------------ + /// @brief Gets the owner of this platform node delegate. This is useful + /// when you want to get the information about surrounding nodes + /// of this platform node delegate, e.g. the global rect of this + /// platform node delegate. This pointer is only safe in the + /// platform thread. + std::weak_ptr GetOwnerBridge() const; + + // Get the platform node represented by this delegate. + virtual ui::AXPlatformNode* GetPlatformNode() const; + + // |ui::AXPlatformNodeDelegateBase| + virtual ui::AXPlatformNode* GetFromNodeID(int32_t id) override; + + // |ui::AXPlatformNodeDelegateBase| + virtual ui::AXPlatformNode* GetFromTreeIDAndNodeID( + const ui::AXTreeID& tree_id, + int32_t node_id) override; + + // |ui::AXPlatformNodeDelegateBase| + virtual const ui::AXTree::Selection GetUnignoredSelection() const override; + + private: + ui::AXNode* ax_node_; + std::weak_ptr bridge_; + ui::AXUniqueId unique_id_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_FLUTTER_PLATFORM_NODE_DELEGATE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..00e3240fa4f6c57c5f8225a9a315e3d36927ce79 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/flutter_platform_node_delegate_unittests.cc @@ -0,0 +1,308 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter_platform_node_delegate.h" + +#include "flutter/third_party/accessibility/ax/ax_action_data.h" +#include "gtest/gtest.h" + +#include "test_accessibility_bridge.h" + +namespace flutter { +namespace testing { + +TEST(FlutterPlatformNodeDelegateTest, NodeDelegateHasUniqueId) { + std::shared_ptr bridge = + std::make_shared(); + + // Add node 0: root. + FlutterSemanticsNode2 node0{sizeof(FlutterSemanticsNode2), 0}; + std::vector node0_children{1}; + node0.child_count = node0_children.size(); + node0.children_in_traversal_order = node0_children.data(); + node0.children_in_hit_test_order = node0_children.data(); + + // Add node 1: text child of node 0. + FlutterSemanticsNode2 node1{sizeof(FlutterSemanticsNode2), 1}; + node1.label = "prefecture"; + node1.value = "Kyoto"; + + bridge->AddFlutterSemanticsNodeUpdate(node0); + bridge->AddFlutterSemanticsNodeUpdate(node1); + bridge->CommitUpdates(); + + auto node0_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + auto node1_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + EXPECT_TRUE(node0_delegate->GetUniqueId() != node1_delegate->GetUniqueId()); +} + +TEST(FlutterPlatformNodeDelegateTest, canPerfomActions) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField; + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 0; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + + auto accessibility = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + // Performs an AXAction. + ui::AXActionData action_data; + action_data.action = ax::mojom::Action::kDoDefault; + accessibility->AccessibilityPerformAction(action_data); + EXPECT_EQ(bridge->performed_actions.size(), size_t{1}); + EXPECT_EQ(bridge->performed_actions[0], + FlutterSemanticsAction::kFlutterSemanticsActionTap); + + action_data.action = ax::mojom::Action::kFocus; + accessibility->AccessibilityPerformAction(action_data); + EXPECT_EQ(bridge->performed_actions.size(), size_t{2}); + EXPECT_EQ( + bridge->performed_actions[1], + FlutterSemanticsAction::kFlutterSemanticsActionDidGainAccessibilityFocus); + + action_data.action = ax::mojom::Action::kScrollToMakeVisible; + accessibility->AccessibilityPerformAction(action_data); + EXPECT_EQ(bridge->performed_actions.size(), size_t{3}); + EXPECT_EQ(bridge->performed_actions[2], + FlutterSemanticsAction::kFlutterSemanticsActionShowOnScreen); +} + +TEST(FlutterPlatformNodeDelegateTest, canGetAXNode) { + // Set up a flutter accessibility node. + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root; + root.id = 0; + root.flags = FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField; + root.actions = static_cast(0); + root.text_selection_base = -1; + root.text_selection_extent = -1; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 0; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + + auto accessibility = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + EXPECT_EQ(accessibility->GetData().id, 0); +} + +TEST(FlutterPlatformNodeDelegateTest, canCalculateBoundsCorrectly) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root; + root.id = 0; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + root.rect = {0, 0, 100, 100}; // LTRB + root.transform = {1, 0, 0, 0, 1, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(root); + + FlutterSemanticsNode2 child1; + child1.id = 1; + child1.label = "child 1"; + child1.hint = ""; + child1.value = ""; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.tooltip = ""; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + child1.rect = {0, 0, 50, 50}; // LTRB + child1.transform = {0.5, 0, 0, 0, 0.5, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(child1); + + bridge->CommitUpdates(); + auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + ui::AXOffscreenResult result; + gfx::Rect bounds = + child1_node->GetBoundsRect(ui::AXCoordinateSystem::kScreenDIPs, + ui::AXClippingBehavior::kClipped, &result); + EXPECT_EQ(bounds.x(), 0); + EXPECT_EQ(bounds.y(), 0); + EXPECT_EQ(bounds.width(), 25); + EXPECT_EQ(bounds.height(), 25); + EXPECT_EQ(result, ui::AXOffscreenResult::kOnscreen); +} + +TEST(FlutterPlatformNodeDelegateTest, canCalculateOffScreenBoundsCorrectly) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root; + root.id = 0; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + root.rect = {0, 0, 100, 100}; // LTRB + root.transform = {1, 0, 0, 0, 1, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(root); + + FlutterSemanticsNode2 child1; + child1.id = 1; + child1.label = "child 1"; + child1.hint = ""; + child1.value = ""; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.tooltip = ""; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + child1.rect = {90, 90, 100, 100}; // LTRB + child1.transform = {2, 0, 0, 0, 2, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(child1); + + bridge->CommitUpdates(); + auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + ui::AXOffscreenResult result; + gfx::Rect bounds = + child1_node->GetBoundsRect(ui::AXCoordinateSystem::kScreenDIPs, + ui::AXClippingBehavior::kUnclipped, &result); + EXPECT_EQ(bounds.x(), 180); + EXPECT_EQ(bounds.y(), 180); + EXPECT_EQ(bounds.width(), 20); + EXPECT_EQ(bounds.height(), 20); + EXPECT_EQ(result, ui::AXOffscreenResult::kOffscreen); +} + +TEST(FlutterPlatformNodeDelegateTest, canUseOwnerBridge) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root; + root.id = 0; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + root.rect = {0, 0, 100, 100}; // LTRB + root.transform = {1, 0, 0, 0, 1, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(root); + + FlutterSemanticsNode2 child1; + child1.id = 1; + child1.label = "child 1"; + child1.hint = ""; + child1.value = ""; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.tooltip = ""; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + child1.rect = {0, 0, 50, 50}; // LTRB + child1.transform = {0.5, 0, 0, 0, 0.5, 0, 0, 0, 1}; + bridge->AddFlutterSemanticsNodeUpdate(child1); + + bridge->CommitUpdates(); + auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + auto owner_bridge = child1_node->GetOwnerBridge().lock(); + + bool result; + gfx::RectF bounds = owner_bridge->RelativeToGlobalBounds( + child1_node->GetAXNode(), result, true); + EXPECT_EQ(bounds.x(), 0); + EXPECT_EQ(bounds.y(), 0); + EXPECT_EQ(bounds.width(), 25); + EXPECT_EQ(bounds.height(), 25); + EXPECT_EQ(result, false); +} + +TEST(FlutterPlatformNodeDelegateTest, selfIsLowestPlatformAncestor) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root; + root.id = 0; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 0; + root.children_in_traversal_order = nullptr; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + bridge->CommitUpdates(); + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + auto lowest_platform_ancestor = root_node->GetLowestPlatformAncestor(); + EXPECT_EQ(root_node->GetNativeViewAccessible(), lowest_platform_ancestor); +} + +TEST(FlutterPlatformNodeDelegateTest, canGetFromNodeID) { + std::shared_ptr bridge = + std::make_shared(); + FlutterSemanticsNode2 root; + root.id = 0; + root.label = "root"; + root.hint = ""; + root.value = ""; + root.increased_value = ""; + root.decreased_value = ""; + root.tooltip = ""; + root.child_count = 1; + int32_t children[] = {1}; + root.children_in_traversal_order = children; + root.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(root); + + FlutterSemanticsNode2 child1; + child1.id = 1; + child1.label = "child 1"; + child1.hint = ""; + child1.value = ""; + child1.increased_value = ""; + child1.decreased_value = ""; + child1.tooltip = ""; + child1.child_count = 0; + child1.custom_accessibility_actions_count = 0; + bridge->AddFlutterSemanticsNodeUpdate(child1); + + bridge->CommitUpdates(); + auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); + auto child1_node = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock(); + auto node_by_id = root_node->GetFromNodeID(1); + EXPECT_EQ(child1_node->GetPlatformNode(), node_by_id); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/geometry.h b/flutter/engine/src/flutter/shell/platform/common/geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..4d6e8daded04157776cf3243e082619f8276972a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/geometry.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_COMMON_GEOMETRY_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_GEOMETRY_H_ + +#include + +namespace flutter { + +// A point in Cartesian space relative to a separately-maintained origin. +class Point { + public: + Point() = default; + Point(double x, double y) : x_(x), y_(y) {} + Point(const Point& point) = default; + Point& operator=(const Point& other) = default; + + double x() const { return x_; } + double y() const { return y_; } + + bool operator==(const Point& other) const { + return x_ == other.x_ && y_ == other.y_; + } + + private: + double x_ = 0.0; + double y_ = 0.0; +}; + +// A 2D floating-point size with non-negative dimensions. +class Size { + public: + Size() = default; + Size(double width, double height) + : width_(std::fmax(0.0, width)), height_(std::fmax(0.0, height)) {} + + Size(const Size& size) = default; + Size& operator=(const Size& other) = default; + + double width() const { return width_; } + double height() const { return height_; } + + bool operator==(const Size& other) const { + return width_ == other.width_ && height_ == other.height_; + } + + private: + double width_ = 0.0; + double height_ = 0.0; +}; + +// A rectangle with position in Cartesian space specified relative to a +// separately-maintained origin. +class Rect { + public: + Rect() = default; + Rect(const Point& origin, const Size& size) : origin_(origin), size_(size) {} + Rect(const Rect& rect) = default; + Rect& operator=(const Rect& other) = default; + + double left() const { return origin_.x(); } + double top() const { return origin_.y(); } + double right() const { return origin_.x() + size_.width(); } + double bottom() const { return origin_.y() + size_.height(); } + double width() const { return size_.width(); } + double height() const { return size_.height(); } + Point origin() const { return origin_; } + Size size() const { return size_; } + + bool operator==(const Rect& other) const { + return origin_ == other.origin_ && size_ == other.size_; + } + + private: + Point origin_; + Size size_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/geometry_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/geometry_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..c8645028be9090ae404d5ab004f26ab1cb1f2431 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/geometry_unittests.cc @@ -0,0 +1,55 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/geometry.h" + +#include "gtest/gtest.h" + +namespace flutter { + +TEST(Point, SetsCoordinates) { + Point point(-30.0, 42.0); + EXPECT_DOUBLE_EQ(-30.0, point.x()); + EXPECT_DOUBLE_EQ(42.0, point.y()); +} + +TEST(Size, SetsDimensions) { + Size size(20.0, 42.0); + EXPECT_DOUBLE_EQ(20.0, size.width()); + EXPECT_DOUBLE_EQ(42.0, size.height()); +} + +TEST(Size, ClampsDimensionsPositive) { + Size size(-20.0, -42.0); + EXPECT_DOUBLE_EQ(0.0, size.width()); + EXPECT_DOUBLE_EQ(0.0, size.height()); +} + +TEST(Rect, SetsOriginAndSize) { + Point origin(-30.0, 42.0); + Size size(20.0, 22.0); + Rect rect(origin, size); + EXPECT_EQ(origin, rect.origin()); + EXPECT_EQ(size, rect.size()); +} + +TEST(Rect, ReturnsLTRB) { + Point origin(-30.0, 42.0); + Size size(20.0, 22.0); + Rect rect(origin, size); + EXPECT_DOUBLE_EQ(-30.0, rect.left()); + EXPECT_DOUBLE_EQ(42.0, rect.top()); + EXPECT_DOUBLE_EQ(-10.0, rect.right()); + EXPECT_DOUBLE_EQ(64.0, rect.bottom()); +} + +TEST(Rect, ReturnsWidthHeight) { + Point origin(-30.0, 42.0); + Size size(20.0, 22.0); + Rect rect(origin, size); + EXPECT_DOUBLE_EQ(20.0, rect.width()); + EXPECT_DOUBLE_EQ(22.0, rect.height()); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/incoming_message_dispatcher.cc b/flutter/engine/src/flutter/shell/platform/common/incoming_message_dispatcher.cc new file mode 100644 index 0000000000000000000000000000000000000000..5cc23d248134a9fc557881525bb81f81a06f8ec0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/incoming_message_dispatcher.cc @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/incoming_message_dispatcher.h" + +namespace flutter { + +IncomingMessageDispatcher::IncomingMessageDispatcher( + FlutterDesktopMessengerRef messenger) + : messenger_(messenger) {} + +IncomingMessageDispatcher::~IncomingMessageDispatcher() = default; + +/// @note Procedure doesn't copy all closures. +void IncomingMessageDispatcher::HandleMessage( + const FlutterDesktopMessage& message, + const std::function& input_block_cb, + const std::function& input_unblock_cb) { + std::string channel(message.channel); + + auto callback_iterator = callbacks_.find(channel); + // Find the handler for the channel; if there isn't one, report the failure. + if (callback_iterator == callbacks_.end()) { + FlutterDesktopMessengerSendResponse(messenger_, message.response_handle, + nullptr, 0); + return; + } + auto& callback_info = callback_iterator->second; + const FlutterDesktopMessageCallback& message_callback = callback_info.first; + + // Process the call, handling input blocking if requested. + bool block_input = input_blocking_channels_.count(channel) > 0; + if (block_input) { + input_block_cb(); + } + message_callback(messenger_, &message, callback_info.second); + if (block_input) { + input_unblock_cb(); + } +} + +void IncomingMessageDispatcher::SetMessageCallback( + const std::string& channel, + FlutterDesktopMessageCallback callback, + void* user_data) { + if (!callback) { + callbacks_.erase(channel); + return; + } + callbacks_[channel] = std::make_pair(callback, user_data); +} + +void IncomingMessageDispatcher::EnableInputBlockingForChannel( + const std::string& channel) { + input_blocking_channels_.insert(channel); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/incoming_message_dispatcher.h b/flutter/engine/src/flutter/shell/platform/common/incoming_message_dispatcher.h new file mode 100644 index 0000000000000000000000000000000000000000..2152b05818da78afc0c8b3eb83866219e4dd2067 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/incoming_message_dispatcher.h @@ -0,0 +1,78 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_COMMON_INCOMING_MESSAGE_DISPATCHER_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_INCOMING_MESSAGE_DISPATCHER_H_ + +#include +#include +#include +#include +#include + +#include "flutter/shell/platform/common/public/flutter_messenger.h" + +namespace flutter { + +// Manages per-channel registration of callbacks for handling messages from the +// Flutter engine, and dispatching incoming messages to those handlers. +class IncomingMessageDispatcher { + public: + // Creates a new IncomingMessageDispatcher. |messenger| must remain valid as + // long as this object exists. + explicit IncomingMessageDispatcher(FlutterDesktopMessengerRef messenger); + + virtual ~IncomingMessageDispatcher(); + + // Prevent copying. + IncomingMessageDispatcher(IncomingMessageDispatcher const&) = delete; + IncomingMessageDispatcher& operator=(IncomingMessageDispatcher const&) = + delete; + + // Routes |message| to the registered handler for its channel, if any. + // + // If input blocking has been enabled on that channel, wraps the call to the + // handler with calls to the given callbacks to block and then unblock input. + // + // If no handler is registered for the message's channel, sends a + // NotImplemented response to the engine. + void HandleMessage( + const FlutterDesktopMessage& message, + const std::function& input_block_cb = [] {}, + const std::function& input_unblock_cb = [] {}); + + // Registers a message callback for incoming messages from the Flutter + // side on the specified channel. |callback| will be called with the message + // and |user_data| any time a message arrives on that channel. + // + // Replaces any existing callback. Pass a null callback to unregister the + // existing callback. + void SetMessageCallback(const std::string& channel, + FlutterDesktopMessageCallback callback, + void* user_data); + + // Enables input blocking on the given channel name. + // + // If set, then the parent window should disable input callbacks + // while waiting for the handler for messages on that channel to run. + void EnableInputBlockingForChannel(const std::string& channel); + + private: + // Handle for interacting with the C messaging API. + FlutterDesktopMessengerRef messenger_; + + // A map from channel names to the FlutterDesktopMessageCallback that should + // be called for incoming messages on that channel, along with the void* user + // data to pass to it. + std::map> + callbacks_; + + // Channel names for which input blocking should be enabled during the call to + // that channel's handler. + std::set input_blocking_channels_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_INCOMING_MESSAGE_DISPATCHER_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/incoming_message_dispatcher_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/incoming_message_dispatcher_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..55d69ed3692189d24523c5a6665a1a639457f7d4 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/incoming_message_dispatcher_unittests.cc @@ -0,0 +1,91 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/incoming_message_dispatcher.h" + +#include "gtest/gtest.h" + +namespace flutter { +TEST(IncomingMessageDispatcher, SetHandle) { + FlutterDesktopMessengerRef messenger = + reinterpret_cast(0xfeedface); + const uint8_t* message_data = reinterpret_cast(0xcafebabe); + auto dispatcher = std::make_unique(messenger); + bool did_call = false; + dispatcher->SetMessageCallback( + "hello", + [](FlutterDesktopMessengerRef messenger, + const FlutterDesktopMessage* message, void* user_data) { + EXPECT_EQ(messenger, + reinterpret_cast(0xfeedface)); + EXPECT_EQ(message->message, + reinterpret_cast(0xcafebabe)); + EXPECT_EQ(message->message_size, 123u); + *reinterpret_cast(user_data) = true; + }, + &did_call); + FlutterDesktopMessage message = { + .struct_size = sizeof(FlutterDesktopMessage), + .channel = "hello", + .message = message_data, + .message_size = 123, + .response_handle = nullptr, + }; + dispatcher->HandleMessage(message); + EXPECT_TRUE(did_call); +} + +TEST(IncomingMessageDispatcher, BlockInputFalse) { + FlutterDesktopMessengerRef messenger = nullptr; + auto dispatcher = std::make_unique(messenger); + bool did_call[3] = {false, false, false}; + dispatcher->SetMessageCallback( + "hello", + [](FlutterDesktopMessengerRef messenger, + const FlutterDesktopMessage* message, + void* user_data) { reinterpret_cast(user_data)[0] = true; }, + &did_call); + FlutterDesktopMessage message = { + .struct_size = sizeof(FlutterDesktopMessage), + .channel = "hello", + .message = nullptr, + .message_size = 0, + .response_handle = nullptr, + }; + dispatcher->HandleMessage( + message, [&did_call] { did_call[1] = true; }, + [&did_call] { did_call[2] = true; }); + EXPECT_TRUE(did_call[0]); + EXPECT_FALSE(did_call[1]); + EXPECT_FALSE(did_call[2]); +} + +TEST(IncomingMessageDispatcher, BlockInputTrue) { + FlutterDesktopMessengerRef messenger = nullptr; + auto dispatcher = std::make_unique(messenger); + static int counter = 0; + int did_call[3] = {-1, -1, -1}; + dispatcher->EnableInputBlockingForChannel("hello"); + dispatcher->SetMessageCallback( + "hello", + [](FlutterDesktopMessengerRef messenger, + const FlutterDesktopMessage* message, + void* user_data) { reinterpret_cast(user_data)[counter++] = 1; }, + &did_call); + FlutterDesktopMessage message = { + .struct_size = sizeof(FlutterDesktopMessage), + .channel = "hello", + .message = nullptr, + .message_size = 0, + .response_handle = nullptr, + }; + dispatcher->HandleMessage( + message, [&did_call] { did_call[counter++] = 0; }, + [&did_call] { did_call[counter++] = 2; }); + EXPECT_EQ(did_call[0], 0); + EXPECT_EQ(did_call[1], 1); + EXPECT_EQ(did_call[2], 2); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/json_message_codec.cc b/flutter/engine/src/flutter/shell/platform/common/json_message_codec.cc new file mode 100644 index 0000000000000000000000000000000000000000..76229323a713475fa9c11b9023d38f4fc7ef843c --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/json_message_codec.cc @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/json_message_codec.h" + +#include +#include + +#include "rapidjson/error/en.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/writer.h" + +namespace flutter { + +// static +const JsonMessageCodec& JsonMessageCodec::GetInstance() { + static JsonMessageCodec sInstance; + return sInstance; +} + +std::unique_ptr> JsonMessageCodec::EncodeMessageInternal( + const rapidjson::Document& message) const { + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + // clang-tidy has trouble reasoning about some of the complicated array and + // pointer-arithmetic code in rapidjson. + // NOLINTNEXTLINE(clang-analyzer-core.*) + message.Accept(writer); + const char* buffer_start = buffer.GetString(); + return std::make_unique>( + buffer_start, buffer_start + buffer.GetSize()); +} + +std::unique_ptr JsonMessageCodec::DecodeMessageInternal( + const uint8_t* binary_message, + const size_t message_size) const { + auto raw_message = reinterpret_cast(binary_message); + auto json_message = std::make_unique(); + rapidjson::ParseResult result = + json_message->Parse(raw_message, message_size); + if (result.IsError()) { + std::cerr << "Unable to parse JSON message:" << std::endl + << rapidjson::GetParseError_En(result.Code()) << std::endl; + return nullptr; + } + return json_message; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/json_message_codec.h b/flutter/engine/src/flutter/shell/platform/common/json_message_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..dc27b8f3d1475f4e1ee321d73cca726d76da9e65 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/json_message_codec.h @@ -0,0 +1,43 @@ +// 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_COMMON_JSON_MESSAGE_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_JSON_MESSAGE_CODEC_H_ + +#include + +#include "flutter/shell/platform/common/client_wrapper/include/flutter/message_codec.h" + +namespace flutter { + +// A message encoding/decoding mechanism for communications to/from the +// Flutter engine via JSON channels. +class JsonMessageCodec : public MessageCodec { + public: + // Returns the shared instance of the codec. + static const JsonMessageCodec& GetInstance(); + + ~JsonMessageCodec() = default; + + // Prevent copying. + JsonMessageCodec(JsonMessageCodec const&) = delete; + JsonMessageCodec& operator=(JsonMessageCodec const&) = delete; + + protected: + // Instances should be obtained via GetInstance. + JsonMessageCodec() = default; + + // |flutter::MessageCodec| + std::unique_ptr DecodeMessageInternal( + const uint8_t* binary_message, + const size_t message_size) const override; + + // |flutter::MessageCodec| + std::unique_ptr> EncodeMessageInternal( + const rapidjson::Document& message) const override; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_JSON_MESSAGE_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/json_message_codec_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/json_message_codec_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..e95de83865c9198cc3cd2e89e64673e0f0fe5513 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/json_message_codec_unittests.cc @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/json_message_codec.h" + +#include +#include +#include + +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// Validates round-trip encoding and decoding of |value|. +static void CheckEncodeDecode(const rapidjson::Document& value) { + const JsonMessageCodec& codec = JsonMessageCodec::GetInstance(); + auto encoded = codec.EncodeMessage(value); + ASSERT_TRUE(encoded); + auto decoded = codec.DecodeMessage(*encoded); + EXPECT_EQ(value, *decoded); +} + +} // namespace + +// Tests that a JSON document with various data types round-trips correctly. +TEST(JsonMessageCodec, EncodeDecode) { + // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) + rapidjson::Document array(rapidjson::kArrayType); + auto& allocator = array.GetAllocator(); + + array.PushBack("string", allocator); + + rapidjson::Value map(rapidjson::kObjectType); + map.AddMember("a", -7, allocator); + map.AddMember("b", std::numeric_limits::max(), allocator); + map.AddMember("c", 3.14159, allocator); + map.AddMember("d", true, allocator); + map.AddMember("e", rapidjson::Value(), allocator); + array.PushBack(map, allocator); + + CheckEncodeDecode(array); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/json_method_codec.cc b/flutter/engine/src/flutter/shell/platform/common/json_method_codec.cc new file mode 100644 index 0000000000000000000000000000000000000000..da543c1eb14eeae2b6daa1f3467bdcaa71c0f012 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/json_method_codec.cc @@ -0,0 +1,158 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/json_method_codec.h" + +#include "flutter/shell/platform/common/json_message_codec.h" + +namespace flutter { + +namespace { + +// Keys used in MethodCall encoding. +constexpr char kMessageMethodKey[] = "method"; +constexpr char kMessageArgumentsKey[] = "args"; + +// Returns a new document containing only |element|, which must be an element +// in |document|. This is a move rather than a copy, so it is efficient but +// destructive to the data in |document|. +std::unique_ptr ExtractElement( + rapidjson::Document* document, + rapidjson::Value* subtree) { + auto extracted = std::make_unique(); + // Pull the subtree up to the root of the document. + document->Swap(*subtree); + // Swap the entire document into |extracted|. Unlike the swap above this moves + // the allocator ownership, so the data won't be deleted when |document| is + // destroyed. + extracted->Swap(*document); + return extracted; +} + +} // namespace + +// static +const JsonMethodCodec& JsonMethodCodec::GetInstance() { + static JsonMethodCodec sInstance; + return sInstance; +} + +std::unique_ptr> +JsonMethodCodec::DecodeMethodCallInternal(const uint8_t* message, + size_t message_size) const { + std::unique_ptr json_message = + JsonMessageCodec::GetInstance().DecodeMessage(message, message_size); + if (!json_message) { + return nullptr; + } + + auto method_name_iter = json_message->FindMember(kMessageMethodKey); + if (method_name_iter == json_message->MemberEnd()) { + return nullptr; + } + if (!method_name_iter->value.IsString()) { + return nullptr; + } + std::string method_name(method_name_iter->value.GetString()); + auto arguments_iter = json_message->FindMember(kMessageArgumentsKey); + std::unique_ptr arguments; + if (arguments_iter != json_message->MemberEnd()) { + arguments = ExtractElement(json_message.get(), &(arguments_iter->value)); + } + return std::make_unique>( + method_name, std::move(arguments)); +} + +std::unique_ptr> JsonMethodCodec::EncodeMethodCallInternal( + const MethodCall& method_call) const { + // TODO(stuartmorgan): Consider revisiting the codec APIs to avoid the need + // to copy everything when doing encoding (e.g., by having a version that + // takes owership of the object to encode, so that it can be moved instead). + rapidjson::Document message(rapidjson::kObjectType); + auto& allocator = message.GetAllocator(); + rapidjson::Value name(method_call.method_name(), allocator); + rapidjson::Value arguments; + if (method_call.arguments()) { + arguments.CopyFrom(*method_call.arguments(), allocator); + } + message.AddMember(kMessageMethodKey, name, allocator); + message.AddMember(kMessageArgumentsKey, arguments, allocator); + + return JsonMessageCodec::GetInstance().EncodeMessage(message); +} + +std::unique_ptr> +JsonMethodCodec::EncodeSuccessEnvelopeInternal( + const rapidjson::Document* result) const { + rapidjson::Document envelope; + envelope.SetArray(); + rapidjson::Value result_value; + if (result) { + result_value.CopyFrom(*result, envelope.GetAllocator()); + } + envelope.PushBack(result_value, envelope.GetAllocator()); + + return JsonMessageCodec::GetInstance().EncodeMessage(envelope); +} + +std::unique_ptr> +JsonMethodCodec::EncodeErrorEnvelopeInternal( + const std::string& error_code, + const std::string& error_message, + const rapidjson::Document* error_details) const { + // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) + rapidjson::Document envelope(rapidjson::kArrayType); + auto& allocator = envelope.GetAllocator(); + envelope.PushBack(rapidjson::Value(error_code, allocator), allocator); + envelope.PushBack(rapidjson::Value(error_message, allocator), allocator); + rapidjson::Value details_value; + if (error_details) { + details_value.CopyFrom(*error_details, allocator); + } + envelope.PushBack(details_value, allocator); + + return JsonMessageCodec::GetInstance().EncodeMessage(envelope); +} + +bool JsonMethodCodec::DecodeAndProcessResponseEnvelopeInternal( + const uint8_t* response, + size_t response_size, + MethodResult* result) const { + std::unique_ptr json_response = + JsonMessageCodec::GetInstance().DecodeMessage(response, response_size); + if (!json_response) { + return false; + } + if (!json_response->IsArray()) { + return false; + } + switch (json_response->Size()) { + case 1: { + std::unique_ptr value = + ExtractElement(json_response.get(), &((*json_response)[0])); + if (value->IsNull()) { + result->Success(); + } else { + result->Success(*value); + } + return true; + } + case 3: { + std::string code = (*json_response)[0].GetString(); + std::string message = (*json_response)[1].GetString(); + std::unique_ptr details = + ExtractElement(json_response.get(), &((*json_response)[2])); + if (details->IsNull()) { + result->Error(code, message); + } else { + result->Error(code, message, *details); + } + return true; + } + default: + return false; + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/json_method_codec.h b/flutter/engine/src/flutter/shell/platform/common/json_method_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..31ba96c0272cbe8fd0d9d7c439fd70784aa17e61 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/json_method_codec.h @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_COMMON_JSON_METHOD_CODEC_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_JSON_METHOD_CODEC_H_ + +#include + +#include "flutter/shell/platform/common/client_wrapper/include/flutter/method_call.h" +#include "flutter/shell/platform/common/client_wrapper/include/flutter/method_codec.h" + +namespace flutter { + +// An implementation of MethodCodec that uses JSON strings as the serialization. +class JsonMethodCodec : public MethodCodec { + public: + // Returns the shared instance of the codec. + static const JsonMethodCodec& GetInstance(); + + ~JsonMethodCodec() = default; + + // Prevent copying. + JsonMethodCodec(JsonMethodCodec const&) = delete; + JsonMethodCodec& operator=(JsonMethodCodec const&) = delete; + + protected: + // Instances should be obtained via GetInstance. + JsonMethodCodec() = default; + + // |flutter::MethodCodec| + std::unique_ptr> DecodeMethodCallInternal( + const uint8_t* message, + const size_t message_size) const override; + + // |flutter::MethodCodec| + std::unique_ptr> EncodeMethodCallInternal( + const MethodCall& method_call) const override; + + // |flutter::MethodCodec| + std::unique_ptr> EncodeSuccessEnvelopeInternal( + const rapidjson::Document* result) const override; + + // |flutter::MethodCodec| + std::unique_ptr> EncodeErrorEnvelopeInternal( + const std::string& error_code, + const std::string& error_message, + const rapidjson::Document* error_details) const override; + + // |flutter::MethodCodec| + bool DecodeAndProcessResponseEnvelopeInternal( + const uint8_t* response, + const size_t response_size, + MethodResult* result) const override; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_JSON_METHOD_CODEC_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/json_method_codec_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/json_method_codec_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4989192fab56e321ee43e74fe1360e4111cf4f0e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/json_method_codec_unittests.cc @@ -0,0 +1,161 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/json_method_codec.h" + +#include "flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// Returns true if the given method calls have the same method name, and their +// arguments have equivalent values. +bool MethodCallsAreEqual(const MethodCall& a, + const MethodCall& b) { + if (a.method_name() != b.method_name()) { + return false; + } + // Treat nullptr and Null as equivalent. + if ((!a.arguments() || a.arguments()->IsNull()) && + (!b.arguments() || b.arguments()->IsNull())) { + return true; + } + return *a.arguments() == *b.arguments(); +} + +} // namespace + +TEST(JsonMethodCodec, HandlesMethodCallsWithNullArguments) { + const JsonMethodCodec& codec = JsonMethodCodec::GetInstance(); + MethodCall call("hello", nullptr); + auto encoded = codec.EncodeMethodCall(call); + ASSERT_TRUE(encoded); + std::unique_ptr> decoded = + codec.DecodeMethodCall(*encoded); + ASSERT_TRUE(decoded); + EXPECT_TRUE(MethodCallsAreEqual(call, *decoded)); +} + +TEST(JsonMethodCodec, HandlesMethodCallsWithArgument) { + const JsonMethodCodec& codec = JsonMethodCodec::GetInstance(); + + auto arguments = std::make_unique(rapidjson::kArrayType); + auto& allocator = arguments->GetAllocator(); + arguments->PushBack(42, allocator); + arguments->PushBack("world", allocator); + MethodCall call("hello", std::move(arguments)); + auto encoded = codec.EncodeMethodCall(call); + ASSERT_TRUE(encoded); + std::unique_ptr> decoded = + codec.DecodeMethodCall(*encoded); + ASSERT_TRUE(decoded); + EXPECT_TRUE(MethodCallsAreEqual(call, *decoded)); +} + +TEST(JsonMethodCodec, HandlesSuccessEnvelopesWithNullResult) { + const JsonMethodCodec& codec = JsonMethodCodec::GetInstance(); + auto encoded = codec.EncodeSuccessEnvelope(); + ASSERT_TRUE(encoded); + std::vector bytes = {'[', 'n', 'u', 'l', 'l', ']'}; + EXPECT_EQ(*encoded, bytes); + + bool decoded_successfully = false; + MethodResultFunctions result_handler( + [&decoded_successfully](const rapidjson::Document* result) { + decoded_successfully = true; + EXPECT_EQ(result, nullptr); + }, + nullptr, nullptr); + codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), + &result_handler); + EXPECT_TRUE(decoded_successfully); +} + +TEST(JsonMethodCodec, HandlesSuccessEnvelopesWithResult) { + const JsonMethodCodec& codec = JsonMethodCodec::GetInstance(); + rapidjson::Document result; + result.SetInt(42); + auto encoded = codec.EncodeSuccessEnvelope(&result); + ASSERT_TRUE(encoded); + std::vector bytes = {'[', '4', '2', ']'}; + EXPECT_EQ(*encoded, bytes); + + bool decoded_successfully = false; + MethodResultFunctions result_handler( + [&decoded_successfully](const rapidjson::Document* result) { + decoded_successfully = true; + EXPECT_EQ(result->GetInt(), 42); + }, + nullptr, nullptr); + codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), + &result_handler); + EXPECT_TRUE(decoded_successfully); +} + +TEST(JsonMethodCodec, HandlesErrorEnvelopesWithNulls) { + const JsonMethodCodec& codec = JsonMethodCodec::GetInstance(); + auto encoded = codec.EncodeErrorEnvelope("errorCode"); + ASSERT_TRUE(encoded); + std::vector bytes = { + '[', '"', 'e', 'r', 'r', 'o', 'r', 'C', 'o', 'd', 'e', + '"', ',', '"', '"', ',', 'n', 'u', 'l', 'l', ']', + }; + EXPECT_EQ(*encoded, bytes); + + bool decoded_successfully = false; + MethodResultFunctions result_handler( + nullptr, + [&decoded_successfully](const std::string& code, + const std::string& message, + const rapidjson::Document* details) { + decoded_successfully = true; + EXPECT_EQ(code, "errorCode"); + EXPECT_EQ(message, ""); + EXPECT_EQ(details, nullptr); + }, + nullptr); + codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), + &result_handler); + EXPECT_TRUE(decoded_successfully); +} + +TEST(JsonMethodCodec, HandlesErrorEnvelopesWithDetails) { + const JsonMethodCodec& codec = JsonMethodCodec::GetInstance(); + // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) + rapidjson::Document details(rapidjson::kArrayType); + auto& allocator = details.GetAllocator(); + details.PushBack("a", allocator); + details.PushBack(42, allocator); + auto encoded = + codec.EncodeErrorEnvelope("errorCode", "something failed", &details); + ASSERT_NE(encoded.get(), nullptr); + std::vector bytes = { + '[', '"', 'e', 'r', 'r', 'o', 'r', 'C', 'o', 'd', 'e', '"', ',', '"', + 's', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g', ' ', 'f', 'a', 'i', 'l', + 'e', 'd', '"', ',', '[', '"', 'a', '"', ',', '4', '2', ']', ']', + }; + EXPECT_EQ(*encoded, bytes); + + bool decoded_successfully = false; + MethodResultFunctions result_handler( + nullptr, + [&decoded_successfully](const std::string& code, + const std::string& message, + const rapidjson::Document* details) { + decoded_successfully = true; + EXPECT_EQ(code, "errorCode"); + EXPECT_EQ(message, "something failed"); + EXPECT_TRUE(details->IsArray()); + EXPECT_EQ(std::string((*details)[0].GetString()), "a"); + EXPECT_EQ((*details)[1].GetInt(), 42); + }, + nullptr); + codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), + &result_handler); + EXPECT_TRUE(decoded_successfully); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/path_utils.cc b/flutter/engine/src/flutter/shell/platform/common/path_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..4e5690eb54fe4bc51d649c8ed096492b3de70efa --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/path_utils.cc @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/path_utils.h" + +#if defined(_WIN32) +#include +#elif defined(__linux__) +#include +#include +#endif + +namespace flutter { + +std::filesystem::path GetExecutableDirectory() { +#if defined(_WIN32) + wchar_t buffer[MAX_PATH]; + if (GetModuleFileName(nullptr, buffer, MAX_PATH) == 0) { + return std::filesystem::path(); + } + std::filesystem::path executable_path(buffer); + return executable_path.remove_filename(); +#elif defined(__linux__) + char buffer[PATH_MAX + 1]; + ssize_t length = readlink("/proc/self/exe", buffer, sizeof(buffer)); + if (length > PATH_MAX) { + return std::filesystem::path(); + } + std::filesystem::path executable_path(std::string(buffer, length)); + return executable_path.remove_filename(); +#else + return std::filesystem::path(); +#endif +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/path_utils.h b/flutter/engine/src/flutter/shell/platform/common/path_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..e608430473162ffd91d06f5d33984b7c330eb850 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/path_utils.h @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_COMMON_PATH_UTILS_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_PATH_UTILS_H_ + +#include + +namespace flutter { + +// Returns the path of the directory containing this executable, or an empty +// path if the directory cannot be found. +std::filesystem::path GetExecutableDirectory(); + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_PATH_UTILS_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/path_utils_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/path_utils_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4612f4060fd6f02c58abbb834014779838e55bd0 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/path_utils_unittests.cc @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/path_utils.h" + +#include "gtest/gtest.h" + +namespace flutter { + +// Tests that GetExecutableDirectory returns a valid, absolute path. +TEST(PathUtilsTest, ExecutableDirector) { + std::filesystem::path exe_directory = GetExecutableDirectory(); +#if defined(__linux__) || defined(_WIN32) + EXPECT_EQ(exe_directory.empty(), false); + EXPECT_EQ(exe_directory.is_absolute(), true); +#else + // On platforms where it's not implemented, it should indicate that + // by returning an empty path. + EXPECT_EQ(exe_directory.empty(), true); +#endif +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/platform_provided_menu.h b/flutter/engine/src/flutter/shell/platform/common/platform_provided_menu.h new file mode 100644 index 0000000000000000000000000000000000000000..ac23df33a65ec4f4bb39ac874d4b0af05bb2f35d --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/platform_provided_menu.h @@ -0,0 +1,52 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_COMMON_PLATFORM_PROVIDED_MENU_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_PLATFORM_PROVIDED_MENU_H_ + +namespace flutter { + +// Enumerates the provided menus that a platform may support. +// Must be kept in sync with the framework enum in widgets/menu.dart. +enum class PlatformProvidedMenu { + // orderFrontStandardAboutPanel macOS provided menu + kAbout, + + // terminate macOS provided menu + kQuit, + + // Services macOS provided submenu. + kServicesSubmenu, + + // hide macOS provided menu + kHide, + + // hideOtherApplications macOS provided menu + kHideOtherApplications, + + // unhideAllApplications macOS provided menu + kShowAllApplications, + + // startSpeaking macOS provided menu + kStartSpeaking, + + // stopSpeaking macOS provided menu + kStopSpeaking, + + // toggleFullScreen macOS provided menu + kToggleFullScreen, + + // performMiniaturize macOS provided menu + kMinimizeWindow, + + // performZoom macOS provided menu + kZoomWindow, + + // arrangeInFront macOS provided menu + kArrangeWindowsInFront, +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_PLATFORM_PROVIDED_MENU_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/test_accessibility_bridge.cc b/flutter/engine/src/flutter/shell/platform/common/test_accessibility_bridge.cc new file mode 100644 index 0000000000000000000000000000000000000000..aa1a9def262c663f8926d13a59e2a33e42e6eb38 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/test_accessibility_bridge.cc @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "test_accessibility_bridge.h" + +namespace flutter { + +std::shared_ptr +TestAccessibilityBridge::CreateFlutterPlatformNodeDelegate() { + return std::make_unique(); +}; + +void TestAccessibilityBridge::OnAccessibilityEvent( + ui::AXEventGenerator::TargetedEvent targeted_event) { + accessibility_events.push_back(targeted_event.event_params.event); +} + +void TestAccessibilityBridge::DispatchAccessibilityAction( + AccessibilityNodeId target, + FlutterSemanticsAction action, + fml::MallocMapping data) { + performed_actions.push_back(action); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/test_accessibility_bridge.h b/flutter/engine/src/flutter/shell/platform/common/test_accessibility_bridge.h new file mode 100644 index 0000000000000000000000000000000000000000..a9ce43269dd8763482b2653a612591ec7a0b0391 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/test_accessibility_bridge.h @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_COMMON_TEST_ACCESSIBILITY_BRIDGE_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_TEST_ACCESSIBILITY_BRIDGE_H_ + +#include "accessibility_bridge.h" + +namespace flutter { + +class TestAccessibilityBridge : public AccessibilityBridge { + public: + TestAccessibilityBridge() = default; + + void DispatchAccessibilityAction(AccessibilityNodeId target, + FlutterSemanticsAction action, + fml::MallocMapping data) override; + + std::vector accessibility_events; + std::vector performed_actions; + + protected: + void OnAccessibilityEvent( + ui::AXEventGenerator::TargetedEvent targeted_event) override; + + std::shared_ptr + CreateFlutterPlatformNodeDelegate() override; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_TEST_ACCESSIBILITY_BRIDGE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/text_editing_delta.cc b/flutter/engine/src/flutter/shell/platform/common/text_editing_delta.cc new file mode 100644 index 0000000000000000000000000000000000000000..600c29280218793f6506fb5a04afbcd4d5b3ae7a --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/text_editing_delta.cc @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/text_editing_delta.h" + +#include "flutter/fml/string_conversion.h" + +namespace flutter { + +TextEditingDelta::TextEditingDelta(const std::u16string& text_before_change, + const TextRange& range, + const std::u16string& text) + : old_text_(text_before_change), + delta_text_(text), + delta_start_(range.start()), + delta_end_(range.start() + range.length()) {} + +TextEditingDelta::TextEditingDelta(const std::string& text_before_change, + const TextRange& range, + const std::string& text) + : old_text_(fml::Utf8ToUtf16(text_before_change)), + delta_text_(fml::Utf8ToUtf16(text)), + delta_start_(range.start()), + delta_end_(range.start() + range.length()) {} + +TextEditingDelta::TextEditingDelta(const std::u16string& text) + : old_text_(text), delta_text_(u""), delta_start_(-1), delta_end_(-1) {} + +TextEditingDelta::TextEditingDelta(const std::string& text) + : old_text_(fml::Utf8ToUtf16(text)), + delta_text_(u""), + delta_start_(-1), + delta_end_(-1) {} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/text_editing_delta.h b/flutter/engine/src/flutter/shell/platform/common/text_editing_delta.h new file mode 100644 index 0000000000000000000000000000000000000000..90f7fd89f1952b8cd9c13de120837838ed7f12c9 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/text_editing_delta.h @@ -0,0 +1,77 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_COMMON_TEXT_EDITING_DELTA_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_TEXT_EDITING_DELTA_H_ + +#include + +#include "flutter/fml/string_conversion.h" +#include "flutter/shell/platform/common/text_range.h" + +namespace flutter { + +/// A change in the state of an input field. +struct TextEditingDelta { + TextEditingDelta(const std::u16string& text_before_change, + const TextRange& range, + const std::u16string& text); + + TextEditingDelta(const std::string& text_before_change, + const TextRange& range, + const std::string& text); + + explicit TextEditingDelta(const std::u16string& text); + + explicit TextEditingDelta(const std::string& text); + + virtual ~TextEditingDelta() = default; + + /// Get the old_text_ value. + /// + /// All strings are stored as UTF16 but converted to UTF8 when accessed. + std::string old_text() const { return fml::Utf16ToUtf8(old_text_); } + + /// Get the delta_text value. + /// + /// All strings are stored as UTF16 but converted to UTF8 when accessed. + std::string delta_text() const { return fml::Utf16ToUtf8(delta_text_); } + + /// Get the delta_start_ value. + int delta_start() const { return delta_start_; } + + /// Get the delta_end_ value. + int delta_end() const { return delta_end_; } + + bool operator==(const TextEditingDelta& rhs) const { + return old_text_ == rhs.old_text_ && delta_text_ == rhs.delta_text_ && + delta_start_ == rhs.delta_start_ && delta_end_ == rhs.delta_end_; + } + + bool operator!=(const TextEditingDelta& rhs) const { return !(*this == rhs); } + + TextEditingDelta(const TextEditingDelta& other) = default; + + TextEditingDelta& operator=(const TextEditingDelta& other) = default; + + private: + std::u16string old_text_; + std::u16string delta_text_; + int delta_start_; + int delta_end_; + + void set_old_text(const std::u16string& old_text) { old_text_ = old_text; } + + void set_delta_text(const std::u16string& delta_text) { + delta_text_ = delta_text; + } + + void set_delta_start(int delta_start) { delta_start_ = delta_start; } + + void set_delta_end(int delta_end) { delta_end_ = delta_end; } +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_TEXT_EDITING_DELTA_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/text_editing_delta_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/text_editing_delta_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..393c1a4a645631c99930220d6f880b9713c54bff --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/text_editing_delta_unittests.cc @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/text_editing_delta.h" + +#include "gtest/gtest.h" + +namespace flutter { + +TEST(TextEditingDeltaTest, TestTextEditingDeltaConstructor) { + // Here we are simulating inserting an "o" at the end of "hell". + std::string old_text = "hell"; + std::string replacement_text = "hello"; + TextRange range(0, 4); + + TextEditingDelta delta = TextEditingDelta(old_text, range, replacement_text); + + EXPECT_EQ(delta.old_text(), old_text); + EXPECT_EQ(delta.delta_text(), "hello"); + EXPECT_EQ(delta.delta_start(), 0); + EXPECT_EQ(delta.delta_end(), 4); +} + +TEST(TextEditingDeltaTest, TestTextEditingDeltaNonTextConstructor) { + // Here we are simulating inserting an "o" at the end of "hell". + std::string old_text = "hello"; + + TextEditingDelta delta = TextEditingDelta(old_text); + + EXPECT_EQ(delta.old_text(), old_text); + EXPECT_EQ(delta.delta_text(), ""); + EXPECT_EQ(delta.delta_start(), -1); + EXPECT_EQ(delta.delta_end(), -1); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/text_input_model.cc b/flutter/engine/src/flutter/shell/platform/common/text_input_model.cc new file mode 100644 index 0000000000000000000000000000000000000000..a21fe1ff3effa1d74f423806dcb2d56f076cece6 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/text_input_model.cc @@ -0,0 +1,308 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/text_input_model.h" + +#include +#include + +#include "flutter/fml/string_conversion.h" + +namespace flutter { + +namespace { + +// Returns true if |code_point| is a leading surrogate of a surrogate pair. +bool IsLeadingSurrogate(char32_t code_point) { + return (code_point & 0xFFFFFC00) == 0xD800; +} +// Returns true if |code_point| is a trailing surrogate of a surrogate pair. +bool IsTrailingSurrogate(char32_t code_point) { + return (code_point & 0xFFFFFC00) == 0xDC00; +} + +} // namespace + +TextInputModel::TextInputModel() = default; + +TextInputModel::~TextInputModel() = default; + +bool TextInputModel::SetText(const std::string& text, + const TextRange& selection, + const TextRange& composing_range) { + text_ = fml::Utf8ToUtf16(text); + if (!text_range().Contains(selection) || + !text_range().Contains(composing_range)) { + return false; + } + + selection_ = selection; + composing_range_ = composing_range; + composing_ = !composing_range.collapsed(); + return true; +} + +bool TextInputModel::SetSelection(const TextRange& range) { + if (composing_ && !range.collapsed()) { + return false; + } + if (!editable_range().Contains(range)) { + return false; + } + selection_ = range; + return true; +} + +bool TextInputModel::SetComposingRange(const TextRange& range, + size_t cursor_offset) { + if (!composing_ || !text_range().Contains(range)) { + return false; + } + composing_range_ = range; + selection_ = TextRange(range.start() + cursor_offset); + return true; +} + +void TextInputModel::BeginComposing() { + composing_ = true; + composing_range_ = TextRange(selection_.start()); +} + +void TextInputModel::UpdateComposingText(const std::u16string& text, + const TextRange& selection) { + // Preserve selection if we get a no-op update to the composing region. + if (text.length() == 0 && composing_range_.collapsed()) { + return; + } + const TextRange& rangeToDelete = + composing_range_.collapsed() ? selection_ : composing_range_; + text_.replace(rangeToDelete.start(), rangeToDelete.length(), text); + composing_range_.set_end(composing_range_.start() + text.length()); + selection_ = TextRange(selection.start() + composing_range_.start(), + selection.extent() + composing_range_.start()); +} + +void TextInputModel::UpdateComposingText(const std::u16string& text) { + UpdateComposingText(text, TextRange(text.length())); +} + +void TextInputModel::UpdateComposingText(const std::string& text) { + UpdateComposingText(fml::Utf8ToUtf16(text)); +} + +void TextInputModel::CommitComposing() { + // Preserve selection if no composing text was entered. + if (composing_range_.collapsed()) { + return; + } + composing_range_ = TextRange(composing_range_.end()); + selection_ = composing_range_; +} + +void TextInputModel::EndComposing() { + composing_ = false; + composing_range_ = TextRange(0); +} + +bool TextInputModel::DeleteSelected() { + if (selection_.collapsed()) { + return false; + } + size_t start = selection_.start(); + text_.erase(start, selection_.length()); + selection_ = TextRange(start); + if (composing_) { + // This occurs only immediately after composing has begun with a selection. + composing_range_ = selection_; + } + return true; +} + +void TextInputModel::AddCodePoint(char32_t c) { + if (c <= 0xFFFF) { + AddText(std::u16string({static_cast(c)})); + } else { + char32_t to_decompose = c - 0x10000; + AddText(std::u16string({ + // High surrogate. + static_cast((to_decompose >> 10) + 0xd800), + // Low surrogate. + static_cast((to_decompose % 0x400) + 0xdc00), + })); + } +} + +void TextInputModel::AddText(const std::u16string& text) { + DeleteSelected(); + if (composing_) { + // Delete the current composing text, set the cursor to composing start. + text_.erase(composing_range_.start(), composing_range_.length()); + selection_ = TextRange(composing_range_.start()); + composing_range_.set_end(composing_range_.start() + text.length()); + } + size_t position = selection_.position(); + text_.insert(position, text); + selection_ = TextRange(position + text.length()); +} + +void TextInputModel::AddText(const std::string& text) { + AddText(fml::Utf8ToUtf16(text)); +} + +bool TextInputModel::Backspace() { + if (DeleteSelected()) { + return true; + } + // There is no selection. Delete the preceding codepoint. + size_t position = selection_.position(); + if (position != editable_range().start()) { + int count = IsTrailingSurrogate(text_.at(position - 1)) ? 2 : 1; + text_.erase(position - count, count); + selection_ = TextRange(position - count); + if (composing_) { + composing_range_.set_end(composing_range_.end() - count); + } + return true; + } + return false; +} + +bool TextInputModel::Delete() { + if (DeleteSelected()) { + return true; + } + // There is no selection. Delete the preceding codepoint. + size_t position = selection_.position(); + if (position < editable_range().end()) { + int count = IsLeadingSurrogate(text_.at(position)) ? 2 : 1; + text_.erase(position, count); + if (composing_) { + composing_range_.set_end(composing_range_.end() - count); + } + return true; + } + return false; +} + +bool TextInputModel::DeleteSurrounding(int offset_from_cursor, int count) { + size_t max_pos = editable_range().end(); + size_t start = selection_.extent(); + if (offset_from_cursor < 0) { + for (int i = 0; i < -offset_from_cursor; i++) { + // If requested start is before the available text then reduce the + // number of characters to delete. + if (start == editable_range().start()) { + count = i; + break; + } + start -= IsTrailingSurrogate(text_.at(start - 1)) ? 2 : 1; + } + } else { + for (int i = 0; i < offset_from_cursor && start != max_pos; i++) { + start += IsLeadingSurrogate(text_.at(start)) ? 2 : 1; + } + } + + auto end = start; + for (int i = 0; i < count && end != max_pos; i++) { + end += IsLeadingSurrogate(text_.at(start)) ? 2 : 1; + } + + if (start == end) { + return false; + } + + auto deleted_length = end - start; + text_.erase(start, deleted_length); + + // Cursor moves only if deleted area is before it. + selection_ = TextRange(offset_from_cursor <= 0 ? start : selection_.start()); + + // Adjust composing range. + if (composing_) { + composing_range_.set_end(composing_range_.end() - deleted_length); + } + return true; +} + +bool TextInputModel::MoveCursorToBeginning() { + size_t min_pos = editable_range().start(); + if (selection_.collapsed() && selection_.position() == min_pos) { + return false; + } + selection_ = TextRange(min_pos); + return true; +} + +bool TextInputModel::MoveCursorToEnd() { + size_t max_pos = editable_range().end(); + if (selection_.collapsed() && selection_.position() == max_pos) { + return false; + } + selection_ = TextRange(max_pos); + return true; +} + +bool TextInputModel::SelectToBeginning() { + size_t min_pos = editable_range().start(); + if (selection_.collapsed() && selection_.position() == min_pos) { + return false; + } + selection_ = TextRange(selection_.base(), min_pos); + return true; +} + +bool TextInputModel::SelectToEnd() { + size_t max_pos = editable_range().end(); + if (selection_.collapsed() && selection_.position() == max_pos) { + return false; + } + selection_ = TextRange(selection_.base(), max_pos); + return true; +} + +bool TextInputModel::MoveCursorForward() { + // If there's a selection, move to the end of the selection. + if (!selection_.collapsed()) { + selection_ = TextRange(selection_.end()); + return true; + } + // Otherwise, move the cursor forward. + size_t position = selection_.position(); + if (position != editable_range().end()) { + int count = IsLeadingSurrogate(text_.at(position)) ? 2 : 1; + selection_ = TextRange(position + count); + return true; + } + return false; +} + +bool TextInputModel::MoveCursorBack() { + // If there's a selection, move to the beginning of the selection. + if (!selection_.collapsed()) { + selection_ = TextRange(selection_.start()); + return true; + } + // Otherwise, move the cursor backward. + size_t position = selection_.position(); + if (position != editable_range().start()) { + int count = IsTrailingSurrogate(text_.at(position - 1)) ? 2 : 1; + selection_ = TextRange(position - count); + return true; + } + return false; +} + +std::string TextInputModel::GetText() const { + return fml::Utf16ToUtf8(text_); +} + +int TextInputModel::GetCursorOffset() const { + // Measure the length of the current text up to the selection extent. + // There is probably a much more efficient way of doing this. + auto leading_text = text_.substr(0, selection_.extent()); + return fml::Utf16ToUtf8(leading_text).size(); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/text_input_model.h b/flutter/engine/src/flutter/shell/platform/common/text_input_model.h new file mode 100644 index 0000000000000000000000000000000000000000..2546e56bbe84e67d4cfca7662bdff95ce44420cb --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/text_input_model.h @@ -0,0 +1,234 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_COMMON_TEXT_INPUT_MODEL_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_TEXT_INPUT_MODEL_H_ + +#include +#include + +#include "flutter/shell/platform/common/text_range.h" + +namespace flutter { + +// Handles underlying text input state, using a simple ASCII model. +// +// Ignores special states like "insert mode" for now. +class TextInputModel { + public: + TextInputModel(); + virtual ~TextInputModel(); + + // Sets the text, as well as the selection and the composing region. + // + // This method is typically used to update the TextInputModel's editing state + // when the Flutter framework sends its latest text editing state. + bool SetText(const std::string& text, + const TextRange& selection = TextRange(0), + const TextRange& composing_range = TextRange(0)); + + // Attempts to set the text selection. + // + // Returns false if the selection is not within the bounds of the text. + // While in composing mode, the selection is restricted to the composing + // range; otherwise, it is restricted to the length of the text. + // + // To update both the text and the selection/composing range within the text + // (for instance, when the framework sends its latest text editing state), + // call |SetText| instead. + bool SetSelection(const TextRange& range); + + // Attempts to set the composing range. + // + // Returns false if the range or offset are out of range for the text, or if + // the offset is outside the composing range. + // + // To update both the text and the selection/composing range within the text + // (for instance, when the framework sends its latest text editing state), + // call |SetText| instead. + bool SetComposingRange(const TextRange& range, size_t cursor_offset); + + // Begins IME composing mode. + // + // Resets the composing base and extent to the selection start. The existing + // selection is preserved in case composing is aborted with no changes. Until + // |EndComposing| is called, any further changes to selection base and extent + // are restricted to the composing range. + void BeginComposing(); + + // Replaces the composing range with new UTF-16 text, and sets the selection. + // + // The given |text| replaces text within the current composing range, or the + // current selection if the text wasn't composing. The composing range is + // adjusted to the length of |text|, and the |selection| describes the new + // selection range, relative to the start of the new composing range. + void UpdateComposingText(const std::u16string& text, + const TextRange& selection); + + // Replaces the composing range with new UTF-16 text and sets the selection to + // the end of the composing text. + void UpdateComposingText(const std::u16string& text); + + // Replaces the composing range with new UTF-8 text. + // + // If a selection of non-zero length exists, it is deleted if the composing + // text is non-empty. The composing range is adjusted to the length of + // |text| and the selection base and offset are set to the end of the + // composing range. + void UpdateComposingText(const std::string& text); + + // Commits composing range to the string. + // + // Causes the composing base and extent to be collapsed to the end of the + // range. + void CommitComposing(); + + // Ends IME composing mode. + // + // Collapses the composing base and offset to 0. + void EndComposing(); + + // Adds a Unicode code point. + // + // Either appends after the cursor (when selection base and extent are the + // same), or deletes the selected text, replacing it with the given + // code point. + void AddCodePoint(char32_t c); + + // Adds UTF-16 text. + // + // Either appends after the cursor (when selection base and extent are the + // same), or deletes the selected text, replacing it with the given text. + void AddText(const std::u16string& text); + + // Adds UTF-8 text. + // + // Either appends after the cursor (when selection base and extent are the + // same), or deletes the selected text, replacing it with the given text. + void AddText(const std::string& text); + + // Deletes either the selection, or one character ahead of the cursor. + // + // Deleting one character ahead of the cursor occurs when the selection base + // and extent are the same. When composing is active, deletions are + // restricted to text between the composing base and extent. + // + // Returns true if any deletion actually occurred. + bool Delete(); + + // Deletes text near the cursor. + // + // A section is made starting at |offset_from_cursor| code points past the + // cursor (negative values go before the cursor). |count| code points are + // removed. The selection may go outside the bounds of the available text and + // will result in only the part selection that covers the available text + // being deleted. The existing selection is ignored and removed after this + // operation. When composing is active, deletions are restricted to the + // composing range. + // + // Returns true if any deletion actually occurred. + bool DeleteSurrounding(int offset_from_cursor, int count); + + // Deletes either the selection, or one character behind the cursor. + // + // Deleting one character behind the cursor occurs when the selection base + // and extent are the same. When composing is active, deletions are + // restricted to the text between the composing base and extent. + // + // Returns true if any deletion actually occurred. + bool Backspace(); + + // Attempts to move the cursor backward. + // + // Returns true if the cursor could be moved. If a selection is active, moves + // to the start of the selection. If composing is active, motion is + // restricted to the composing range. + bool MoveCursorBack(); + + // Attempts to move the cursor forward. + // + // Returns true if the cursor could be moved. If a selection is active, moves + // to the end of the selection. If composing is active, motion is restricted + // to the composing range. + bool MoveCursorForward(); + + // Attempts to move the cursor to the beginning. + // + // If composing is active, the cursor is moved to the beginning of the + // composing range; otherwise, it is moved to the beginning of the text. If + // composing is active, motion is restricted to the composing range. + // + // Returns true if the cursor could be moved. + bool MoveCursorToBeginning(); + + // Attempts to move the cursor to the end. + // + // If composing is active, the cursor is moved to the end of the composing + // range; otherwise, it is moved to the end of the text. If composing is + // active, motion is restricted to the composing range. + // + // Returns true if the cursor could be moved. + bool MoveCursorToEnd(); + + // Attempts to select text from the cursor position to the beginning. + // + // If composing is active, the selection is applied to the beginning of the + // composing range; otherwise, it is applied to the beginning of the text. + // + // Returns true if the selection could be applied. + bool SelectToBeginning(); + + // Attempts to select text from the cursor position to the end. + // + // If composing is active, the selection is applied to the end of the + // composing range; otherwise, it is moved to the end of the text. + // + // Returns true if the selection could be applied. + bool SelectToEnd(); + + // Gets the current text as UTF-8. + std::string GetText() const; + + // Gets the cursor position as a byte offset in UTF-8 string returned from + // GetText(). + int GetCursorOffset() const; + + // Returns a range covering the entire text. + TextRange text_range() const { return TextRange(0, text_.length()); } + + // The current selection. + TextRange selection() const { return selection_; } + + // The composing range. + // + // If not in composing mode, returns a collapsed range at position 0. + TextRange composing_range() const { return composing_range_; } + + // Whether multi-step input composing mode is active. + bool composing() const { return composing_; } + + private: + // Deletes the current selection, if any. + // + // Returns true if any text is deleted. The selection base and extent are + // reset to the start of the selected range. + bool DeleteSelected(); + + // Returns the currently editable text range. + // + // In composing mode, returns the composing range; otherwise, returns a range + // covering the entire text. + TextRange editable_range() const { + return composing_ ? composing_range_ : text_range(); + } + + std::u16string text_; + TextRange selection_ = TextRange(0); + TextRange composing_range_ = TextRange(0); + bool composing_ = false; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_TEXT_INPUT_MODEL_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/text_input_model_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/text_input_model_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e8ed8f218a4ebda437c2ca636c8584acb71f1c2 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/text_input_model_unittests.cc @@ -0,0 +1,1732 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/text_input_model.h" + +#include +#include +#include + +#include "gtest/gtest.h" + +namespace flutter { + +TEST(TextInputModel, SetText) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetTextWideCharacters) { + auto model = std::make_unique(); + model->SetText("😄🙃🤪🧐"); + EXPECT_STREQ(model->GetText().c_str(), "😄🙃🤪🧐"); +} + +TEST(TextInputModel, SetTextEmpty) { + auto model = std::make_unique(); + model->SetText(""); + EXPECT_STREQ(model->GetText().c_str(), ""); +} + +TEST(TextInputModel, SetTextReplaceText) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); + model->SetText(""); + EXPECT_STREQ(model->GetText().c_str(), ""); +} + +TEST(TextInputModel, SetTextResetsSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(3))); + EXPECT_EQ(model->selection(), TextRange(3)); + model->SetText("FGHJI"); + EXPECT_EQ(model->selection(), TextRange(0)); +} + +TEST(TextInputModel, SetSelectionStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionComposingStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->SetSelection(TextRange(1))); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionComposingMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(5))); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionComposingEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->SetSelection(TextRange(4))); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionWthExtent) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + EXPECT_EQ(model->selection(), TextRange(1, 4)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionWthExtentComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_FALSE(model->SetSelection(TextRange(1, 4))); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionReverseExtent) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + EXPECT_EQ(model->selection(), TextRange(4, 1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionReverseExtentComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_FALSE(model->SetSelection(TextRange(4, 1))); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetSelectionOutsideString) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_FALSE(model->SetSelection(TextRange(4, 6))); + EXPECT_FALSE(model->SetSelection(TextRange(5, 6))); + EXPECT_FALSE(model->SetSelection(TextRange(6))); +} + +TEST(TextInputModel, SetSelectionOutsideComposingRange) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_FALSE(model->SetSelection(TextRange(0))); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_FALSE(model->SetSelection(TextRange(5))); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); +} + +TEST(TextInputModel, SetComposingRangeStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(0, 0), 0)); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetComposingRangeMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(2, 2), 0)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(2)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetComposingRangeEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(5, 5), 0)); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(5)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetComposingRangeWithExtent) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 3)); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetComposingRangeReverseExtent) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 3)); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SetComposingRangeOutsideString) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_FALSE(model->SetComposingRange(TextRange(4, 6), 0)); + EXPECT_FALSE(model->SetComposingRange(TextRange(5, 6), 0)); + EXPECT_FALSE(model->SetComposingRange(TextRange(6, 6), 0)); +} + +// Composing sequence with no initial selection and no text input. +TEST(TextInputModel, CommitComposingNoTextWithNoSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->SetSelection(TextRange(0)); + + // Verify no changes on BeginComposing. + model->BeginComposing(); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); + + // Verify no changes on CommitComposing. + model->CommitComposing(); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); + + // Verify no changes on CommitComposing. + model->EndComposing(); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +// Composing sequence with an initial selection and no text input. +TEST(TextInputModel, CommitComposingNoTextWithSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->SetSelection(TextRange(1, 3)); + + // Verify no changes on BeginComposing. + model->BeginComposing(); + EXPECT_EQ(model->selection(), TextRange(1, 3)); + EXPECT_EQ(model->composing_range(), TextRange(1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); + + // Verify no changes on CommitComposing. + model->CommitComposing(); + EXPECT_EQ(model->selection(), TextRange(1, 3)); + EXPECT_EQ(model->composing_range(), TextRange(1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); + + // Verify no changes on CommitComposing. + model->EndComposing(); + EXPECT_EQ(model->selection(), TextRange(1, 3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +// Composing sequence with no initial selection. +TEST(TextInputModel, CommitComposingTextWithNoSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->SetSelection(TextRange(1)); + + // Verify no changes on BeginComposing. + model->BeginComposing(); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); + + // Verify selection base, extent and composing extent increment as text is + // entered. Verify composing base does not change. + model->UpdateComposingText("つ"); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "AつBCDE"); + model->UpdateComposingText("つる"); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(1, 3)); + EXPECT_STREQ(model->GetText().c_str(), "AつるBCDE"); + + // Verify that cursor position is set to correct offset from composing base. + model->UpdateComposingText("鶴"); + EXPECT_TRUE(model->SetSelection(TextRange(1))); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴BCDE"); + + // Verify composing base is set to composing extent on commit. + model->CommitComposing(); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(2)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴BCDE"); + + // Verify that further text entry increments the selection base, extent and + // the composing extent. Verify that composing base does not change. + model->UpdateComposingText("が"); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(2, 3)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴がBCDE"); + + // Verify composing base is set to composing extent on commit. + model->CommitComposing(); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(3)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴がBCDE"); + + // Verify no changes on EndComposing. + model->EndComposing(); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴がBCDE"); +} + +// Composing sequence with an initial selection. +TEST(TextInputModel, CommitComposingTextWithSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->SetSelection(TextRange(1, 3)); + + // Verify no changes on BeginComposing. + model->BeginComposing(); + EXPECT_EQ(model->selection(), TextRange(1, 3)); + EXPECT_EQ(model->composing_range(), TextRange(1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); + + // Verify selection is replaced and selection base, extent and composing + // extent increment to the position immediately after the composing text. + // Verify composing base does not change. + model->UpdateComposingText("つ"); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "AつDE"); + + // Verify that further text entry increments the selection base, extent and + // the composing extent. Verify that composing base does not change. + model->UpdateComposingText("つる"); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(1, 3)); + EXPECT_STREQ(model->GetText().c_str(), "AつるDE"); + + // Verify that cursor position is set to correct offset from composing base. + model->UpdateComposingText("鶴"); + EXPECT_TRUE(model->SetSelection(TextRange(1))); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴DE"); + + // Verify composing base is set to composing extent on commit. + model->CommitComposing(); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(2)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴DE"); + + // Verify that further text entry increments the selection base, extent and + // the composing extent. Verify that composing base does not change. + model->UpdateComposingText("が"); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(2, 3)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴がDE"); + + // Verify composing base is set to composing extent on commit. + model->CommitComposing(); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(3)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴がDE"); + + // Verify no changes on EndComposing. + model->EndComposing(); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "A鶴がDE"); +} + +TEST(TextInputModel, UpdateComposingRemovesLastComposingCharacter) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + model->SetComposingRange(TextRange(1, 2), 1); + model->UpdateComposingText(""); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1)); + model->SetText("ACDE"); +} + +TEST(TextInputModel, UpdateSelectionWhileComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + model->SetComposingRange(TextRange(4, 5), 1); + model->UpdateComposingText(u"ぴょんぴょん", TextRange(3, 6)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDぴょんぴょん"); + EXPECT_EQ(model->selection(), TextRange(7, 10)); + EXPECT_EQ(model->composing_range(), TextRange(4, 10)); +} + +TEST(TextInputModel, AddCodePoint) { + auto model = std::make_unique(); + model->AddCodePoint('A'); + model->AddCodePoint('B'); + model->AddCodePoint(0x1f604); + model->AddCodePoint('D'); + model->AddCodePoint('E'); + EXPECT_EQ(model->selection(), TextRange(6)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AB😄DE"); +} + +TEST(TextInputModel, AddCodePointSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + model->AddCodePoint('x'); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AxE"); +} + +TEST(TextInputModel, AddCodePointReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + model->AddCodePoint('x'); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AxE"); +} + +TEST(TextInputModel, AddCodePointSelectionWideCharacter) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + model->AddCodePoint(0x1f604); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "A😄E"); +} + +TEST(TextInputModel, AddCodePointReverseSelectionWideCharacter) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + model->AddCodePoint(0x1f604); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "A😄E"); +} + +TEST(TextInputModel, AddText) { + auto model = std::make_unique(); + model->AddText(u"ABCDE"); + model->AddText("😄"); + model->AddText("FGHIJ"); + EXPECT_EQ(model->selection(), TextRange(12)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE😄FGHIJ"); +} + +TEST(TextInputModel, AddTextSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + model->AddText("xy"); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AxyE"); +} + +TEST(TextInputModel, AddTextReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + model->AddText("xy"); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AxyE"); +} + +TEST(TextInputModel, AddTextSelectionWideCharacter) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + model->AddText(u"😄🙃"); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "A😄🙃E"); +} + +TEST(TextInputModel, AddTextReverseSelectionWideCharacter) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + model->AddText(u"😄🙃"); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "A😄🙃E"); +} + +TEST(TextInputModel, DeleteStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "BCDE"); +} + +TEST(TextInputModel, DeleteMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABDE"); +} + +TEST(TextInputModel, DeleteEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(5))); + ASSERT_FALSE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, DeleteWideCharacters) { + auto model = std::make_unique(); + model->SetText("😄🙃🤪🧐"); + EXPECT_TRUE(model->SetSelection(TextRange(4))); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "😄🙃🧐"); +} + +TEST(TextInputModel, DeleteSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AE"); +} + +TEST(TextInputModel, DeleteReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AE"); +} + +TEST(TextInputModel, DeleteStartComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 3)); + EXPECT_STREQ(model->GetText().c_str(), "ACDE"); +} + +TEST(TextInputModel, DeleteStartReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 0)); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(3, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ACDE"); +} + +TEST(TextInputModel, DeleteMiddleComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(1, 3)); + EXPECT_STREQ(model->GetText().c_str(), "ABDE"); +} + +TEST(TextInputModel, DeleteMiddleReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 1)); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(3, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABDE"); +} + +TEST(TextInputModel, DeleteEndComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 3)); + ASSERT_FALSE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, DeleteEndReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 3)); + ASSERT_FALSE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, DeleteSurroundingAtCursor) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->DeleteSurrounding(0, 1)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABDE"); +} + +TEST(TextInputModel, DeleteSurroundingAtCursorComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + EXPECT_TRUE(model->DeleteSurrounding(0, 1)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(1, 3)); + EXPECT_STREQ(model->GetText().c_str(), "ABDE"); +} + +TEST(TextInputModel, DeleteSurroundingAtCursorAll) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->DeleteSurrounding(0, 3)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AB"); +} + +TEST(TextInputModel, DeleteSurroundingAtCursorAllComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + EXPECT_TRUE(model->DeleteSurrounding(0, 2)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "ABE"); +} + +TEST(TextInputModel, DeleteSurroundingAtCursorGreedy) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->DeleteSurrounding(0, 4)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AB"); +} + +TEST(TextInputModel, DeleteSurroundingAtCursorGreedyComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + EXPECT_TRUE(model->DeleteSurrounding(0, 4)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "ABE"); +} + +TEST(TextInputModel, DeleteSurroundingBeforeCursor) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->DeleteSurrounding(-1, 1)); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ACDE"); +} + +TEST(TextInputModel, DeleteSurroundingBeforeCursorComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 2)); + EXPECT_TRUE(model->DeleteSurrounding(-1, 1)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(1, 3)); + EXPECT_STREQ(model->GetText().c_str(), "ABDE"); +} + +TEST(TextInputModel, DeleteSurroundingBeforeCursorAll) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->DeleteSurrounding(-2, 2)); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "CDE"); +} + +TEST(TextInputModel, DeleteSurroundingBeforeCursorAllComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 2)); + EXPECT_TRUE(model->DeleteSurrounding(-2, 2)); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "ADE"); +} + +TEST(TextInputModel, DeleteSurroundingBeforeCursorGreedy) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->DeleteSurrounding(-3, 3)); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "CDE"); +} + +TEST(TextInputModel, DeleteSurroundingBeforeCursorGreedyComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 2)); + EXPECT_TRUE(model->DeleteSurrounding(-3, 3)); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "ADE"); +} + +TEST(TextInputModel, DeleteSurroundingAfterCursor) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->DeleteSurrounding(1, 1)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCE"); +} + +TEST(TextInputModel, DeleteSurroundingAfterCursorComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->DeleteSurrounding(1, 1)); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 3)); + EXPECT_STREQ(model->GetText().c_str(), "ABDE"); +} + +TEST(TextInputModel, DeleteSurroundingAfterCursorAll) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->DeleteSurrounding(1, 2)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABC"); +} + +TEST(TextInputModel, DeleteSurroundingAfterCursorAllComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->DeleteSurrounding(1, 2)); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "ABE"); +} + +TEST(TextInputModel, DeleteSurroundingAfterCursorGreedy) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->DeleteSurrounding(1, 3)); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABC"); +} + +TEST(TextInputModel, DeleteSurroundingAfterCursorGreedyComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->DeleteSurrounding(1, 3)); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 2)); + EXPECT_STREQ(model->GetText().c_str(), "ABE"); +} + +TEST(TextInputModel, DeleteSurroundingSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2, 3))); + EXPECT_TRUE(model->DeleteSurrounding(0, 1)); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCE"); +} + +TEST(TextInputModel, DeleteSurroundingReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 3))); + EXPECT_TRUE(model->DeleteSurrounding(0, 1)); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCE"); +} + +TEST(TextInputModel, BackspaceStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + ASSERT_FALSE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, BackspaceMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + ASSERT_TRUE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ACDE"); +} + +TEST(TextInputModel, BackspaceEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(5))); + ASSERT_TRUE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCD"); +} + +TEST(TextInputModel, BackspaceWideCharacters) { + auto model = std::make_unique(); + model->SetText("😄🙃🤪🧐"); + EXPECT_TRUE(model->SetSelection(TextRange(4))); + ASSERT_TRUE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "😄🤪🧐"); +} + +TEST(TextInputModel, BackspaceSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AE"); +} + +TEST(TextInputModel, BackspaceReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + ASSERT_TRUE(model->Delete()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "AE"); +} + +TEST(TextInputModel, BackspaceStartComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + ASSERT_FALSE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, BackspaceStartReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 0)); + ASSERT_FALSE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, BackspaceMiddleComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + ASSERT_TRUE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 3)); + EXPECT_STREQ(model->GetText().c_str(), "ACDE"); +} + +TEST(TextInputModel, BackspaceMiddleReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 1)); + ASSERT_TRUE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(3, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ACDE"); +} + +TEST(TextInputModel, BackspaceEndComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 3)); + ASSERT_TRUE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(1, 3)); + EXPECT_STREQ(model->GetText().c_str(), "ABCE"); +} + +TEST(TextInputModel, BackspaceEndReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 3)); + ASSERT_TRUE(model->Backspace()); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(3, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCE"); +} + +TEST(TextInputModel, MoveCursorForwardStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(5))); + EXPECT_FALSE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardWideCharacters) { + auto model = std::make_unique(); + model->SetText("😄🙃🤪🧐"); + EXPECT_TRUE(model->SetSelection(TextRange(4))); + ASSERT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(6)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "😄🙃🤪🧐"); +} + +TEST(TextInputModel, MoveCursorForwardSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardStartComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardStartReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 0)); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardMiddleComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardMiddleReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 1)); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardEndComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 3)); + EXPECT_FALSE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorForwardEndReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 3)); + EXPECT_FALSE(model->MoveCursorForward()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + EXPECT_FALSE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(5))); + EXPECT_TRUE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackWideCharacters) { + auto model = std::make_unique(); + model->SetText("😄🙃🤪🧐"); + EXPECT_TRUE(model->SetSelection(TextRange(4))); + ASSERT_TRUE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(2)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "😄🙃🤪🧐"); +} + +TEST(TextInputModel, MoveCursorBackSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + EXPECT_TRUE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + EXPECT_TRUE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackStartComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->SetSelection(TextRange(1))); + EXPECT_FALSE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackStartReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 0)); + EXPECT_TRUE(model->SetSelection(TextRange(1))); + EXPECT_FALSE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackMiddleComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + EXPECT_TRUE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackMiddleReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 1)); + EXPECT_TRUE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackEndComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 3)); + EXPECT_TRUE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorBackEndReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 3)); + EXPECT_TRUE(model->MoveCursorBack()); + EXPECT_EQ(model->selection(), TextRange(3)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + EXPECT_FALSE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + EXPECT_FALSE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(2, 0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(5))); + EXPECT_TRUE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(5))); + EXPECT_TRUE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(5, 0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + EXPECT_TRUE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + EXPECT_TRUE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1, 0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + EXPECT_TRUE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + EXPECT_TRUE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(4, 0)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningStartComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_FALSE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningStartComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_FALSE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningStartReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 0)); + EXPECT_FALSE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningStartReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 0)); + EXPECT_FALSE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningMiddleComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + EXPECT_TRUE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningMiddleComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + EXPECT_TRUE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(2, 1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningMiddleReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 1)); + EXPECT_TRUE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningMiddleReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 1)); + EXPECT_TRUE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(2, 1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningEndComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 3)); + EXPECT_TRUE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningEndComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 3)); + EXPECT_TRUE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToBeginningEndReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 3)); + EXPECT_TRUE(model->MoveCursorToBeginning()); + EXPECT_EQ(model->selection(), TextRange(1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToBeginningEndReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 3)); + EXPECT_TRUE(model->SelectToBeginning()); + EXPECT_EQ(model->selection(), TextRange(4, 1)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + EXPECT_TRUE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndStart) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + EXPECT_TRUE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(0, 5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndMiddle) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(2))); + EXPECT_TRUE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(2, 5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(5))); + EXPECT_FALSE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndEnd) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(5))); + EXPECT_FALSE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + EXPECT_TRUE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + EXPECT_TRUE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(1, 5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + EXPECT_TRUE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + EXPECT_TRUE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(4, 5)); + EXPECT_EQ(model->composing_range(), TextRange(0)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndStartComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndStartComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(1, 4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndStartReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndStartReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 0)); + EXPECT_TRUE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(1, 4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndMiddleComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + EXPECT_TRUE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndMiddleComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 1)); + EXPECT_TRUE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(2, 4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndMiddleReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 1)); + EXPECT_TRUE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndMiddleReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 1)); + EXPECT_TRUE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(2, 4)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndEndComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 3)); + EXPECT_FALSE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndEndComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 3)); + EXPECT_FALSE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(1, 4)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, MoveCursorToEndEndReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 3)); + EXPECT_FALSE(model->MoveCursorToEnd()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, SelectToEndEndReverseComposing) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + model->BeginComposing(); + EXPECT_TRUE(model->SetComposingRange(TextRange(4, 1), 3)); + EXPECT_FALSE(model->SelectToEnd()); + EXPECT_EQ(model->selection(), TextRange(4)); + EXPECT_EQ(model->composing_range(), TextRange(4, 1)); + EXPECT_STREQ(model->GetText().c_str(), "ABCDE"); +} + +TEST(TextInputModel, GetCursorOffset) { + auto model = std::make_unique(); + // These characters take 1, 2, 3 and 4 bytes in UTF-8. + model->SetText("$¢€𐍈"); + EXPECT_TRUE(model->SetSelection(TextRange(0))); + EXPECT_EQ(model->GetCursorOffset(), 0); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->GetCursorOffset(), 1); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->GetCursorOffset(), 3); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->GetCursorOffset(), 6); + EXPECT_TRUE(model->MoveCursorForward()); + EXPECT_EQ(model->GetCursorOffset(), 10); +} + +TEST(TextInputModel, GetCursorOffsetSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(1, 4))); + EXPECT_EQ(model->GetCursorOffset(), 4); +} + +TEST(TextInputModel, GetCursorOffsetReverseSelection) { + auto model = std::make_unique(); + model->SetText("ABCDE"); + EXPECT_TRUE(model->SetSelection(TextRange(4, 1))); + EXPECT_EQ(model->GetCursorOffset(), 1); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/common/text_range.h b/flutter/engine/src/flutter/shell/platform/common/text_range.h new file mode 100644 index 0000000000000000000000000000000000000000..f1168942b0b70c62ffed0cb507af535e7281208f --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/text_range.h @@ -0,0 +1,103 @@ +// 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_COMMON_TEXT_RANGE_H_ +#define FLUTTER_SHELL_PLATFORM_COMMON_TEXT_RANGE_H_ + +#include + +#include "flutter/fml/logging.h" + +namespace flutter { + +// A directional range of text. +// +// A |TextRange| describes a range of text with |base| and |extent| positions. +// In the case where |base| == |extent|, the range is said to be collapsed, and +// when |base| > |extent|, the range is said to be reversed. +class TextRange { + public: + explicit TextRange(size_t position) : base_(position), extent_(position) {} + explicit TextRange(size_t base, size_t extent) + : base_(base), extent_(extent) {} + TextRange(const TextRange&) = default; + TextRange& operator=(const TextRange&) = default; + + virtual ~TextRange() = default; + + // The base position of the range. + size_t base() const { return base_; } + + // Sets the base position of the range. + void set_base(size_t pos) { base_ = pos; } + + // The extent position of the range. + size_t extent() const { return extent_; } + + // Sets the extent position of the range. + void set_extent(size_t pos) { extent_ = pos; } + + // The lesser of the base and extent positions. + size_t start() const { return std::min(base_, extent_); } + + // Sets the start position of the range. + void set_start(size_t pos) { + if (base_ <= extent_) { + base_ = pos; + } else { + extent_ = pos; + } + } + + // The greater of the base and extent positions. + size_t end() const { return std::max(base_, extent_); } + + // Sets the end position of the range. + void set_end(size_t pos) { + if (base_ <= extent_) { + extent_ = pos; + } else { + base_ = pos; + } + } + + // The position of a collapsed range. + // + // Asserts that the range is of length 0. + size_t position() const { + FML_DCHECK(base_ == extent_); + return extent_; + } + + // The length of the range. + size_t length() const { return end() - start(); } + + // Returns true if the range is of length 0. + bool collapsed() const { return base_ == extent_; } + + // Returns true if the base is greater than the extent. + bool reversed() const { return base_ > extent_; } + + // Returns true if |position| is contained within the range. + bool Contains(size_t position) const { + return position >= start() && position <= end(); + } + + // Returns true if |range| is contained within the range. + bool Contains(const TextRange& range) const { + return range.start() >= start() && range.end() <= end(); + } + + bool operator==(const TextRange& other) const { + return base_ == other.base_ && extent_ == other.extent_; + } + + private: + size_t base_; + size_t extent_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_COMMON_TEXT_RANGE_H_ diff --git a/flutter/engine/src/flutter/shell/platform/common/text_range_unittests.cc b/flutter/engine/src/flutter/shell/platform/common/text_range_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..6fe20ddfda0d9f942008e1cbdc429d99f0fd8b4e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/common/text_range_unittests.cc @@ -0,0 +1,248 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/common/text_range.h" + +#include "gtest/gtest.h" + +namespace flutter { + +TEST(TextRange, TextRangeFromPositionZero) { + TextRange range(0); + EXPECT_EQ(range.base(), size_t(0)); + EXPECT_EQ(range.extent(), size_t(0)); + EXPECT_EQ(range.start(), size_t(0)); + EXPECT_EQ(range.end(), size_t(0)); + EXPECT_EQ(range.length(), size_t(0)); + EXPECT_EQ(range.position(), size_t(0)); + EXPECT_TRUE(range.collapsed()); +} + +TEST(TextRange, TextRangeFromPositionNonZero) { + TextRange range(3); + EXPECT_EQ(range.base(), size_t(3)); + EXPECT_EQ(range.extent(), size_t(3)); + EXPECT_EQ(range.start(), size_t(3)); + EXPECT_EQ(range.end(), size_t(3)); + EXPECT_EQ(range.length(), size_t(0)); + EXPECT_EQ(range.position(), size_t(3)); + EXPECT_TRUE(range.collapsed()); +} + +TEST(TextRange, TextRangeFromRange) { + TextRange range(3, 7); + EXPECT_EQ(range.base(), size_t(3)); + EXPECT_EQ(range.extent(), size_t(7)); + EXPECT_EQ(range.start(), size_t(3)); + EXPECT_EQ(range.end(), size_t(7)); + EXPECT_EQ(range.length(), size_t(4)); + EXPECT_FALSE(range.collapsed()); +} + +TEST(TextRange, TextRangeFromReversedRange) { + TextRange range(7, 3); + EXPECT_EQ(range.base(), size_t(7)); + EXPECT_EQ(range.extent(), size_t(3)); + EXPECT_EQ(range.start(), size_t(3)); + EXPECT_EQ(range.end(), size_t(7)); + EXPECT_EQ(range.length(), size_t(4)); + EXPECT_FALSE(range.collapsed()); +} + +TEST(TextRange, SetBase) { + TextRange range(3, 7); + range.set_base(4); + EXPECT_EQ(range.base(), size_t(4)); + EXPECT_EQ(range.extent(), size_t(7)); +} + +TEST(TextRange, SetBaseReversed) { + TextRange range(7, 3); + range.set_base(5); + EXPECT_EQ(range.base(), size_t(5)); + EXPECT_EQ(range.extent(), size_t(3)); +} + +TEST(TextRange, SetExtent) { + TextRange range(3, 7); + range.set_extent(6); + EXPECT_EQ(range.base(), size_t(3)); + EXPECT_EQ(range.extent(), size_t(6)); +} + +TEST(TextRange, SetExtentReversed) { + TextRange range(7, 3); + range.set_extent(4); + EXPECT_EQ(range.base(), size_t(7)); + EXPECT_EQ(range.extent(), size_t(4)); +} + +TEST(TextRange, SetStart) { + TextRange range(3, 7); + range.set_start(5); + EXPECT_EQ(range.base(), size_t(5)); + EXPECT_EQ(range.extent(), size_t(7)); +} + +TEST(TextRange, SetStartReversed) { + TextRange range(7, 3); + range.set_start(5); + EXPECT_EQ(range.base(), size_t(7)); + EXPECT_EQ(range.extent(), size_t(5)); +} + +TEST(TextRange, SetEnd) { + TextRange range(3, 7); + range.set_end(6); + EXPECT_EQ(range.base(), size_t(3)); + EXPECT_EQ(range.extent(), size_t(6)); +} + +TEST(TextRange, SetEndReversed) { + TextRange range(7, 3); + range.set_end(5); + EXPECT_EQ(range.base(), size_t(5)); + EXPECT_EQ(range.extent(), size_t(3)); +} + +TEST(TextRange, ContainsPreStartPosition) { + TextRange range(2, 6); + EXPECT_FALSE(range.Contains(1)); +} + +TEST(TextRange, ContainsStartPosition) { + TextRange range(2, 6); + EXPECT_TRUE(range.Contains(2)); +} + +TEST(TextRange, ContainsMiddlePosition) { + TextRange range(2, 6); + EXPECT_TRUE(range.Contains(3)); + EXPECT_TRUE(range.Contains(4)); +} + +TEST(TextRange, ContainsEndPosition) { + TextRange range(2, 6); + EXPECT_TRUE(range.Contains(6)); +} + +TEST(TextRange, ContainsPostEndPosition) { + TextRange range(2, 6); + EXPECT_FALSE(range.Contains(7)); +} + +TEST(TextRange, ContainsPreStartPositionReversed) { + TextRange range(6, 2); + EXPECT_FALSE(range.Contains(1)); +} + +TEST(TextRange, ContainsStartPositionReversed) { + TextRange range(6, 2); + EXPECT_TRUE(range.Contains(2)); +} + +TEST(TextRange, ContainsMiddlePositionReversed) { + TextRange range(6, 2); + EXPECT_TRUE(range.Contains(3)); + EXPECT_TRUE(range.Contains(4)); +} + +TEST(TextRange, ContainsEndPositionReversed) { + TextRange range(6, 2); + EXPECT_TRUE(range.Contains(6)); +} + +TEST(TextRange, ContainsPostEndPositionReversed) { + TextRange range(6, 2); + EXPECT_FALSE(range.Contains(7)); +} + +TEST(TextRange, ContainsRangePreStartPosition) { + TextRange range(2, 6); + EXPECT_FALSE(range.Contains(TextRange(0, 1))); +} + +TEST(TextRange, ContainsRangeSpanningStartPosition) { + TextRange range(2, 6); + EXPECT_FALSE(range.Contains(TextRange(1, 3))); +} + +TEST(TextRange, ContainsRangeStartPosition) { + TextRange range(2, 6); + EXPECT_TRUE(range.Contains(TextRange(2))); +} + +TEST(TextRange, ContainsRangeMiddlePosition) { + TextRange range(2, 6); + EXPECT_TRUE(range.Contains(TextRange(3, 4))); + EXPECT_TRUE(range.Contains(TextRange(4, 5))); +} + +TEST(TextRange, ContainsRangeEndPosition) { + TextRange range(2, 6); + EXPECT_TRUE(range.Contains(TextRange(6))); +} + +TEST(TextRange, ContainsRangeSpanningEndPosition) { + TextRange range(2, 6); + EXPECT_FALSE(range.Contains(TextRange(5, 7))); +} + +TEST(TextRange, ContainsRangePostEndPosition) { + TextRange range(2, 6); + EXPECT_FALSE(range.Contains(TextRange(6, 7))); +} + +TEST(TextRange, ContainsRangePreStartPositionReversed) { + TextRange range(6, 2); + EXPECT_FALSE(range.Contains(TextRange(0, 1))); +} + +TEST(TextRange, ContainsRangeSpanningStartPositionReversed) { + TextRange range(6, 2); + EXPECT_FALSE(range.Contains(TextRange(1, 3))); +} + +TEST(TextRange, ContainsRangeStartPositionReversed) { + TextRange range(6, 2); + EXPECT_TRUE(range.Contains(TextRange(2))); +} + +TEST(TextRange, ContainsRangeMiddlePositionReversed) { + TextRange range(6, 2); + EXPECT_TRUE(range.Contains(TextRange(3, 4))); + EXPECT_TRUE(range.Contains(TextRange(4, 5))); +} + +TEST(TextRange, ContainsRangeSpanningEndPositionReversed) { + TextRange range(6, 2); + EXPECT_FALSE(range.Contains(TextRange(5, 7))); +} + +TEST(TextRange, ContainsRangeEndPositionReversed) { + TextRange range(6, 2); + EXPECT_TRUE(range.Contains(TextRange(5))); +} + +TEST(TextRange, ContainsRangePostEndPositionReversed) { + TextRange range(6, 2); + EXPECT_FALSE(range.Contains(TextRange(6, 7))); +} + +TEST(TextRange, ReversedForwardRange) { + TextRange range(2, 6); + EXPECT_FALSE(range.reversed()); +} + +TEST(TextRange, ReversedCollapsedRange) { + TextRange range(2, 2); + EXPECT_FALSE(range.reversed()); +} + +TEST(TextRange, ReversedReversedRange) { + TextRange range(6, 2); + EXPECT_TRUE(range.reversed()); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/shell/platform/config.gni b/flutter/engine/src/flutter/shell/platform/config.gni new file mode 100644 index 0000000000000000000000000000000000000000..192af2cec7d49cf820c0dea042b2447be111f855 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/config.gni @@ -0,0 +1,8 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +declare_args() { + # Whether or not to include desktop embedding targets in the build. + enable_desktop_embeddings = true +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/BUILD.gn b/flutter/engine/src/flutter/shell/platform/darwin/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c1db2da1341dc59237ec1f071138b1eaffd98880 --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/BUILD.gn @@ -0,0 +1,19 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +assert(is_mac || is_ios) + +import("//flutter/shell/platform/config.gni") + +group("darwin") { + if (is_ios) { + deps = [ "ios:flutter_framework" ] + } + if (is_mac) { + deps = [] + if (enable_desktop_embeddings) { + deps += [ "macos" ] + } + } +} diff --git a/flutter/engine/src/flutter/shell/platform/darwin/Doxyfile b/flutter/engine/src/flutter/shell/platform/darwin/Doxyfile new file mode 100644 index 0000000000000000000000000000000000000000..b6ba3e0e330831a14ba12a650cf4b8812f91fc1e --- /dev/null +++ b/flutter/engine/src/flutter/shell/platform/darwin/Doxyfile @@ -0,0 +1,2556 @@ +# Doxyfile 1.8.17 + +############################################################################## +# This is a Doxyfile to help identify holes in iOS's Flutter.framework. +############################################################################## + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the configuration +# file that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# https://www.gnu.org/software/libiconv/ for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = "Flutter.framework" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all generated output in the proper direction. +# Possible values are: None, LTR, RTL and Context. +# The default value is: None. + +OUTPUT_TEXT_DIRECTION = None + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = NO + +# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line +# such as +# /*************** +# as being the beginning of a Javadoc-style comment "banner". If set to NO, the +# Javadoc-style will behave just like regular comments and it will not be +# interpreted by doxygen. +# The default value is: NO. + +JAVADOC_BANNER = NO + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines (in the resulting output). You can put ^^ in the value part of an +# alias to insert a newline as if a physical newline was in the original file. +# When you need a literal { or } or , in the value part of an alias you have to +# escape them by means of a backslash (\), this can lead to conflicts with the +# commands \{ and \} for these it is advised to use the version @{ and @} or use +# a double escape (\\{ and \\}) + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice +# sources only. Doxygen will then generate output that is more tailored for that +# language. For instance, namespaces will be presented as modules, types will be +# separated into more groups, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_SLICE = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, JavaScript, +# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice, +# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: +# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser +# tries to guess whether the code is fixed or free formatted code, this is the +# default for Fortran type files), VHDL, tcl. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is +# Fortran), use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See https://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up +# to that level are automatically included in the table of contents, even if +# they do not have an id attribute. +# Note: This feature currently applies only to Markdown headings. +# Minimum value: 0, maximum value: 99, default value: 5. +# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. + +TOC_INCLUDE_HEADINGS = 5 + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# If one adds a struct or class to a group and this option is enabled, then also +# any nested class or struct is added to the same group. By default this option +# is disabled and one has to add nested compounds explicitly via \ingroup. +# The default value is: NO. + +GROUP_NESTED_COMPOUNDS = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual +# methods of a class will be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIV_VIRTUAL = NO + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# declarations. If set to NO, these declarations will be included in the +# documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES, upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# (including Cygwin) ands Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if ... \endif and \cond +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong or incomplete +# parameter documentation, but not about the absence of documentation. If +# EXTRACT_ALL is set to YES then this flag will automatically be disabled. +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when +# a warning is encountered. +# The default value is: NO. + +WARN_AS_ERROR = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING +# Note: If this tag is empty the current directory is searched. + +INPUT = common/framework/Headers \ + ios/framework/Headers + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: https://www.gnu.org/software/libiconv/) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# read by doxygen. +# +# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, +# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, +# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, +# *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C comment), +# *.doc (to be provided as doxygen C comment), *.txt (to be provided as doxygen +# C comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f, *.for, *.tcl, *.vhd, +# *.vhdl, *.ucf, *.qsf and *.ice. + +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ + *.cpp \ + *.c++ \ + *.java \ + *.ii \ + *.ixx \ + *.ipp \ + *.i++ \ + *.inl \ + *.idl \ + *.ddl \ + *.odl \ + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.h++ \ + *.cs \ + *.d \ + *.php \ + *.php4 \ + *.php5 \ + *.phtml \ + *.inc \ + *.markdown \ + *.md \ + *.dox \ + *.doc \ + *.txt \ + *.py \ + *.pyw \ + *.f90 \ + *.f95 \ + *.f03 \ + *.f08 \ + *.f \ + *.for \ + *.tcl \ + *.vhd \ + *.vhdl \ + *.ucf \ + *.qsf \ + *.ice + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# +# +# where is the value of the INPUT_FILTER tag, and is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# entity all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see https://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# https://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to YES can help to show when doxygen was last run and thus if the +# documentation is up to date. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = NO + +# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML +# documentation will contain a main index with vertical navigation menus that +# are dynamically created via JavaScript. If disabled, the navigation index will +# consists of multiple levels of tabs that are statically embedded in every HTML +# page. Disable this option to support browsers that do not have JavaScript, +# like the Qt help browser. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_MENUS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: https://developer.apple.com/xcode/), introduced with OSX +# 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy +# genXcode/_index.html for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the master .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = NO + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANSPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands +# to create new LaTeX commands to be used in formulas as building blocks. See +# the section "Including formulas" for details. + +FORMULA_MACROFILE = + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# https://www.mathjax.org) which uses client side JavaScript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from https://www.mathjax.org before deployment. +# The default value is: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/ + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use + S +# (what the is depends on the OS and browser, but it is typically +# , /