Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- flutter/engine/src/flutter/shell/common/BUILD.gnAdded+369
- flutter/engine/src/flutter/shell/common/animator.ccAdded+329
- flutter/engine/src/flutter/shell/common/animator.hAdded+160
- flutter/engine/src/flutter/shell/common/animator_unittests.ccAdded+267
- flutter/engine/src/flutter/shell/common/base64.ccAdded+160
- flutter/engine/src/flutter/shell/common/base64.hAdded+59
- flutter/engine/src/flutter/shell/common/base64_unittests.ccAdded+122
- flutter/engine/src/flutter/shell/common/context_options.ccAdded+47
- flutter/engine/src/flutter/shell/common/context_options.hAdded+47
- flutter/engine/src/flutter/shell/common/context_options_unittests.ccAdded+19
- flutter/engine/src/flutter/shell/common/dart_native_benchmarks.ccAdded+108
- flutter/engine/src/flutter/shell/common/display.ccAdded+11
- flutter/engine/src/flutter/shell/common/display.hAdded+91
- flutter/engine/src/flutter/shell/common/display_manager.ccAdded+32
- flutter/engine/src/flutter/shell/common/display_manager.hAdded+41
- flutter/engine/src/flutter/shell/common/dl_op_spy.ccAdded+156
- flutter/engine/src/flutter/shell/common/dl_op_spy.hAdded+123
- flutter/engine/src/flutter/shell/common/dl_op_spy_unittests.ccAdded+588
- flutter/engine/src/flutter/shell/common/engine.ccAdded+646
- flutter/engine/src/flutter/shell/common/engine.hAdded+1093
- flutter/engine/src/flutter/shell/common/engine_animator_unittests.ccAdded+666
- flutter/engine/src/flutter/shell/common/engine_unittests.ccAdded+560
- flutter/engine/src/flutter/shell/common/input_events_unittests.ccAdded+446
- flutter/engine/src/flutter/shell/common/persistent_cache_unittests.ccAdded+203
- flutter/engine/src/flutter/shell/common/pipeline.ccAdded+14
- flutter/engine/src/flutter/shell/common/pipeline.hAdded+260
- flutter/engine/src/flutter/shell/common/pipeline_unittests.ccAdded+148
- flutter/engine/src/flutter/shell/common/platform_message_handler.hAdded+48
- flutter/engine/src/flutter/shell/common/platform_view.ccAdded+233
- flutter/engine/src/flutter/shell/common/platform_view.hAdded+994
- flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.ccAdded+75
- flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.hAdded+177
- flutter/engine/src/flutter/shell/common/rasterizer.ccAdded+1169
- flutter/engine/src/flutter/shell/common/rasterizer.hAdded+779
- flutter/engine/src/flutter/shell/common/rasterizer_unittests.ccAdded+1411
- flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.ccAdded+25
- flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.hAdded+49
- flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator_unittests.ccAdded+54
- flutter/engine/src/flutter/shell/common/run_configuration.ccAdded+122
- flutter/engine/src/flutter/shell/common/run_configuration.hAdded+219
- flutter/engine/src/flutter/shell/common/serialization_callbacks.ccAdded+81
- flutter/engine/src/flutter/shell/common/serialization_callbacks.hAdded+28
- flutter/engine/src/flutter/shell/common/shell.ccAdded+2297
- flutter/engine/src/flutter/shell/common/shell.hAdded+815
- flutter/engine/src/flutter/shell/common/shell_benchmarks.ccAdded+123
- flutter/engine/src/flutter/shell/common/shell_fuchsia_unittests.ccAdded+267
- flutter/engine/src/flutter/shell/common/shell_io_manager.ccAdded+127
- flutter/engine/src/flutter/shell/common/shell_io_manager.hAdded+84
- flutter/engine/src/flutter/shell/common/shell_io_manager_unittests.ccAdded+106
- flutter/engine/src/flutter/shell/common/shell_test.ccAdded+424
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369# Copyright 2013 The Flutter 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 datadepstemplate("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/graphicssource_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", ] } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329// Copyright 2013 The Flutter 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<VsyncWaiter> waiter) : delegate_(delegate), task_runners_(task_runners), waiter_(std::move(waiter)),#if SHELL_ENABLE_METAL layer_tree_pipeline_(std::make_shared<FramePipeline>(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<FramePipeline>( 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<FrameTimingsRecorder> 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<uint64_t[]> flow_ids = std::make_unique<uint64_t[]>(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<std::unique_ptr<LayerTreeTask>> 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<FrameItem>(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<flutter::LayerTree> 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<FrameTimingsRecorder>(); 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<LayerTreeTask>(view_id, std::move(layer_tree), device_pixel_ratio));}
const std::weak_ptr<VsyncWaiter> Animator::GetVsyncWaiter() const { std::weak_ptr<VsyncWaiter> weak = waiter_; return weak;}
bool Animator::CanReuseLastLayerTrees() { return !regenerate_layer_trees_;}
void Animator::DrawLastLayerTrees( std::unique_ptr<FrameTimingsRecorder> 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<FrameTimingsRecorder> 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<uintptr_t>(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<uint64_t[]> flow_ids = std::make_unique<uint64_t[]>(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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160// Copyright 2013 The Flutter 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 <deque>
#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<FramePipeline> pipeline) = 0;
virtual void OnAnimatorDrawLastLayerTrees( std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) = 0; };
Animator(Delegate& delegate, const TaskRunners& task_runners, std::unique_ptr<VsyncWaiter> 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<flutter::LayerTree> layer_tree, float device_pixel_ratio);
const std::weak_ptr<VsyncWaiter> 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<FrameTimingsRecorder> frame_timings_recorder); void EndFrame();
bool CanReuseLastLayerTrees();
void DrawLastLayerTrees( std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder);
void AwaitVSync();
// Clear |trace_flow_ids_| if |frame_scheduled_| is false. void ScheduleMaybeClearTraceFlowIds();
Delegate& delegate_; TaskRunners task_runners_; std::shared_ptr<VsyncWaiter> waiter_;
std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder_; std::unordered_map<int64_t, std::unique_ptr<LayerTreeTask>> layer_trees_tasks_; uint64_t frame_request_number_ = 1; fml::TimeDelta dart_frame_deadline_; std::shared_ptr<FramePipeline> layer_tree_pipeline_; fml::Semaphore pending_frame_semaphore_; FramePipeline::ProducerContinuation producer_continuation_; bool regenerate_layer_trees_ = false; bool frame_scheduled_ = false; std::deque<uint64_t> trace_flow_ids_; bool has_rendered_ = false;
fml::WeakPtrFactory<Animator> weak_factory_;
friend class testing::ShellTest;
FML_DISALLOW_COPY_AND_ASSIGN(Animator);};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_ANIMATOR_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267// Copyright 2013 The Flutter 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 <functional>#include <future>#include <memory>
#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<FramePipeline> pipeline), (override));
void OnAnimatorDrawLastLayerTrees( std::unique_ptr<FrameTimingsRecorder> 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<int64_t>::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> shell;
TaskRunners task_runners = GetTaskRunnersForFixture(); // this is not used as we are not using simulated events. const auto vsync_clock = std::make_shared<ShellTestVsyncClock>(); CreateVsyncWaiter create_vsync_waiter = [&]() { return static_cast<std::unique_ptr<VsyncWaiter>>( std::make_unique<ConstantFiringVsyncWaiter>(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<Rasterizer>(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<ShellTestVsyncClock>(); fml::AutoResetWaitableEvent latch; std::shared_ptr<Animator> 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::unique_ptr<VsyncWaiter>>( std::make_unique<ShellTestVsyncWaiter>(task_runners, clock)); animator = std::make_unique<Animator>(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<LayerTree>(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<ShellTestVsyncClock>(); std::shared_ptr<Animator> 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::unique_ptr<VsyncWaiter>>( std::make_unique<ShellTestVsyncWaiter>(task_runners, clock)); animator = std::make_unique<Animator>(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<LayerTree>(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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160// Copyright 2013 The Flutter 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 <cstdint>
#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<const unsigned char*>(srcv); unsigned char* dst = static_cast<unsigned char*>(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<uint8_t>(bytes[0] << 2); two = bytes[1]; one |= two >> 4; two = static_cast<uint8_t>((two << 4) & 0xFF); three = bytes[2]; two |= three >> 2; three = static_cast<uint8_t>((three << 6) & 0xFF); three |= bytes[3]; FML_DCHECK(one < 256 && two < 256 && three < 256); dst[i] = static_cast<unsigned char>(one); } i++; if (padTwo) { break; } if (dst) { dst[i] = static_cast<unsigned char>(two); } i++; if (padThree) { break; } if (dst) { dst[i] = static_cast<unsigned char>(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<const unsigned char*>(srcv); unsigned char* dst = static_cast<unsigned char*>(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<uint8_t>(*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 flutter1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859// Copyright 2013 The Flutter 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 <cstddef>
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_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122// Copyright 2013 The Flutter 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 <string>
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<int>(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 flutter1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// Copyright 2013 The Flutter 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<GrBackendApi> 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 // !SLIMPELLER1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// Copyright 2013 The Flutter 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 <optional>
#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<GrBackendApi> api = std::nullopt);
} // namespace flutter
#endif // !SLIMPELLER
#endif // FLUTTER_SHELL_COMMON_CONTEXT_OPTIONS_H_12345678910111213141516171819// Copyright 2013 The Flutter 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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108// Copyright 2013 The Flutter 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)1234567891011// Copyright 2013 The Flutter 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 flutter12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091// Copyright 2013 The Flutter 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 <optional>
#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_1234567891011121314151617181920212223242526272829303132// Copyright 2013 The Flutter 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<std::unique_ptr<Display>> displays) { FML_DCHECK(!displays.empty()); std::scoped_lock lock(displays_mutex_); displays_ = std::move(displays);}
} // namespace flutter1234567891011121314151617181920212223242526272829303132333435363738394041// Copyright 2013 The Flutter 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 <mutex>#include <vector>
#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<std::unique_ptr<Display>> displays);
private: /// Guards `displays_` vector. mutable std::mutex displays_mutex_; std::vector<std::unique_ptr<Display>> displays_;};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_DISPLAY_MANAGER_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156// Copyright 2013 The Flutter 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<int64_t> 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/123803void 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<DlVertices>& 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<DlImage> image, const DlPoint& point, DlImageSampling sampling, bool render_with_attributes) { did_draw_ = true;}void DlOpSpy::drawImageRect(const sk_sp<DlImage> image, const DlRect& src, const DlRect& dst, DlImageSampling sampling, bool render_with_attributes, DlSrcRectConstraint constraint) { did_draw_ = true;}void DlOpSpy::drawImageNine(const sk_sp<DlImage> image, const DlIRect& center, const DlRect& dst, DlFilterMode filter, bool render_with_attributes) { did_draw_ = true;}void DlOpSpy::drawAtlas(const sk_sp<DlImage> 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<DisplayList> 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<SkTextBlob> blob, DlScalar x, DlScalar y) { did_draw_ |= will_draw_;}
void DlOpSpy::drawTextFrame( const std::shared_ptr<impeller::TextFrame>& 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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123// Copyright 2013 The Flutter 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<int64_t> 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<DlVertices>& vertices, DlBlendMode mode) override; void drawImage(const sk_sp<DlImage> image, const DlPoint& point, DlImageSampling sampling, bool render_with_attributes) override; void drawImageRect( const sk_sp<DlImage> image, const DlRect& src, const DlRect& dst, DlImageSampling sampling, bool render_with_attributes, DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) override; void drawImageNine(const sk_sp<DlImage> image, const DlIRect& center, const DlRect& dst, DlFilterMode filter, bool render_with_attributes) override; void drawAtlas(const sk_sp<DlImage> 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<DisplayList> display_list, DlScalar opacity = SK_Scalar1) override; void drawTextBlob(const sk_sp<SkTextBlob> blob, DlScalar x, DlScalar y) override; void drawTextFrame(const std::shared_ptr<impeller::TextFrame>& 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_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588// Copyright 2013 The Flutter 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> dl = builder.Build();
DisplayListBuilder builder_parent; DlPaint paint_parent(DlColor::kTransparent()); builder_parent.DrawPaint(paint_parent); builder_parent.DrawDisplayList(dl, 1); sk_sp<DisplayList> 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<DisplayList> dl = builder.Build();
DisplayListBuilder builder_parent; DlPaint paint_parent(DlColor::kTransparent()); builder_parent.DrawPaint(paint_parent); builder_parent.DrawDisplayList(dl, 1); sk_sp<DisplayList> 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<DisplayList> dl = builder.Build();
DisplayListBuilder builder_parent; DlPaint paint_parent(DlColor::kTransparent()); builder_parent.DrawPaint(paint_parent); builder_parent.DrawDisplayList(dl, 0); sk_sp<DisplayList> 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<DisplayList> dl = builder.Build();
DisplayListBuilder builder_parent; DlPaint paint_parent(DlColor::kBlack()); builder_parent.DrawPaint(paint_parent); builder_parent.DrawDisplayList(dl, 0); sk_sp<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> 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<DisplayList> dl = builder.Build(); DlOpSpy dl_op_spy; dl->Dispatch(dl_op_spy); ASSERT_NO_DRAW(dl_op_spy, dl); }}
} // namespace testing} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646// Copyright 2013 The Flutter 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 <cstring>#include <memory>#include <string>#include <utility>#include <vector>
#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<fml::ConcurrentTaskRunner>& image_decoder_task_runner, const TaskRunners& task_runners, const Settings& settings, std::unique_ptr<Animator> animator, const fml::WeakPtr<IOManager>& io_manager, const std::shared_ptr<FontCollection>& font_collection, std::unique_ptr<RuntimeController> runtime_controller, const std::shared_ptr<fml::SyncSwitch>& 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<const DartSnapshot> isolate_snapshot, const TaskRunners& task_runners, const PlatformData& platform_data, const Settings& settings, std::unique_ptr<Animator> animator, fml::WeakPtr<IOManager> io_manager, const fml::RefPtr<SkiaUnrefQueue>& unref_queue, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, const std::shared_ptr<fml::SyncSwitch>& 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<FontCollection>(), nullptr, gpu_disabled_switch) { runtime_controller_ = std::make_unique<RuntimeController>( *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> Engine::Spawn( Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, const Settings& settings, std::unique_ptr<Animator> animator, const std::string& initial_route, const fml::WeakPtr<IOManager>& io_manager, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch) const { auto result = std::make_unique<Engine>( /*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> 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<AssetManager> Engine::GetAssetManager() { return asset_manager_;}
fml::WeakPtr<ImageDecoder> Engine::GetImageDecoderWeakPtr() { return image_decoder_->GetWeakPtr();}
fml::WeakPtr<ImageGeneratorRegistry> Engine::GetImageGeneratorRegistry() { return image_generator_registry_.GetWeakPtr();}
bool Engine::UpdateAssetManager( const std::shared_ptr<AssetManager>& 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<NativeAssetsManager>(); } 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<PlatformMessage> service_id_message = std::make_unique<flutter::PlatformMessage>( 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<int64_t> 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<uint32_t> 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<void(bool added)> 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<PlatformMessage> 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<const char*>(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<PlatformMessage> message) { const auto& data = message->data();
rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(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<const char*>(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<std::string> 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<const char*>(data.GetMapping()), data.GetSize()); if (runtime_controller_->SetUserSettingsData(jsonData)) { ScheduleFrame(); }}
void Engine::DispatchPointerDataPacket( std::unique_ptr<PointerDataPacket> 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<flutter::LayerTree> 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<PlatformMessage> 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<std::vector<std::string>> Engine::ComputePlatformResolvedLocale( const std::vector<std::string>& 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<PointerDataPacket> 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<PlatformMessage> message) { fml::RefPtr<PlatformMessageResponse> response = message->response(); if (!response) { return; } const auto& data = message->data(); std::string asset_name(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize());
if (asset_manager_) { std::unique_ptr<fml::Mapping> 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<std::string>& 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<PlatformMessageHandler> 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<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> 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<VsyncWaiter> Engine::GetVsyncWaiter() const { return animator_->GetVsyncWaiter();}
void Engine::SetDisplays(const std::vector<DisplayData>& displays) { runtime_controller_->SetDisplays(displays); ScheduleFrame();}
void Engine::ShutdownPlatformIsolates() { runtime_controller_->ShutdownPlatformIsolates();}
void Engine::FlushMicrotaskQueue() { runtime_controller_->FlushMicrotaskQueue();}
} // namespace flutter1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093// Copyright 2013 The Flutter 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 <memory>#include <string>
#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<PlatformMessage> 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<std::vector<std::string>> ComputePlatformResolvedLocale( const std::vector<std::string>& 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<PlatformMessageHandler>& 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<fml::ConcurrentTaskRunner>& image_decoder_task_runner, const TaskRunners& task_runners, const Settings& settings, std::unique_ptr<Animator> animator, const fml::WeakPtr<IOManager>& io_manager, const std::shared_ptr<FontCollection>& font_collection, std::unique_ptr<RuntimeController> runtime_controller, const std::shared_ptr<fml::SyncSwitch>& 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<const DartSnapshot> isolate_snapshot, const TaskRunners& task_runners, const PlatformData& platform_data, const Settings& settings, std::unique_ptr<Animator> animator, fml::WeakPtr<IOManager> io_manager, const fml::RefPtr<SkiaUnrefQueue>& unref_queue, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, const std::shared_ptr<fml::SyncSwitch>& 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<Engine> Spawn( Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, const Settings& settings, std::unique_ptr<Animator> animator, const std::string& initial_route, const fml::WeakPtr<IOManager>& io_manager, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, const std::shared_ptr<fml::SyncSwitch>& 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<Engine> 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<AssetManager>& 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<int64_t> 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<uint32_t> 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<void(bool added)> 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<DisplayData>& 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<PlatformMessage> 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<PointerDataPacket> 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<AssetManager> GetAssetManager() override;
// Return the weak_ptr of ImageDecoder. fml::WeakPtr<ImageDecoder> GetImageDecoderWeakPtr();
//---------------------------------------------------------------------------- /// @brief Get the `ImageGeneratorRegistry` associated with the current /// engine. /// /// @return The engine's `ImageGeneratorRegistry`. /// fml::WeakPtr<ImageGeneratorRegistry> GetImageGeneratorRegistry();
// |PointerDataDispatcher::Delegate| void DoDispatchPacket(std::unique_ptr<PointerDataPacket> 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<std::string>& 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<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> 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<VsyncWaiter> 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<flutter::LayerTree> 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<PlatformMessage> message) override;
// |RuntimeDelegate| void OnRootIsolateCreated() override;
// |RuntimeDelegate| void UpdateIsolateDescription(const std::string isolate_name, int64_t isolate_port) override;
// |RuntimeDelegate| std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocale( const std::vector<std::string>& supported_locale_data) override;
// |RuntimeDelegate| void RequestDartDeferredLibrary(intptr_t loading_unit_id) override;
// |RuntimeDelegate| std::weak_ptr<PlatformMessageHandler> 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<PlatformMessage> message);
bool HandleLocalizationPlatformMessage(PlatformMessage* message);
void HandleSettingsPlatformMessage(PlatformMessage* message);
void HandleAssetPlatformMessage(std::unique_ptr<PlatformMessage> message);
bool GetAssetAsBuffer(const std::string& name, std::vector<uint8_t>* data);
friend class testing::ShellTest;
Engine::Delegate& delegate_; const Settings settings_; std::unique_ptr<Animator> animator_; std::unique_ptr<RuntimeController> 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<PointerDataDispatcher> pointer_data_dispatcher_;
std::string last_entry_point_; std::string last_entry_point_library_; std::vector<std::string> last_entry_point_args_; std::string initial_route_; std::shared_ptr<AssetManager> asset_manager_; std::shared_ptr<FontCollection> font_collection_; std::shared_ptr<NativeAssetsManager> native_assets_manager_; const std::unique_ptr<ImageDecoder> image_decoder_; ImageGeneratorRegistry image_generator_registry_; TaskRunners task_runners_; fml::WeakPtrFactory<Engine> weak_factory_; // Must be the last member. FML_DISALLOW_COPY_AND_ASSIGN(Engine);};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_ENGINE_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666// Copyright 2013 The Flutter 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 <cstring>
#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<fml::TaskRunner>& 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<const LayerTreeTask*> Sorted( const std::vector<std::unique_ptr<LayerTreeTask>>& layer_tree_tasks) { std::vector<const LayerTreeTask*> 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<PlatformMessage>), (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<std::vector<std::string>>, ComputePlatformResolvedLocale, (const std::vector<std::string>&), (override)); MOCK_METHOD(void, RequestDartDeferredLibrary, (intptr_t), (override)); MOCK_METHOD(fml::TimePoint, GetCurrentTimePoint, (), (override)); MOCK_METHOD(const std::shared_ptr<PlatformMessageHandler>&, 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<FramePipeline> pipeline), (override)); MOCK_METHOD(void, OnAnimatorDrawLastLayerTrees, (std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder), (override));};
class MockPlatformMessageHandler : public PlatformMessageHandler { public: MOCK_METHOD(void, HandlePlatformMessage, (std::unique_ptr<PlatformMessage> message), (override)); MOCK_METHOD(bool, DoesHandlePlatformMessageOnPlatformThread, (), (const, override)); MOCK_METHOD(void, InvokePlatformMessageResponseCallback, (int response_id, std::unique_ptr<fml::Mapping> 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<void()>& 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> animator_; fml::WeakPtr<IOManager> io_manager_; std::unique_ptr<RuntimeController> runtime_controller_; std::shared_ptr<fml::ConcurrentTaskRunner> image_decoder_task_runner_; fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> 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<void(Engine&)>;
[[nodiscard]] static std::unique_ptr<EngineContext> Create( Engine::Delegate& delegate, // Settings settings, // const TaskRunners& task_runners, // std::unique_ptr<Animator> 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<EngineContext>(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> animator, // const DartVMRef& vm, // fml::RefPtr<const DartSnapshot> 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<DefaultPointerDataDispatcher>(delegate); }; engine_ = std::make_unique<Engine>( /*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<fml::SyncSwitch>()); }); }
TaskRunners task_runners_; DartVMRef vm_; std::unique_ptr<Engine> engine_;
fml::WeakPtr<IOManager> io_manager_; fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate_;};} // namespace
TEST_F(EngineAnimatorTest, AnimatorAcceptsMultipleRenders) { MockAnimatorDelegate animator_delegate; std::unique_ptr<EngineContext> engine_context;
std::shared_ptr<PlatformMessageHandler> platform_message_handler = std::make_shared<MockPlatformMessageHandler>(); 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<FramePipeline>& pipeline) { auto status = pipeline->Consume([&](std::unique_ptr<FrameItem> 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> animator; PostSync(task_runners_.GetUITaskRunner(), [&animator, &animator_delegate, &task_runners = task_runners_] { animator = std::make_unique<Animator>( animator_delegate, task_runners, static_cast<std::unique_ptr<VsyncWaiter>>( std::make_unique<testing::ConstantFiringVsyncWaiter>( 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<EngineContext> engine_context;
std::shared_ptr<PlatformMessageHandler> platform_message_handler = std::make_shared<MockPlatformMessageHandler>(); 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<FramePipeline>& pipeline) { auto status = pipeline->Consume([&](std::unique_ptr<FrameItem> 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> animator; PostSync(task_runners_.GetUITaskRunner(), [&animator, &animator_delegate, &task_runners = task_runners_] { animator = std::make_unique<Animator>( animator_delegate, task_runners, static_cast<std::unique_ptr<VsyncWaiter>>( std::make_unique<testing::ConstantFiringVsyncWaiter>( 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<EngineContext> engine_context;
std::vector<std::shared_ptr<Layer>> 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<SceneBuilder*>(peer); ASSERT_TRUE(scene_builder); std::shared_ptr<ContainerLayer> root_layer = scene_builder->layer_stack()[0]; ASSERT_TRUE(root_layer); benchmark_layers = root_layer->layers(); };
std::shared_ptr<PlatformMessageHandler> platform_message_handler = std::make_shared<MockPlatformMessageHandler>(); 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<FramePipeline>& pipeline) { auto status = pipeline->Consume([&](std::unique_ptr<FrameItem> item) { EXPECT_EQ(item->layer_tree_tasks.size(), 1u); EXPECT_EQ(item->layer_tree_tasks[0]->view_id, kFlutterImplicitViewId); ContainerLayer* root_layer = reinterpret_cast<ContainerLayer*>( item->layer_tree_tasks[0]->layer_tree->root_layer()); std::vector<std::shared_ptr<Layer>> 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> animator; PostSync(task_runners_.GetUITaskRunner(), [&animator, &animator_delegate, &task_runners = task_runners_] { animator = std::make_unique<Animator>( animator_delegate, task_runners, static_cast<std::unique_ptr<VsyncWaiter>>( std::make_unique<testing::ConstantFiringVsyncWaiter>( 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<EngineContext> engine_context;
std::shared_ptr<PlatformMessageHandler> platform_message_handler = std::make_shared<MockPlatformMessageHandler>(); 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<FramePipeline>& pipeline) { rasterization_started = true; auto status = pipeline->Consume([&](std::unique_ptr<FrameItem> 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> animator; PostSync(task_runners_.GetUITaskRunner(), [&animator, &animator_delegate, &task_runners = task_runners_] { animator = std::make_unique<Animator>( animator_delegate, task_runners, static_cast<std::unique_ptr<VsyncWaiter>>( std::make_unique<testing::ConstantFiringVsyncWaiter>( 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<EngineContext> engine_context;
std::shared_ptr<PlatformMessageHandler> platform_message_handler = std::make_shared<MockPlatformMessageHandler>(); 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<FramePipeline>& pipeline) { auto status = pipeline->Consume([&](std::unique_ptr<FrameItem> 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> animator; PostSync(task_runners_.GetUITaskRunner(), [&animator, &animator_delegate, &task_runners = task_runners_] { animator = std::make_unique<Animator>( animator_delegate, task_runners, static_cast<std::unique_ptr<VsyncWaiter>>( std::make_unique<testing::ConstantFiringVsyncWaiter>( 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<EngineContext> engine_context;
std::shared_ptr<PlatformMessageHandler> platform_message_handler = std::make_shared<MockPlatformMessageHandler>(); 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<FramePipeline>& pipeline) { auto status = pipeline->Consume([&](std::unique_ptr<FrameItem> 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> animator; PostSync(task_runners_.GetUITaskRunner(), [&animator, &animator_delegate, &task_runners = task_runners_] { animator = std::make_unique<Animator>( animator_delegate, task_runners, static_cast<std::unique_ptr<VsyncWaiter>>( std::make_unique<testing::ConstantFiringVsyncWaiter>( 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560// Copyright 2013 The Flutter 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 <cstring>
#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<fml::Mapping> GetAsMapping( const std::string& asset_name) const override { mapping_call_count++; if (asset_name == "FontManifest.json") { return std::make_unique<fml::DataMapping>("[{},{},{}]"); } return nullptr; }
std::vector<std::unique_ptr<fml::Mapping>> GetAsMappings( const std::string& asset_pattern, const std::optional<std::string>& 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<PlatformMessage>), (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<std::vector<std::string>>, ComputePlatformResolvedLocale, (const std::vector<std::string>&), (override)); MOCK_METHOD(void, RequestDartDeferredLibrary, (intptr_t), (override)); MOCK_METHOD(fml::TimePoint, GetCurrentTimePoint, (), (override)); MOCK_METHOD(const std::shared_ptr<PlatformMessageHandler>&, 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<fml::Mapping> 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<flutter::LayerTree>, float), (override)); MOCK_METHOD(void, UpdateSemantics, (int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates), (override)); MOCK_METHOD(void, HandlePlatformMessage, (std::unique_ptr<PlatformMessage>), (override)); MOCK_METHOD(FontCollection&, GetFontCollection, (), (override)); MOCK_METHOD(std::shared_ptr<AssetManager>, 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<std::vector<std::string>>, ComputePlatformResolvedLocale, (const std::vector<std::string>&), (override)); MOCK_METHOD(void, RequestDartDeferredLibrary, (intptr_t), (override)); MOCK_METHOD(std::weak_ptr<PlatformMessageHandler>, 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<PlatformMessage>), (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<AssetManager>& asset_manager), (override));};
std::unique_ptr<PlatformMessage> MakePlatformMessage( const std::string& channel, const std::map<std::string, std::string>& values, const fml::RefPtr<PlatformMessageResponse>& 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<rapidjson::StringBuffer> writer(buffer); document.Accept(writer); const uint8_t* data = reinterpret_cast<const uint8_t*>(buffer.GetString());
std::unique_ptr<PlatformMessage> message = std::make_unique<PlatformMessage>( 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<void()>& 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> animator_; fml::WeakPtr<IOManager> io_manager_; std::unique_ptr<RuntimeController> runtime_controller_; std::shared_ptr<fml::ConcurrentTaskRunner> image_decoder_task_runner_; fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate_;};} // namespace
TEST_F(EngineTest, Create) { PostUITaskSync([this] { auto engine = std::make_unique<Engine>( /*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<FontCollection>(), /*runtime_controller=*/std::move(runtime_controller_), /*gpu_disabled_switch=*/std::make_shared<fml::SyncSwitch>()); EXPECT_TRUE(engine); });}
TEST_F(EngineTest, DispatchPlatformMessageUnknown) { PostUITaskSync([this] { MockRuntimeDelegate client; auto mock_runtime_controller = std::make_unique<MockRuntimeController>(client, task_runners_); EXPECT_CALL(*mock_runtime_controller, IsRootIsolateRunning()) .WillRepeatedly(::testing::Return(false)); auto engine = std::make_unique<Engine>( /*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<FontCollection>(), /*runtime_controller=*/std::move(mock_runtime_controller), /*gpu_disabled_switch=*/std::make_shared<fml::SyncSwitch>());
fml::RefPtr<PlatformMessageResponse> response = fml::MakeRefCounted<MockResponse>(); std::unique_ptr<PlatformMessage> message = std::make_unique<PlatformMessage>("foo", response); engine->DispatchPlatformMessage(std::move(message)); });}
TEST_F(EngineTest, DispatchPlatformMessageInitialRoute) { PostUITaskSync([this] { MockRuntimeDelegate client; auto mock_runtime_controller = std::make_unique<MockRuntimeController>(client, task_runners_); EXPECT_CALL(*mock_runtime_controller, IsRootIsolateRunning()) .WillRepeatedly(::testing::Return(false)); auto engine = std::make_unique<Engine>( /*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<FontCollection>(), /*runtime_controller=*/std::move(mock_runtime_controller), /*gpu_disabled_switch=*/std::make_shared<fml::SyncSwitch>());
fml::RefPtr<PlatformMessageResponse> response = fml::MakeRefCounted<MockResponse>(); std::map<std::string, std::string> values{ {"method", "setInitialRoute"}, {"args", "test_initial_route"}, }; std::unique_ptr<PlatformMessage> 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<MockRuntimeController>(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<Engine>( /*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<FontCollection>(), /*runtime_controller=*/std::move(mock_runtime_controller), /*gpu_disabled_switch=*/std::make_shared<fml::SyncSwitch>());
fml::RefPtr<PlatformMessageResponse> response = fml::MakeRefCounted<MockResponse>(); std::map<std::string, std::string> values{ {"method", "setInitialRoute"}, {"args", "test_initial_route"}, }; std::unique_ptr<PlatformMessage> 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<MockRuntimeController>(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<Engine>( /*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<FontCollection>(), /*runtime_controller=*/std::move(mock_runtime_controller), /*gpu_disabled_switch=*/std::make_shared<fml::SyncSwitch>());
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<MockRuntimeController>(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<Engine>( /*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<FontCollection>(), /*runtime_controller=*/std::move(mock_runtime_controller), /*gpu_disabled_switch=*/std::make_shared<fml::SyncSwitch>());
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<MockRuntimeController>(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<Engine>( /*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<FontCollection>(), /*runtime_controller=*/std::move(mock_runtime_controller), /*gpu_disabled_switch=*/std::make_shared<fml::SyncSwitch>());
Settings custom_settings = settings_; custom_settings.persistent_isolate_data = std::make_shared<fml::DataMapping>("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<RuntimeController*>(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<MockRuntimeController>(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<Engine>( /*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<FontCollection>(), /*runtime_controller=*/std::move(mock_runtime_controller), /*gpu_disabled_switch=*/std::make_shared<fml::SyncSwitch>());
engine->LoadDartDeferredLibraryError(error_id, error_message, true); });}
TEST_F(EngineTest, SpawnedEngineInheritsAssetManager) { PostUITaskSync([this] { MockRuntimeDelegate client; auto mock_runtime_controller = std::make_unique<MockRuntimeController>(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<MockFontCollection>(); // EXPECT_CALL(*mock_font_collection, RegisterFonts(::testing::_)) // .WillOnce(::testing::Return()); auto engine = std::make_unique<Engine>( /*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<FontCollection>(), /*runtime_controller=*/std::move(mock_runtime_controller), /*gpu_disabled_switch=*/std::make_shared<fml::SyncSwitch>());
EXPECT_EQ(engine->GetAssetManager(), nullptr);
auto asset_manager = std::make_shared<AssetManager>(); asset_manager->PushBack(std::make_unique<FontManifestAssetResolver>()); 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<MockRuntimeController>(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<MockFontCollection>(); EXPECT_CALL(*mock_font_collection, RegisterFonts(::testing::_)) .WillOnce(::testing::Return()); auto engine = std::make_unique<Engine>( /*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<fml::SyncSwitch>());
EXPECT_EQ(engine->GetAssetManager(), nullptr);
auto asset_manager = std::make_shared<AssetManager>(); asset_manager->PushBack(std::make_unique<FontManifestAssetResolver>());
auto asset_manager_2 = std::make_shared<AssetManager>(); asset_manager_2->PushBack(std::make_unique<FontManifestAssetResolver>());
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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446// Copyright 2013 The Flutter 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<UnitlessTime(int)>;
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<UnitlessTime>& events_consumed_at_frame, bool restart_engine = false) { ///// Begin constructing shell /////////////////////////////////////////////// auto settings = fixture->CreateSettingsForFixture(); std::unique_ptr<Shell> 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<int>((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<UnitlessTime>( i * frame_time + base_latency + (i % 2 == 0 ? 0.1 * frame_time : 0.9 * frame_time)); }; constexpr int n = 40; std::vector<int> 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<UnitlessTime>(i * 0.5 * frame_time + base_latency); }; constexpr int n = 40; std::vector<int> 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<UnitlessTime>(base_latency_f * frame_time); Generator iphone_xs_generator = [frame_time, base_latency](int i) { return base_latency + static_cast<UnitlessTime>(iphone_xs_times[i] * frame_time); }; std::vector<int> 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> 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<int64_t> result_sequence; auto nativeOnPointerDataPacket = [&reportLatch, &result_sequence]( Dart_NativeArguments args) { Dart_Handle exception = nullptr; result_sequence = tonic::DartConverter<std::vector<int64_t>>::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<PointerDataPacket>(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> 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<int64_t> result_sequence; auto nativeOnPointerDataPacket = [&reportLatch, &result_sequence]( Dart_NativeArguments args) { Dart_Handle exception = nullptr; result_sequence = tonic::DartConverter<std::vector<int64_t>>::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<PointerDataPacket>(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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203// Copyright 2013 The Flutter 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 <memory>
#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<SkData>& data, const std::string& expected) { std::string data_string(reinterpret_cast<const char*>(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<fml::DataMapping>( std::vector<uint8_t>{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<AssetManager>(); RunConfiguration config(nullptr, asset_manager); asset_manager->PushBack(std::make_unique<DirectoryAssetBundle>( 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> 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<SkData> shader_key = SkData::MakeWithCString("key"); sk_sp<SkData> 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> 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<bool> 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 flutter1234567891011121314// Copyright 2013 The Flutter 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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260// Copyright 2013 The Flutter 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 <deque>#include <memory>#include <mutex>
#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 R>class Pipeline { public: using Resource = R; using ResourcePtr = std::unique_ptr<Resource>;
/// 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<PipelineProduceResult(ResourcePtr, size_t)>;
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<int64_t>(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<int64_t>(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<void(ResourcePtr)>;
/// @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<int> inflight_; std::mutex queue_mutex_; std::deque<std::pair<ResourcePtr, size_t>> 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_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148// Copyright 2013 The Flutter 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 <functional>#include <future>#include <memory>
#include "gtest/gtest.h"
namespace flutter {namespace testing {
using IntPipeline = Pipeline<int>;using Continuation = IntPipeline::ProducerContinuation;
TEST(PipelineTest, ConsumeOneVal) { std::shared_ptr<IntPipeline> pipeline = std::make_shared<IntPipeline>(2);
Continuation continuation = pipeline->Produce();
const int test_val = 1; PipelineProduceResult result = continuation.Complete(std::make_unique<int>(test_val)); ASSERT_EQ(result.success, true); ASSERT_EQ(result.is_first_item, true);
PipelineConsumeResult consume_result = pipeline->Consume( [&test_val](std::unique_ptr<int> v) { ASSERT_EQ(*v, test_val); });
ASSERT_EQ(consume_result, PipelineConsumeResult::Done);}
TEST(PipelineTest, ContinuationCanOnlyBeUsedOnce) { std::shared_ptr<IntPipeline> pipeline = std::make_shared<IntPipeline>(2);
Continuation continuation = pipeline->Produce();
const int test_val = 1; PipelineProduceResult result = continuation.Complete(std::make_unique<int>(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<int> v) { ASSERT_EQ(*v, test_val); });
result = continuation.Complete(std::make_unique<int>(test_val)); ASSERT_EQ(result.success, false); ASSERT_EQ(consume_result_1, PipelineConsumeResult::Done);
PipelineConsumeResult consume_result_2 = pipeline->Consume([](std::unique_ptr<int> v) { FAIL(); });
result = continuation.Complete(std::make_unique<int>(test_val)); ASSERT_EQ(result.success, false); ASSERT_EQ(consume_result_2, PipelineConsumeResult::NoneAvailable);}
TEST(PipelineTest, PushingMoreThanDepthCompletesFirstSubmission) { const int depth = 1; std::shared_ptr<IntPipeline> pipeline = std::make_shared<IntPipeline>(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<int>(test_val_1)); ASSERT_EQ(result.success, true); ASSERT_EQ(result.is_first_item, true); result = continuation_2.Complete(std::make_unique<int>(test_val_2)); ASSERT_EQ(result.success, false);
PipelineConsumeResult consume_result_1 = pipeline->Consume( [&test_val_1](std::unique_ptr<int> v) { ASSERT_EQ(*v, test_val_1); });
ASSERT_EQ(consume_result_1, PipelineConsumeResult::Done);}
TEST(PipelineTest, PushingMultiProcessesInOrder) { const int depth = 2; std::shared_ptr<IntPipeline> pipeline = std::make_shared<IntPipeline>(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<int>(test_val_1)); ASSERT_EQ(result.success, true); ASSERT_EQ(result.is_first_item, true); result = continuation_2.Complete(std::make_unique<int>(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<int> 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<int> v) { ASSERT_EQ(*v, test_val_2); }); ASSERT_EQ(consume_result_2, PipelineConsumeResult::Done);}
TEST(PipelineTest, ProduceIfEmptyDoesNotConsumeWhenQueueIsNotEmpty) { const int depth = 2; std::shared_ptr<IntPipeline> pipeline = std::make_shared<IntPipeline>(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<int>(test_val_1)); ASSERT_EQ(result.success, true); ASSERT_EQ(result.is_first_item, true); result = continuation_2.Complete(std::make_unique<int>(test_val_2)); ASSERT_EQ(result.success, false);
PipelineConsumeResult consume_result_1 = pipeline->Consume( [&test_val_1](std::unique_ptr<int> v) { ASSERT_EQ(*v, test_val_1); }); ASSERT_EQ(consume_result_1, PipelineConsumeResult::Done);}
TEST(PipelineTest, ProduceIfEmptySuccessfulIfQueueIsEmpty) { const int depth = 1; std::shared_ptr<IntPipeline> pipeline = std::make_shared<IntPipeline>(depth);
Continuation continuation_1 = pipeline->ProduceIfEmpty();
const int test_val_1 = 1; PipelineProduceResult result = continuation_1.Complete(std::make_unique<int>(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<int> v) { ASSERT_EQ(*v, test_val_1); }); ASSERT_EQ(consume_result_1, PipelineConsumeResult::Done);}
} // namespace testing} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748// Copyright 2013 The Flutter 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 <memory>
#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<PlatformMessage> 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<fml::Mapping> 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_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233// Copyright 2013 The Flutter 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 <utility>
#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<VsyncWaiter> 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<VsyncWaiterFallback>(task_runners_);}
void PlatformView::DispatchPlatformMessage( std::unique_ptr<PlatformMessage> message) { delegate_.OnPlatformViewDispatchPlatformMessage(std::move(message));}
void PlatformView::DispatchPointerDataPacket( std::unique_ptr<PointerDataPacket> 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> 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<GrDirectContext> 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<impeller::Context> PlatformView::GetImpellerContext() const { return nullptr;}
void PlatformView::ReleaseResourceContext() const {}
PointerDataDispatcherMaker PlatformView::GetDispatcherMaker() { return [](DefaultPointerDataDispatcher::Delegate& delegate) { return std::make_unique<DefaultPointerDataDispatcher>(delegate); };}
fml::WeakPtr<PlatformView> 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<PlatformMessage> message) { if (auto response = message->response()) { response->CompleteEmpty(); }}
void PlatformView::OnPreEngineRestart() const {}
void PlatformView::RegisterTexture(std::shared_ptr<flutter::Texture> 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<Surface> 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<ExternalViewEmbedder>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<std::vector<std::string>>PlatformView::ComputePlatformResolvedLocales( const std::vector<std::string>& supported_locale_data) { std::unique_ptr<std::vector<std::string>> out = std::make_unique<std::vector<std::string>>(); return out;}
void PlatformView::RequestDartDeferredLibrary(intptr_t loading_unit_id) {}
void PlatformView::LoadDartDeferredLibrary( intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> 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<AssetResolver> updated_asset_resolver, AssetResolver::AssetResolverType type) { delegate_.UpdateAssetResolverByType(std::move(updated_asset_resolver), type);}
std::unique_ptr<SnapshotSurfaceProducer>PlatformView::CreateSnapshotSurfaceProducer() { return nullptr;}
std::shared_ptr<PlatformMessageHandler>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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994// Copyright 2013 The Flutter 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 <functional>#include <memory>
#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<void(bool added)>; using RemoveViewCallback = std::function<void(bool removed)>; //---------------------------------------------------------------------------- /// @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<void(bool)>; //-------------------------------------------------------------------------- /// @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> 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<PlatformMessage> 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<PointerDataPacket> 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> 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<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> 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<AssetResolver> 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<VsyncWaiter> 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<PlatformMessage> 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<PlatformMessage> 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<GrDirectContext> CreateResourceContext() const;
virtual std::shared_ptr<impeller::Context> 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<PlatformView> 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<PointerDataPacket> 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<flutter::Texture> 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<std::vector<std::string>> ComputePlatformResolvedLocales( const std::vector<std::string>& supported_locale_data);
virtual std::shared_ptr<ExternalViewEmbedder> 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<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> 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<AssetResolver> 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<SnapshotSurfaceProducer> 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<PlatformMessageHandler> 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<Surface> CreateRenderingSurface();
PlatformView::Delegate& delegate_; const TaskRunners task_runners_; fml::WeakPtrFactory<PlatformView> weak_factory_; // Must be the last member.
private: FML_DISALLOW_COPY_AND_ASSIGN(PlatformView);};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_PLATFORM_VIEW_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475// Copyright 2013 The Flutter 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<PointerDataPacket> 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<PointerDataPacket> 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<uintptr_t>(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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177// Copyright 2013 The Flutter 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<PointerDataPacket> 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<PointerDataPacket> 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<PointerDataPacket> 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<PointerDataPacket> 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<PointerDataPacket> pending_packet_; int pending_trace_flow_id_ = -1; bool is_pointer_data_in_progress_ = false;
// WeakPtrFactory must be the last member. fml::WeakPtrFactory<SmoothPointerDataDispatcher> weak_factory_; FML_DISALLOW_COPY_AND_ASSIGN(SmoothPointerDataDispatcher);};
//--------------------------------------------------------------------------/// @brief Signature for constructing PointerDataDispatcher.////// @param[in] delegate the `Flutter::Engine`///using PointerDataDispatcherMaker = std::function<std::unique_ptr<PointerDataDispatcher>( PointerDataDispatcher::Delegate&)>;
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_POINTER_DATA_DISPATCHER_H_12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169// Copyright 2013 The Flutter 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 <algorithm>#include <memory>#include <utility>
#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<flutter::CompositorContext>(*this)), snapshot_controller_( SnapshotController::Make(*this, delegate.GetSettings())), weak_factory_(this) { FML_DCHECK(compositor_context_);}
Rasterizer::~Rasterizer() = default;
fml::TaskRunnerAffineWeakPtr<Rasterizer> Rasterizer::GetWeakPtr() const { return weak_factory_.GetWeakPtr();}
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> Rasterizer::GetSnapshotDelegate() const { return weak_factory_.GetWeakPtr();}
void Rasterizer::SetImpellerContext( std::weak_ptr<impeller::Context> impeller_context) { impeller_context_ = std::move(impeller_context);}
void Rasterizer::Setup(std::unique_ptr<Surface> 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<DrawSurfaceStatus> 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<DrawSurfaceStatus>(); }}
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<flutter::TextureRegistry> 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<FrameTimingsRecorder> frame_timings_recorder) { if (!surface_) { return; } std::vector<std::unique_ptr<LayerTreeTask>> 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<FramePipeline>& 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<FrameItem> 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 !SLIMPELLERnamespace {std::unique_ptr<SnapshotDelegate::GpuImageResult> MakeBitmapImage( const sk_sp<DisplayList>& 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<SnapshotDelegate::GpuImageResult>( 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<SkSurface> surface = SkSurfaces::Raster(image_info); auto canvas = DlSkCanvasAdapter(surface->getCanvas()); canvas.Clear(DlColor::kTransparent()); canvas.DrawDisplayList(display_list);
sk_sp<SkImage> image = surface->makeImageSnapshot(); return std::make_unique<SnapshotDelegate::GpuImageResult>( GrBackendTexture(), nullptr, image, image ? "" : "Unable to create image");}} // namespace#endif // !SLIMPELLER
std::unique_ptr<Rasterizer::GpuImageResult> Rasterizer::MakeSkiaGpuImage( sk_sp<DisplayList> 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<SnapshotDelegate::GpuImageResult> 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<SnapshotDelegate::GpuImageResult>( 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<SkSurface> sk_surface = SkSurfaces::WrapBackendTexture( context, texture, kTopLeft_GrSurfaceOrigin, /*sampleCnt=*/0, image_info.colorType(), image_info.refColorSpace(), nullptr); if (!sk_surface) { result = std::make_unique<SnapshotDelegate::GpuImageResult>( 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<SnapshotDelegate::GpuImageResult>( texture, sk_ref_sp(context), nullptr, ""); })); return result;#endif // !SLIMPELLER}
void Rasterizer::MakeRasterSnapshot( sk_sp<DisplayList> display_list, SkISize picture_size, std::function<void(sk_sp<DlImage>)> callback) { return snapshot_controller_->MakeRasterSnapshot(display_list, picture_size, callback);}
sk_sp<DlImage> Rasterizer::MakeRasterSnapshotSync( sk_sp<DisplayList> display_list, SkISize picture_size) { return snapshot_controller_->MakeRasterSnapshotSync(display_list, picture_size);}
sk_sp<SkImage> Rasterizer::ConvertToRasterImage(sk_sp<SkImage> image) { TRACE_EVENT0("flutter", __FUNCTION__); return snapshot_controller_->ConvertToRasterImage(image);}
// |SnapshotDelegate|void Rasterizer::CacheRuntimeStage( const std::shared_ptr<impeller::RuntimeStage>& 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<FrameTimingsRecorder> frame_timings_recorder, std::vector<std::unique_ptr<LayerTreeTask>> 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<std::unique_ptr<LayerTreeTask>> 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<FrameItem> Rasterizer::DrawToSurfacesUnsafe( FrameTimingsRecorder& frame_timings_recorder, std::vector<std::unique_ptr<LayerTreeTask>> 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<fml::TimePoint> 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<std::unique_ptr<LayerTreeTask>> resubmitted_tasks; for (std::unique_ptr<LayerTreeTask>& task : tasks) { int64_t view_id = task->view_id; std::unique_ptr<LayerTree> 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<LayerTreeTask>( view_id, std::move(layer_tree), device_pixel_ratio); } else if (status == DrawSurfaceStatus::kRetry) { resubmitted_tasks.push_back(std::make_unique<LayerTreeTask>( 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<FrameItem>( std::move(resubmitted_tasks), frame_timings_recorder.CloneUntil( FrameTimingsRecorder::State::kBuildEnd)); }}
/// \see Rasterizer::DrawToSurfacesDrawSurfaceStatus Rasterizer::DrawToSurfaceUnsafe( int64_t view_id, flutter::LayerTree& layer_tree, float device_pixel_ratio, std::optional<fml::TimePoint> 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<FrameDamage> 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<FrameDamage>(); 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<SkData> 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<SkData> { 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<impeller::AiksContext>& 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_RENDERINGRasterizer::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<sk_sp<SkData>, Rasterizer::ScreenshotFormat>ScreenshotLayerTreeAsImageImpeller( const std::shared_ptr<impeller::AiksContext>& 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<impeller::Texture> 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<SkData> 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<sk_sp<SkData>, 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<OffscreenSurface> snapshot_surface = std::make_unique<OffscreenSurface>(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<sk_sp<SkData>, 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<ExternalViewEmbedder>& view_embedder) { external_view_embedder_ = view_embedder;}
void Rasterizer::SetSnapshotSurfaceProducer( std::unique_ptr<SnapshotSurfaceProducer> producer) { snapshot_surface_producer_ = std::move(producer);}
fml::RefPtr<fml::RasterThreadMerger> 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<size_t> 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<SkData> 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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779// Copyright 2013 The Flutter 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 <memory>#include <optional>#include <unordered_map>
#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_RENDERINGnamespace 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<std::unique_ptr<LayerTreeTask>> tasks, std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) : layer_tree_tasks(std::move(tasks)), frame_timings_recorder(std::move(frame_timings_recorder)) {} std::vector<std::unique_ptr<LayerTreeTask>> layer_tree_tasks; std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder;};
using FramePipeline = Pipeline<FrameItem>;
//------------------------------------------------------------------------------/// 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<fml::RasterThreadMerger> 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<const fml::SyncSwitch> 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> 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> 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<Rasterizer> GetWeakPtr() const;
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> 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<FrameTimingsRecorder> frame_timings_recorder);
// |SnapshotDelegate| GrDirectContext* GetGrContext() override;
std::shared_ptr<flutter::TextureRegistry> 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<FramePipeline>& 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<SkData> 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<SkData> 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<ExternalViewEmbedder>& 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<SnapshotSurfaceProducer> 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<fml::RasterThreadMerger> 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<size_t> 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<DrawSurfaceStatus> 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<FrameItem> resubmitted_item; };
struct ViewRecord { std::unique_ptr<LayerTreeTask> last_successful_task; std::optional<DrawSurfaceStatus> last_draw_status; };
// |SnapshotDelegate| std::unique_ptr<GpuImageResult> MakeSkiaGpuImage( sk_sp<DisplayList> display_list, const SkImageInfo& image_info) override;
// |SnapshotDelegate| void MakeRasterSnapshot( sk_sp<DisplayList> display_list, SkISize picture_size, std::function<void(sk_sp<DlImage>)> callback) override;
// |SnapshotDelegate| sk_sp<DlImage> MakeRasterSnapshotSync(sk_sp<DisplayList> display_list, SkISize picture_size) override;
// |SnapshotDelegate| sk_sp<SkImage> ConvertToRasterImage(sk_sp<SkImage> image) override;
// |SnapshotDelegate| void CacheRuntimeStage( const std::shared_ptr<impeller::RuntimeStage>& 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<Surface>& 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<impeller::AiksContext> GetAiksContext() const override {#if IMPELLER_SUPPORTS_RENDERING if (surface_) { return surface_->GetAiksContext(); } if (auto context = impeller_context_.lock()) { return std::make_shared<impeller::AiksContext>( context, impeller::TypographerContextSkia::Make()); }#endif return nullptr; }
// |SnapshotController::Delegate| const std::unique_ptr<SnapshotSurfaceProducer>& GetSnapshotSurfaceProducer() const override { return snapshot_surface_producer_; }
// |SnapshotController::Delegate| std::shared_ptr<const fml::SyncSwitch> GetIsGpuDisabledSyncSwitch() const override { return delegate_.GetIsGpuDisabledSyncSwitch(); }
std::pair<sk_sp<SkData>, 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<FrameTimingsRecorder> frame_timings_recorder, std::vector<std::unique_ptr<LayerTreeTask>> tasks);
// This method pushes the frame timing recorder from build end to raster end. DoDrawResult DrawToSurfaces( FrameTimingsRecorder& frame_timings_recorder, std::vector<std::unique_ptr<LayerTreeTask>> 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<FrameItem> DrawToSurfacesUnsafe( FrameTimingsRecorder& frame_timings_recorder, std::vector<std::unique_ptr<LayerTreeTask>> 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<fml::TimePoint> 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> impeller_context_; std::unique_ptr<Surface> surface_; std::unique_ptr<SnapshotSurfaceProducer> snapshot_surface_producer_; std::unique_ptr<flutter::CompositorContext> compositor_context_; std::unordered_map<int64_t, ViewRecord> view_records_; fml::closure next_frame_callback_; bool user_override_resource_cache_bytes_ = false; std::optional<size_t> max_cache_bytes_; fml::RefPtr<fml::RasterThreadMerger> raster_thread_merger_; std::shared_ptr<ExternalViewEmbedder> external_view_embedder_; std::unique_ptr<SnapshotController> snapshot_controller_;
// WeakPtrFactory must be the last member. fml::TaskRunnerAffineWeakPtrFactory<Rasterizer> weak_factory_; FML_DISALLOW_COPY_AND_ASSIGN(Rasterizer);};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_RASTERIZER_H_1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411// Copyright 2013 The Flutter 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 <memory>#include <optional>
#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<std::unique_ptr<LayerTreeTask>> SingleLayerTreeList( int64_t view_id, std::unique_ptr<LayerTree> layer_tree, float pixel_ratio) { std::vector<std::unique_ptr<LayerTreeTask>> tasks; tasks.push_back(std::make_unique<LayerTreeTask>( 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<fml::RasterThreadMerger>, GetParentRasterThreadMerger, (), (const, override)); MOCK_METHOD(std::shared_ptr<const fml::SyncSwitch>, 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<SurfaceFrame>, AcquireFrame, (const SkISize& size), (override)); MOCK_METHOD(SkMatrix, GetRootTransformation, (), (const, override)); MOCK_METHOD(GrDirectContext*, GetContext, (), (override)); MOCK_METHOD(std::unique_ptr<GLContextResult>, 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<fml::RasterThreadMerger>& 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<EmbeddedViewParams> params), (override)); MOCK_METHOD( PostPrerollResult, PostPrerollAction, (const fml::RefPtr<fml::RasterThreadMerger>& 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<impeller::AiksContext>& aiks_context, std::unique_ptr<SurfaceFrame> frame), (override)); MOCK_METHOD( void, EndFrame, (bool should_resubmit_frame, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger), (override)); MOCK_METHOD(bool, SupportsDynamicThreadMerging, (), (override));};} // namespace
TEST(RasterizerTest, create) { NiceMock<MockDelegate> delegate; Settings settings; ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); auto rasterizer = std::make_unique<Rasterizer>(delegate); EXPECT_TRUE(rasterizer != nullptr);}
TEST(RasterizerTest, isAiksContextInitialized) { NiceMock<MockDelegate> delegate; Settings settings; ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); auto rasterizer = std::make_shared<Rasterizer>(delegate);
EXPECT_TRUE(rasterizer != nullptr); std::shared_ptr<SnapshotController::Delegate> snapshot_delegate = rasterizer;
EXPECT_FALSE(snapshot_delegate->IsAiksContextInitialized());}
static std::unique_ptr<FrameTimingsRecorder> CreateFinishedBuildRecorder( fml::TimePoint timestamp) { std::unique_ptr<FrameTimingsRecorder> recorder = std::make_unique<FrameTimingsRecorder>(); recorder->RecordVsync(timestamp, timestamp); recorder->RecordBuildStart(timestamp); recorder->RecordBuildEnd(timestamp); return recorder;}
static std::unique_ptr<FrameTimingsRecorder> 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<MockDelegate> delegate; Settings settings; ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); ON_CALL(delegate, GetTaskRunners()).WillByDefault(ReturnRef(task_runners)); auto rasterizer = std::make_unique<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); EXPECT_CALL(*surface, MakeRenderContextCurrent()) .WillOnce(Return(ByMove(std::make_unique<GLContextDefaultResult>(true)))); rasterizer->Setup(std::move(surface)); fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>();
std::shared_ptr<NiceMock<MockExternalViewEmbedder>> external_view_embedder = std::make_shared<NiceMock<MockExternalViewEmbedder>>(); rasterizer->SetExternalViewEmbedder(external_view_embedder);
SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true;
auto surface_frame = std::make_unique<SurfaceFrame>( /*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<GLContextDefaultResult>(true))));
EXPECT_CALL(*external_view_embedder, BeginFrame(/*context=*/nullptr, /*raster_thread_merger=*/ fml::RefPtr<fml::RasterThreadMerger>(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<fml::RasterThreadMerger>( nullptr))) .Times(1);
rasterizer->Setup(std::move(surface)); fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>(/*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); std::shared_ptr<NiceMock<MockExternalViewEmbedder>> external_view_embedder = std::make_shared<NiceMock<MockExternalViewEmbedder>>(); 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<SurfaceFrame>( /*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<GLContextDefaultResult>(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<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>();
std::shared_ptr<NiceMock<MockExternalViewEmbedder>> external_view_embedder = std::make_shared<NiceMock<MockExternalViewEmbedder>>(); rasterizer->SetExternalViewEmbedder(external_view_embedder);
SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true;
auto surface_frame = std::make_unique<SurfaceFrame>( /*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<GLContextDefaultResult>(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<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>(/*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>();
std::shared_ptr<NiceMock<MockExternalViewEmbedder>> external_view_embedder = std::make_shared<NiceMock<MockExternalViewEmbedder>>(); rasterizer->SetExternalViewEmbedder(external_view_embedder);
SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true;
auto surface_frame1 = std::make_unique<SurfaceFrame>( /*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<SurfaceFrame>( /*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<GLContextDefaultResult>(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<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>(/*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> delegate; Settings settings; ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); EXPECT_CALL(delegate, GetTaskRunners()) .WillRepeatedly(ReturnRef(task_runners)); auto rasterizer = std::make_unique<Rasterizer>(delegate);
std::shared_ptr<NiceMock<MockExternalViewEmbedder>> external_view_embedder = std::make_shared<NiceMock<MockExternalViewEmbedder>>(); rasterizer->SetExternalViewEmbedder(external_view_embedder);
EXPECT_CALL( *external_view_embedder, EndFrame(/*should_resubmit_frame=*/false, /*raster_thread_merger=*/fml::RefPtr<fml::RasterThreadMerger>( nullptr))) .Times(0);
fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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<const fml::SyncSwitch>(false); ON_CALL(delegate, GetIsGpuDisabledSyncSwitch()) .WillByDefault(Return(is_gpu_disabled_sync_switch));
auto rasterizer = std::make_unique<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); EXPECT_CALL(*surface, MakeRenderContextCurrent()) .WillOnce(Return(ByMove(std::make_unique<GLContextDefaultResult>(true))));
std::shared_ptr<NiceMock<MockExternalViewEmbedder>> external_view_embedder = std::make_shared<NiceMock<MockExternalViewEmbedder>>(); 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<fml::RasterThreadMerger>( nullptr))) .Times(0);
fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> delegate; Settings settings; ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); EXPECT_CALL(delegate, GetTaskRunners()) .WillRepeatedly(ReturnRef(task_runners));
auto rasterizer = std::make_unique<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); EXPECT_CALL(*surface, MakeRenderContextCurrent()) .WillOnce(Return(ByMove(std::make_unique<GLContextDefaultResult>(true))));
std::shared_ptr<NiceMock<MockExternalViewEmbedder>> external_view_embedder = std::make_shared<NiceMock<MockExternalViewEmbedder>>(); 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<fml::RasterThreadMerger>( nullptr))) .Times(0);
fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); std::shared_ptr<NiceMock<MockExternalViewEmbedder>> external_view_embedder = std::make_shared<NiceMock<MockExternalViewEmbedder>>(); 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<SurfaceFrame>( /*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<GLContextDefaultResult>(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<FramePipeline>(/*depth=*/10); std::vector<std::unique_ptr<LayerTreeTask>> tasks; tasks.push_back(std::make_unique<LayerTreeTask>( 0, std::make_unique<LayerTree>(nullptr, DlISize()), 1.5)); tasks.push_back(std::make_unique<LayerTreeTask>( 1, std::make_unique<LayerTree>(nullptr, DlISize()), 2.0)); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); auto is_gpu_disabled_sync_switch = std::make_shared<const fml::SyncSwitch>(false);
SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true; auto surface_frame = std::make_unique<SurfaceFrame>( /*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<GLContextDefaultResult>(true))));
rasterizer->Setup(std::move(surface)); fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); auto is_gpu_disabled_sync_switch = std::make_shared<const fml::SyncSwitch>(true);
SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true;
auto surface_frame = std::make_unique<SurfaceFrame>( /*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<GLContextDefaultResult>(true))));
rasterizer->Setup(std::move(surface)); fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); auto is_gpu_disabled_sync_switch = std::make_shared<const fml::SyncSwitch>(false);
SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true;
auto surface_frame = std::make_unique<SurfaceFrame>( /*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<GLContextDefaultResult>(true))));
rasterizer->Setup(std::move(surface)); fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); auto is_gpu_disabled_sync_switch = std::make_shared<const fml::SyncSwitch>(true);
SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true;
auto surface_frame = std::make_unique<SurfaceFrame>( /*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<GLContextDefaultResult>(true))));
rasterizer->Setup(std::move(surface)); fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); auto is_gpu_disabled_sync_switch = std::make_shared<const fml::SyncSwitch>(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<GLContextDefaultResult>(true)))); rasterizer->Setup(std::move(surface)); fml::AutoResetWaitableEvent latch; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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> rasterizer; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { rasterizer = std::make_unique<Rasterizer>(delegate); latch.Signal(); }); latch.Wait();
auto surface = std::make_unique<NiceMock<MockSurface>>(); 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<SurfaceFrame>( /*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<GLContextDefaultResult>(true); }));
fml::CountDownLatch count_down_latch(2); auto first_timestamp = fml::TimePoint::Now(); auto second_timestamp = first_timestamp + fml::TimeDelta::FromMilliseconds(8); std::vector<fml::TimePoint> 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<FramePipeline>(/*depth=*/10); for (int i = 0; i < 2; i++) { auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> delegate; Settings settings; ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); EXPECT_CALL(delegate, GetTaskRunners()) .WillRepeatedly(ReturnRef(task_runners));
auto rasterizer = std::make_unique<Rasterizer>(delegate); auto surface = std::make_unique<NiceMock<MockSurface>>(); auto context = GrDirectContext::MakeMock(nullptr); context->setResourceCacheLimit(0);
EXPECT_CALL(*surface, MakeRenderContextCurrent()) .WillRepeatedly([]() -> std::unique_ptr<GLContextResult> { return std::make_unique<GLContextDefaultResult>(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<MockDelegate> delegate; Settings settings; ON_CALL(delegate, GetSettings()).WillByDefault(ReturnRef(settings)); EXPECT_CALL(delegate, GetTaskRunners()) .WillRepeatedly(ReturnRef(task_runners));
auto rasterizer = std::make_unique<Rasterizer>(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<MockDelegate> 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> rasterizer; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { rasterizer = std::make_unique<Rasterizer>(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<fml::TimePoint> timestamps = {first_timestamp, second_timestamp};
int frames_submitted = 0; fml::CountDownLatch submit_latch(2); auto surface = std::make_unique<MockSurface>(); 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<SurfaceFrame>( /*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<GLContextDefaultResult>(true); }));
thread_host.raster_thread->GetTaskRunner()->PostTask([&] { rasterizer->Setup(std::move(surface)); auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); for (int i = 0; i < 2; i++) { auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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<MockDelegate> 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> rasterizer; thread_host.raster_thread->GetTaskRunner()->PostTask([&] { rasterizer = std::make_unique<Rasterizer>(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<MockSurface>(); 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<SurfaceFrame>( /*surface=*/nullptr, framebuffer_info, /*submit_callback=*/ [&](const SurfaceFrame& frame, DlCanvas*) { const std::optional<fml::TimePoint> 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<GLContextDefaultResult>(true); }));
thread_host.raster_thread->GetTaskRunner()->PostTask([&] { rasterizer->Setup(std::move(surface)); auto pipeline = std::make_shared<FramePipeline>(/*depth=*/10); auto layer_tree = std::make_unique<LayerTree>( /*root_layer=*/nullptr, /*frame_size=*/DlISize()); auto layer_tree_item = std::make_unique<FrameItem>( 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 flutter12345678910111213141516171819202122232425// Copyright 2013 The Flutter 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<size_t>::max(); std::vector<fml::WeakPtr<ResourceCacheLimitItem>> 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 flutter12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849// Copyright 2013 The Flutter 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 <cstdint>#include <unordered_map>
#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<ResourceCacheLimitItem>& 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<fml::WeakPtr<ResourceCacheLimitItem>> items_; size_t max_bytes_threshold_; FML_DISALLOW_COPY_AND_ASSIGN(ResourceCacheLimitCalculator);};} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_RESOURCE_CACHE_LIMIT_CALCULATOR_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354// Copyright 2013 The Flutter 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<TestResourceCacheLimitItem> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
private: size_t resource_cache_limit_; fml::WeakPtrFactory<TestResourceCacheLimitItem> weak_factory_;};
TEST(ResourceCacheLimitCalculatorTest, GetResourceCacheMaxBytes) { ResourceCacheLimitCalculator calculator(800U); auto item1 = std::make_unique<TestResourceCacheLimitItem>(100.0); calculator.AddResourceCacheLimitItem(item1->GetWeakPtr()); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(100U));
auto item2 = std::make_unique<TestResourceCacheLimitItem>(200.0); calculator.AddResourceCacheLimitItem(item2->GetWeakPtr()); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(300U));
auto item3 = std::make_unique<TestResourceCacheLimitItem>(300.0); calculator.AddResourceCacheLimitItem(item3->GetWeakPtr()); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(600U));
auto item4 = std::make_unique<TestResourceCacheLimitItem>(400.0); calculator.AddResourceCacheLimitItem(item4->GetWeakPtr()); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(800U));
item3.reset(); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(700U));
item2.reset(); EXPECT_EQ(calculator.GetResourceCacheMaxBytes(), static_cast<size_t>(500U));}
} // namespace testing} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122// Copyright 2013 The Flutter 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 <sstream>#include <utility>
#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<fml::TaskRunner>& io_worker, IsolateLaunchType launch_type) { auto asset_manager = std::make_shared<AssetManager>();
if (fml::UniqueFD::traits_type::IsValid(settings.assets_dir)) { asset_manager->PushBack(std::make_unique<DirectoryAssetBundle>( fml::Duplicate(settings.assets_dir), true)); }
asset_manager->PushBack(std::make_unique<DirectoryAssetBundle>( 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<IsolateConfiguration> configuration) : RunConfiguration(std::move(configuration), std::make_shared<AssetManager>()) {#if !SLIMPELLER PersistentCache::SetAssetManager(asset_manager_);#endif // !SLIMPELLER}
RunConfiguration::RunConfiguration( std::unique_ptr<IsolateConfiguration> configuration, std::shared_ptr<AssetManager> 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<AssetResolver> 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<std::string> entrypoint_args) { entrypoint_args_ = std::move(entrypoint_args);}
std::shared_ptr<AssetManager> 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<std::string>& 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<int64_t> RunConfiguration::GetEngineId() const { return engine_id_;}
std::unique_ptr<IsolateConfiguration>RunConfiguration::TakeIsolateConfiguration() { return std::move(isolate_configuration_);}
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219// Copyright 2013 The Flutter 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 <memory>#include <string>
#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<fml::TaskRunner>& 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<IsolateConfiguration> 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<IsolateConfiguration> configuration, std::shared_ptr<AssetManager> 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<AssetResolver> 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<std::string> entrypoint_args);
//---------------------------------------------------------------------------- /// @return The asset manager referencing all previously registered asset /// resolvers. /// std::shared_ptr<AssetManager> 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<String> to Dart's entrypoint /// function. /// const std::vector<std::string>& 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<IsolateConfiguration> 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<int64_t> GetEngineId() const;
private: std::unique_ptr<IsolateConfiguration> isolate_configuration_; std::shared_ptr<AssetManager> asset_manager_; std::string entrypoint_ = "main"; std::string entrypoint_library_ = ""; std::vector<std::string> entrypoint_args_; std::optional<int64_t> engine_id_;
FML_DISALLOW_COPY_AND_ASSIGN(RunConfiguration);};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_RUN_CONFIGURATION_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081// Copyright 2013 The Flutter 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<SkData> SerializeTypefaceWithoutData(SkTypeface* typeface, void* ctx) { return SkData::MakeEmpty();}
sk_sp<SkData> SerializeTypefaceWithData(SkTypeface* typeface, void* ctx) { return typeface->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);}
sk_sp<SkTypeface> 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<SkData> SerializeImageWithoutData(SkImage* image, void* ctx) { const auto& info = image->imageInfo(); SkDynamicMemoryWStream stream;
ImageMetaData metadata = {info.width(), info.height(), static_cast<uint32_t>(info.colorType()), static_cast<uint32_t>(info.alphaType()), static_cast<bool>(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<SkImage> DeserializeImageWithoutData(const void* data, size_t length, void* ctx) { FML_CHECK(length >= sizeof(ImageMetaData)); auto metadata = static_cast<const ImageMetaData*>(data); sk_sp<SkColorSpace> color_space = nullptr; if (metadata->has_color_space) { color_space = SkColorSpace::Deserialize( static_cast<const uint8_t*>(data) + sizeof(ImageMetaData), length - sizeof(ImageMetaData)); }
auto image_size = SkISize::Make(metadata->width, metadata->height); auto info = SkImageInfo::Make( image_size, static_cast<SkColorType>(metadata->color_type), static_cast<SkAlphaType>(metadata->alpha_type), color_space); sk_sp<SkData> image_data = SkData::MakeUninitialized(image_size.width() * image_size.height() * 4); memset(image_data->writable_data(), 0x0f, image_data->size()); sk_sp<SkImage> image = SkImages::RasterFromData(info, image_data, image_size.width() * 4);
return image;};
} // namespace flutter12345678910111213141516171819202122232425262728// Copyright 2013 The Flutter 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<SkData> SerializeTypefaceWithoutData(SkTypeface* typeface, void* ctx);sk_sp<SkData> SerializeTypefaceWithData(SkTypeface* typeface, void* ctx);sk_sp<SkTypeface> DeserializeTypefaceWithoutData(const void* data, size_t length, void* ctx);
// Serializes only the metadata of the image and not the underlying pixel data.sk_sp<SkData> SerializeImageWithoutData(SkImage* image, void* ctx);sk_sp<SkImage> DeserializeImageWithoutData(const void* data, size_t length, void* ctx);
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_SERIALIZATION_CALLBACKS_H_12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297// Copyright 2013 The Flutter 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 <memory>#include <sstream>#include <utility>#include <vector>
#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<Engine> CreateEngine( Engine::Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm, const fml::RefPtr<const DartSnapshot>& isolate_snapshot, const TaskRunners& task_runners, const PlatformData& platform_data, const Settings& settings, std::unique_ptr<Animator> animator, const fml::WeakPtr<IOManager>& io_manager, const fml::RefPtr<SkiaUnrefQueue>& unref_queue, const fml::TaskRunnerAffineWeakPtr<SnapshotDelegate>& snapshot_delegate, const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch, impeller::RuntimeStageBackend runtime_stage_backend) { return std::make_unique<Engine>(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<DartVMRef, fml::RefPtr<const DartSnapshot>>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> Shell::Create( const PlatformData& platform_data, const TaskRunners& task_runners, Settings settings, const Shell::CreateCallback<PlatformView>& on_create_platform_view, const Shell::CreateCallback<Rasterizer>& 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<ResourceCacheLimitCalculator>( 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>& impeller_context) { if (!impeller_context) { return impeller::RuntimeStageBackend::kSkSL; } return impeller_context->GetRuntimeStageBackend();}
std::unique_ptr<Shell> Shell::CreateShellOnPlatformThread( DartVMRef vm, fml::RefPtr<fml::RasterThreadMerger> parent_merger, std::shared_ptr<ShellIOManager> parent_io_manager, const std::shared_ptr<ResourceCacheLimitCalculator>& resource_cache_limit_calculator, const TaskRunners& task_runners, const PlatformData& platform_data, const Settings& settings, fml::RefPtr<const DartSnapshot> isolate_snapshot, const Shell::CreateCallback<PlatformView>& on_create_platform_view, const Shell::CreateCallback<Rasterizer>& 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<Shell>( 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<std::unique_ptr<Rasterizer>> rasterizer_promise; auto rasterizer_future = rasterizer_promise.get_future(); std::promise<fml::TaskRunnerAffineWeakPtr<SnapshotDelegate>> 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> 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<std::shared_ptr<ShellIOManager>> io_manager_promise; auto io_manager_future = io_manager_promise.get_future(); std::promise<fml::WeakPtr<ShellIOManager>> weak_io_manager_promise; auto weak_io_manager_future = weak_io_manager_promise.get_future(); std::promise<fml::RefPtr<SkiaUnrefQueue>> 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<ShellIOManager> io_manager; if (parent_io_manager) { io_manager = parent_io_manager; } else { io_manager = std::make_shared<ShellIOManager>( 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<std::unique_ptr<Engine>> 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<Animator>(*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> Shell::CreateWithSnapshot( const PlatformData& platform_data, const TaskRunners& task_runners, const fml::RefPtr<fml::RasterThreadMerger>& parent_thread_merger, const std::shared_ptr<ShellIOManager>& parent_io_manager, const std::shared_ptr<ResourceCacheLimitCalculator>& resource_cache_limit_calculator, Settings settings, DartVMRef vm, fml::RefPtr<const DartSnapshot> isolate_snapshot, const Shell::CreateCallback<PlatformView>& on_create_platform_view, const Shell::CreateCallback<Rasterizer>& 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> 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<fml::RasterThreadMerger> parent_merger, const std::shared_ptr<ResourceCacheLimitCalculator>& 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<DisplayManager>(); 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<fml::TaskRunnerAffineWeakPtrFactory<Shell>>(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> Shell::Spawn( RunConfiguration run_configuration, const std::string& initial_route, const CreateCallback<PlatformView>& on_create_platform_view, const CreateCallback<Rasterizer>& 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<Shell> 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<const DartSnapshot>& isolate_snapshot, const TaskRunners& task_runners, const PlatformData& platform_data, const Settings& settings, std::unique_ptr<Animator> animator, const fml::WeakPtr<IOManager>& io_manager, const fml::RefPtr<SkiaUnrefQueue>& unref_queue, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, const std::shared_ptr<fml::SyncSwitch>& 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<void(Engine::RunStatus)>& 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<DartErrorCode> 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<PlatformView> platform_view, std::unique_ptr<Engine> engine, std::unique_ptr<Rasterizer> rasterizer, const std::shared_ptr<ShellIOManager>& 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<fml::RasterThreadMerger> Shell::GetParentRasterThreadMerger() const { return parent_raster_thread_merger_;}
fml::TaskRunnerAffineWeakPtr<Rasterizer> Shell::GetRasterizer() const { FML_DCHECK(is_set_up_); return weak_rasterizer_;}
fml::WeakPtr<Engine> Shell::GetEngine() { FML_DCHECK(is_set_up_); return weak_engine_;}
fml::WeakPtr<PlatformView> Shell::GetPlatformView() { FML_DCHECK(is_set_up_); return weak_platform_view_;}
fml::WeakPtr<ShellIOManager> 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> 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<GrDirectContext> 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<std::mutex> 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<PlatformMessage> 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<PointerDataPacket> 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<flutter::Texture> 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<FramePipeline> 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<FramePipeline>(pipeline)]() mutable { if (rasterizer) { std::shared_ptr<FramePipeline> 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<FrameTimingsRecorder> 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<PlatformMessage> 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<PlatformMessageHandler>(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<PlatformMessage> message) { const auto& data = message->data();
rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(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<size_t>(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<uint8_t> data = {'[', 't', 'r', 'u', 'e', ']'}; response->Complete( std::make_unique<fml::DataMapping>(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<std::vector<std::string>> Shell::ComputePlatformResolvedLocale( const std::vector<std::string>& supported_locale_data) { return platform_view_->ComputePlatformResolvedLocales(supported_locale_data);}
void Shell::LoadDartDeferredLibrary( intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> 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<AssetResolver> 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<std::mutex> 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<fml::TaskRunner> 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 handlerbool 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<const char*>(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 handlerbool 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<const char*>(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 handlerbool 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::FileMapping>(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<DirectoryAssetBundle>( 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 handlerbool 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<PersistentCache::SkSLCache> sksls = persistent_cache->LoadSkSLs(); for (const auto& sksl : sksls) { size_t b64_size = Base64::EncodedSize(sksl.value->size()); sk_sp<SkData> b64_data = SkData::MakeUninitialized(b64_size + 1); char* b64_char = static_cast<char*>(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<const char*>(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<uint64_t>("layerBytes", layer_cache_byte_size, response->GetAllocator()); response->AddMember<uint64_t>("pictureBytes", picture_cache_byte_size, response->GetAllocator()); return true;}
// Service protocol handlerbool 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<AssetManager>();
if (!asset_manager->PushFront(std::make_unique<DirectoryAssetBundle>( 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<rapidjson::StringBuffer> writer(buffer); document.Accept(writer); std::string message = buffer.GetString(); std::unique_ptr<PlatformMessage> fontsChangeMessage = std::make_unique<flutter::PlatformMessage>( 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<std::mutex> 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<const fml::SyncSwitch> 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<std::unique_ptr<Display>> displays) { FML_DCHECK(is_set_up_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());
std::vector<DisplayData> 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<PlatformMessageHandler>&Shell::GetPlatformMessageHandler() const { return platform_message_handler_;}
const std::weak_ptr<VsyncWaiter> Shell::GetVsyncWaiter() const { if (!engine_) { return {}; } return engine_->GetVsyncWaiter();}
const std::shared_ptr<fml::ConcurrentTaskRunner>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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815// Copyright 2013 The Flutter 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 <functional>#include <mutex>#include <string_view>#include <unordered_map>
#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 <class T> using CreateCallback = std::function<std::unique_ptr<T>(Shell&)>; typedef std::function<std::unique_ptr<Engine>( Engine::Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm, fml::RefPtr<const DartSnapshot> isolate_snapshot, TaskRunners task_runners, const PlatformData& platform_data, Settings settings, std::unique_ptr<Animator> animator, fml::WeakPtr<IOManager> io_manager, fml::RefPtr<SkiaUnrefQueue> unref_queue, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, const std::shared_ptr<fml::SyncSwitch>& 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<Shell> Create( const PlatformData& platform_data, const TaskRunners& task_runners, Settings settings, const CreateCallback<PlatformView>& on_create_platform_view, const CreateCallback<Rasterizer>& 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<Shell> Spawn( RunConfiguration run_configuration, const std::string& initial_route, const CreateCallback<PlatformView>& on_create_platform_view, const CreateCallback<Rasterizer>& 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<void(Engine::RunStatus)>& 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<fml::RasterThreadMerger> GetParentRasterThreadMerger() const override;
//---------------------------------------------------------------------------- /// @brief Rasterizers may only be accessed on the raster task runner. /// /// @return A weak pointer to the rasterizer. /// fml::TaskRunnerAffineWeakPtr<Rasterizer> 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<Engine> GetEngine();
//---------------------------------------------------------------------------- /// @brief Platform views may only be accessed on the platform task /// runner. /// /// @return A weak pointer to the platform view. /// fml::WeakPtr<PlatformView> GetPlatformView();
//---------------------------------------------------------------------------- /// @brief The IO Manager may only be accessed on the IO task runner. /// /// @return A weak pointer to the IO manager. /// fml::WeakPtr<ShellIOManager> 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<DartErrorCode> 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<const fml::SyncSwitch> 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<std::unique_ptr<Display>> 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<PlatformMessageHandler>& GetPlatformMessageHandler() const override;
const std::weak_ptr<VsyncWaiter> GetVsyncWaiter() const;
const std::shared_ptr<fml::ConcurrentTaskRunner> 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<DartVMRef, fml::RefPtr<const DartSnapshot>> InferVmInitDataFromSettings(Settings& settings);
private: using ServiceProtocolHandler = std::function<bool(const ServiceProtocol::Handler::ServiceProtocolMap&, rapidjson::Document*)>;
/// 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<std::string> misbehaving_message_channels_; const TaskRunners task_runners_; const fml::RefPtr<fml::RasterThreadMerger> parent_raster_thread_merger_; std::shared_ptr<ResourceCacheLimitCalculator> resource_cache_limit_calculator_; size_t resource_cache_limit_; const Settings settings_; DartVMRef vm_; mutable std::mutex time_recorder_mutex_; std::optional<fml::TimePoint> latest_frame_target_time_; std::unique_ptr<PlatformView> platform_view_; // on platform task runner std::unique_ptr<Engine> engine_; // on UI task runner std::unique_ptr<Rasterizer> rasterizer_; // on raster task runner std::shared_ptr<ShellIOManager> io_manager_; // on IO task runner std::shared_ptr<fml::SyncSwitch> is_gpu_disabled_sync_switch_; std::shared_ptr<PlatformMessageHandler> platform_message_handler_; std::atomic<bool> route_messages_through_platform_thread_ = false;
fml::WeakPtr<Engine> weak_engine_; // to be shared across threads fml::TaskRunnerAffineWeakPtr<Rasterizer> weak_rasterizer_; // to be shared across threads fml::WeakPtr<PlatformView> weak_platform_view_; // to be shared across threads
std::unordered_map<std::string_view, // method std::pair<fml::RefPtr<fml::TaskRunner>, 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<bool> 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<bool> 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<int64_t> unreported_timings_;
/// Manages the displays. This class is thread safe, can be accessed from /// any of the threads. std::unique_ptr<DisplayManager> 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<int64_t, SkISize> 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<fml::Milliseconds> 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<fml::RasterThreadMerger> parent_merger, const std::shared_ptr<ResourceCacheLimitCalculator>& resource_cache_limit_calculator, const Settings& settings, bool is_gpu_disabled);
static std::unique_ptr<Shell> CreateShellOnPlatformThread( DartVMRef vm, fml::RefPtr<fml::RasterThreadMerger> parent_merger, std::shared_ptr<ShellIOManager> parent_io_manager, const std::shared_ptr<ResourceCacheLimitCalculator>& resource_cache_limit_calculator, const TaskRunners& task_runners, const PlatformData& platform_data, const Settings& settings, fml::RefPtr<const DartSnapshot> isolate_snapshot, const Shell::CreateCallback<PlatformView>& on_create_platform_view, const Shell::CreateCallback<Rasterizer>& on_create_rasterizer, const EngineCreateCallback& on_create_engine, bool is_gpu_disabled);
static std::unique_ptr<Shell> CreateWithSnapshot( const PlatformData& platform_data, const TaskRunners& task_runners, const fml::RefPtr<fml::RasterThreadMerger>& parent_thread_merger, const std::shared_ptr<ShellIOManager>& parent_io_manager, const std::shared_ptr<ResourceCacheLimitCalculator>& resource_cache_limit_calculator, Settings settings, DartVMRef vm, fml::RefPtr<const DartSnapshot> isolate_snapshot, const CreateCallback<PlatformView>& on_create_platform_view, const CreateCallback<Rasterizer>& on_create_rasterizer, const EngineCreateCallback& on_create_engine, bool is_gpu_disabled);
bool Setup(std::unique_ptr<PlatformView> platform_view, std::unique_ptr<Engine> engine, std::unique_ptr<Rasterizer> rasterizer, const std::shared_ptr<ShellIOManager>& io_manager);
void ReportTimings();
// |PlatformView::Delegate| void OnPlatformViewCreated(std::unique_ptr<Surface> 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<PlatformMessage> message) override;
// |PlatformView::Delegate| void OnPlatformViewDispatchPointerDataPacket( std::unique_ptr<PointerDataPacket> 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<flutter::Texture> 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<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> 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<AssetResolver> 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<FramePipeline> pipeline) override;
// |Animator::Delegate| void OnAnimatorDrawLastLayerTrees( std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) override;
// |Engine::Delegate| void OnEngineUpdateSemantics( int64_t view_id, SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions) override;
// |Engine::Delegate| void OnEngineHandlePlatformMessage( std::unique_ptr<PlatformMessage> message) override;
void HandleEngineSkiaMessage(std::unique_ptr<PlatformMessage> 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<std::vector<std::string>> ComputePlatformResolvedLocale( const std::vector<std::string>& 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<fml::TaskRunner> 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<DirectoryAssetBundle> RestoreOriginalAssetResolver();
SkISize ExpectedFrameSize(int64_t view_id);
// For accessing the Shell via the raster thread, necessary for various // rasterizer callbacks. std::unique_ptr<fml::TaskRunnerAffineWeakPtrFactory<Shell>> weak_factory_gpu_;
fml::WeakPtrFactory<Shell> weak_factory_; friend class testing::ShellTest;
FML_DISALLOW_COPY_AND_ASSIGN(Shell);};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_SHELL_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123// Copyright 2013 The Flutter 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> shell; std::unique_ptr<ThreadHost> 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<std::unique_ptr<const fml::Mapping>> kernel_mappings; kernel_mappings.emplace_back( fml::FileMapping::CreateReadOnly(assets_dir, "kernel_blob.bin")); return kernel_mappings; }; }
thread_host = std::make_unique<ThreadHost>(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<PlatformView>(shell, shell.GetTaskRunners()); }, [](Shell& shell) { return std::make_unique<Rasterizer>(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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267// Copyright 2013 The Flutter 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 <time.h>#include <unistd.h>
#include <memory>
#include <fuchsia/intl/cpp/fidl.h>#include <fuchsia/settings/cpp/fidl.h>#include <lib/sys/cpp/component_context.h>
#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<sys::ComponentContext> ctx_; fuchsia::settings::IntlSyncPtr intl_;
fuchsia::settings::IntlSettings save_settings_;};
// These functions are used by tests that are currently disabled.#if falsestatic 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<bool()> 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<std::string>::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<bool>::SetReturnValue( args, continue_fixture); }));
auto settings = CreateSettingsForFixture(); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("timezonesChange");
std::unique_ptr<Shell> 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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127// Copyright 2013 The Flutter 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 <utility>
#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<GrDirectContext> ShellIOManager::CreateCompatibleResourceLoadingContext( GrBackendApi backend, const sk_sp<const GrGLInterface>& 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<GrDirectContext> resource_context, std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch, fml::RefPtr<fml::TaskRunner> unref_queue_task_runner, std::shared_ptr<impeller::Context> impeller_context, fml::TimeDelta unref_queue_drain_delay) : resource_context_(std::move(resource_context)), resource_context_weak_factory_( resource_context_ ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>( resource_context_.get()) : nullptr), unref_queue_(fml::MakeRefCounted<flutter::SkiaUnrefQueue>( 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<GrDirectContext> 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<GrDirectContext> resource_context) { resource_context_ = std::move(resource_context); resource_context_weak_factory_ = resource_context_ ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>( resource_context_.get()) : nullptr; unref_queue_->UpdateResourceContext(resource_context_);}
fml::WeakPtr<ShellIOManager> ShellIOManager::GetWeakPtr() { return weak_factory_.GetWeakPtr();}
// |IOManager|fml::WeakPtr<GrDirectContext> ShellIOManager::GetResourceContext() const { return resource_context_weak_factory_ ? resource_context_weak_factory_->GetWeakPtr() : fml::WeakPtr<GrDirectContext>();}
// |IOManager|fml::RefPtr<flutter::SkiaUnrefQueue> ShellIOManager::GetSkiaUnrefQueue() const { return unref_queue_;}
// |IOManager|fml::WeakPtr<IOManager> ShellIOManager::GetWeakIOManager() const { return weak_factory_.GetWeakPtr();}
// |IOManager|std::shared_ptr<const fml::SyncSwitch>ShellIOManager::GetIsGpuDisabledSyncSwitch() { return is_gpu_disabled_sync_switch_;}
// |IOManager|std::shared_ptr<impeller::Context> ShellIOManager::GetImpellerContext() const { return impeller_context_;}
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384// Copyright 2013 The Flutter 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 <memory>
#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<GrDirectContext> CreateCompatibleResourceLoadingContext( GrBackendApi backend, const sk_sp<const GrGLInterface>& gl_interface);
ShellIOManager( sk_sp<GrDirectContext> resource_context, std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch, fml::RefPtr<fml::TaskRunner> unref_queue_task_runner, std::shared_ptr<impeller::Context> 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<GrDirectContext> 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<GrDirectContext> resource_context);
fml::WeakPtr<ShellIOManager> GetWeakPtr();
// |IOManager| fml::WeakPtr<IOManager> GetWeakIOManager() const override;
// |IOManager| fml::WeakPtr<GrDirectContext> GetResourceContext() const override;
// |IOManager| fml::RefPtr<flutter::SkiaUnrefQueue> GetSkiaUnrefQueue() const override;
// |IOManager| std::shared_ptr<const fml::SyncSwitch> GetIsGpuDisabledSyncSwitch() override;
// |IOManager| std::shared_ptr<impeller::Context> GetImpellerContext() const override;
private: // Resource context management. sk_sp<GrDirectContext> resource_context_; std::unique_ptr<fml::WeakPtrFactory<GrDirectContext>> resource_context_weak_factory_; // Unref queue management. fml::RefPtr<flutter::SkiaUnrefQueue> unref_queue_; std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch_; std::shared_ptr<impeller::Context> impeller_context_; fml::WeakPtrFactory<ShellIOManager> weak_factory_;
FML_DISALLOW_COPY_AND_ASSIGN(ShellIOManager);};
} // namespace flutter
#endif // FLUTTER_SHELL_COMMON_SHELL_IO_MANAGER_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106// Copyright 2013 The Flutter 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<ImageGenerator> 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<TestGLSurface> gl_surface; std::unique_ptr<ShellIOManager> io_manager; fml::RefPtr<MultiFrameCodec> codec;
// Setup the IO manager. PostTaskSync(runners.GetIOTaskRunner(), [&]() { gl_surface = std::make_unique<TestGLSurface>(SkISize::Make(1, 1)); io_manager = std::make_unique<ShellIOManager>( gl_surface->CreateGrContext(), std::make_shared<fml::SyncSwitch>(), 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<MultiFrameCodec>(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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424// Copyright 2013 The Flutter 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<int64_t, ViewContent>();}
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<PlatformMessage> 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<PlatformMessage> 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<bool> 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<ShellTestPlatformView*>(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<double>(), // display features bounds std::vector<int>(), // display features type std::vector<int>(), // 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<FrameTimingsRecorder> recorder = std::make_unique<FrameTimingsRecorder>(); 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<RuntimeDelegate> 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<FrameTimingsRecorder> recorder = std::make_unique<FrameTimingsRecorder>(); 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<TransformLayer>(DlMatrix()); auto layer_tree = std::make_unique<LayerTree>( root_layer, DlISize(view_content.viewport_metrics.physical_width, view_content.viewport_metrics.physical_height)); float device_pixel_ratio = static_cast<float>( 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<PointerDataPacket>(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<PointerDataPacket> 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<fml::TaskRunner>& task_runner, const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { std::promise<bool> 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<txt::FontCollection> 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<Shell> ShellTest::CreateShell( const Settings& settings, std::optional<TaskRunners> task_runners) { return CreateShell({ .settings = settings, .task_runners = std::move(task_runners), });}
std::unique_ptr<Shell> ShellTest::CreateShell(const Config& config) { TaskRunners task_runners = config.task_runners.has_value() ? config.task_runners.value() : GetTaskRunnersForFixture(); Shell::CreateCallback<PlatformView> platform_view_create_callback = config.platform_view_create_callback; if (!platform_view_create_callback) { platform_view_create_callback = ShellTestPlatformViewBuilder({}); }
Shell::CreateCallback<Rasterizer> rasterizer_create_callback = [](Shell& shell) { return std::make_unique<Rasterizer>(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> shell) { DestroyShell(std::move(shell), GetTaskRunnersForFixture());}
void ShellTest::DestroyShell(std::unique_ptr<Shell> 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 flutterflutter/engine/src/flutter/shell/common/BUILD.gnAdded+369
flutter/engine/src/flutter/shell/common/animator.ccAdded+329
flutter/engine/src/flutter/shell/common/animator.hAdded+160
flutter/engine/src/flutter/shell/common/animator_unittests.ccAdded+267
flutter/engine/src/flutter/shell/common/base64.ccAdded+160
flutter/engine/src/flutter/shell/common/base64.hAdded+59
flutter/engine/src/flutter/shell/common/base64_unittests.ccAdded+122
flutter/engine/src/flutter/shell/common/context_options.ccAdded+47
flutter/engine/src/flutter/shell/common/context_options.hAdded+47
flutter/engine/src/flutter/shell/common/context_options_unittests.ccAdded+19
flutter/engine/src/flutter/shell/common/dart_native_benchmarks.ccAdded+108
flutter/engine/src/flutter/shell/common/display.ccAdded+11
flutter/engine/src/flutter/shell/common/display.hAdded+91
flutter/engine/src/flutter/shell/common/display_manager.ccAdded+32
flutter/engine/src/flutter/shell/common/display_manager.hAdded+41
flutter/engine/src/flutter/shell/common/dl_op_spy.ccAdded+156
flutter/engine/src/flutter/shell/common/dl_op_spy.hAdded+123
flutter/engine/src/flutter/shell/common/dl_op_spy_unittests.ccAdded+588
flutter/engine/src/flutter/shell/common/engine.ccAdded+646
flutter/engine/src/flutter/shell/common/engine.hAdded+1093
flutter/engine/src/flutter/shell/common/engine_animator_unittests.ccAdded+666
flutter/engine/src/flutter/shell/common/engine_unittests.ccAdded+560
flutter/engine/src/flutter/shell/common/input_events_unittests.ccAdded+446
flutter/engine/src/flutter/shell/common/persistent_cache_unittests.ccAdded+203
flutter/engine/src/flutter/shell/common/pipeline.ccAdded+14
flutter/engine/src/flutter/shell/common/pipeline.hAdded+260
flutter/engine/src/flutter/shell/common/pipeline_unittests.ccAdded+148
flutter/engine/src/flutter/shell/common/platform_message_handler.hAdded+48
flutter/engine/src/flutter/shell/common/platform_view.ccAdded+233
flutter/engine/src/flutter/shell/common/platform_view.hAdded+994
flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.ccAdded+75
flutter/engine/src/flutter/shell/common/pointer_data_dispatcher.hAdded+177
flutter/engine/src/flutter/shell/common/rasterizer.ccAdded+1169
flutter/engine/src/flutter/shell/common/rasterizer.hAdded+779
flutter/engine/src/flutter/shell/common/rasterizer_unittests.ccAdded+1411
flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.ccAdded+25
flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator.hAdded+49
flutter/engine/src/flutter/shell/common/resource_cache_limit_calculator_unittests.ccAdded+54
flutter/engine/src/flutter/shell/common/run_configuration.ccAdded+122
flutter/engine/src/flutter/shell/common/run_configuration.hAdded+219
flutter/engine/src/flutter/shell/common/serialization_callbacks.ccAdded+81
flutter/engine/src/flutter/shell/common/serialization_callbacks.hAdded+28
flutter/engine/src/flutter/shell/common/shell.ccAdded+2297
flutter/engine/src/flutter/shell/common/shell.hAdded+815
flutter/engine/src/flutter/shell/common/shell_benchmarks.ccAdded+123
flutter/engine/src/flutter/shell/common/shell_fuchsia_unittests.ccAdded+267
flutter/engine/src/flutter/shell/common/shell_io_manager.ccAdded+127
flutter/engine/src/flutter/shell/common/shell_io_manager.hAdded+84
flutter/engine/src/flutter/shell/common/shell_io_manager_unittests.ccAdded+106
flutter/engine/src/flutter/shell/common/shell_test.ccAdded+424