5#define RAPIDJSON_HAS_STDSTRING 1
6#include "flutter/shell/common/shell.h"
13#include "flutter/assets/directory_asset_bundle.h"
14#include "flutter/common/constants.h"
15#include "flutter/common/graphics/persistent_cache.h"
16#include "flutter/fml/base32.h"
17#include "flutter/fml/file.h"
18#include "flutter/fml/icu_util.h"
19#include "flutter/fml/log_settings.h"
20#include "flutter/fml/logging.h"
21#include "flutter/fml/make_copyable.h"
22#include "flutter/fml/message_loop.h"
23#include "flutter/fml/paths.h"
24#include "flutter/fml/trace_event.h"
25#include "flutter/runtime/dart_vm.h"
26#include "flutter/shell/common/base64.h"
27#include "flutter/shell/common/engine.h"
28#include "flutter/shell/common/skia_event_tracer_impl.h"
29#include "flutter/shell/common/switches.h"
30#include "flutter/shell/common/vsync_waiter.h"
32#include "rapidjson/stringbuffer.h"
33#include "rapidjson/writer.h"
34#include "third_party/dart/runtime/include/dart_tools_api.h"
55std::unique_ptr<Engine> CreateEngine(
63 std::unique_ptr<Animator> animator,
67 const std::shared_ptr<VolatilePathTracker>& volatile_path_tracker,
68 const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch,
70 return std::make_unique<Engine>(delegate,
81 volatile_path_tracker,
83 runtime_stage_backend);
86void RegisterCodecsWithSkia() {
114 static std::once_flag gShellSettingsInitialization = {};
115 std::call_once(gShellSettingsInitialization, [&
settings] {
123 if (!
settings.trace_allowlist.empty()) {
127 if (!
settings.skia_deterministic_rendering_on_cpu) {
130 FML_DLOG(INFO) <<
"Skia deterministic rendering is enabled.";
132 RegisterCodecsWithSkia();
134 if (
settings.icu_initialization_required) {
135 if (!
settings.icu_data_path.empty()) {
140 FML_DLOG(WARNING) <<
"Skipping ICU initialization in the shell.";
152std::pair<DartVMRef, fml::RefPtr<const DartSnapshot>>
163 if (!isolate_snapshot) {
164 isolate_snapshot = vm->GetVMData()->GetIsolateSnapshot();
166 return {std::move(vm), isolate_snapshot};
175 bool is_gpu_disabled) {
177 PerformInitializationTasks(
settings);
182 auto resource_cache_limit_calculator =
183 std::make_shared<ResourceCacheLimitCalculator>(
184 settings.resource_cache_max_bytes_threshold);
186 return CreateWithSnapshot(platform_data,
190 resource_cache_limit_calculator,
193 std::move(isolate_snapshot),
194 on_create_platform_view,
195 on_create_rasterizer,
196 CreateEngine, is_gpu_disabled);
200 const std::shared_ptr<impeller::Context>& impeller_context) {
201 if (!impeller_context) {
204 switch (impeller_context->GetBackendType()) {
214std::unique_ptr<Shell> Shell::CreateShellOnPlatformThread(
217 std::shared_ptr<ShellIOManager> parent_io_manager,
218 const std::shared_ptr<ResourceCacheLimitCalculator>&
219 resource_cache_limit_calculator,
220 const TaskRunners& task_runners,
221 const PlatformData& platform_data,
224 const Shell::CreateCallback<PlatformView>& on_create_platform_view,
225 const Shell::CreateCallback<Rasterizer>& on_create_rasterizer,
227 bool is_gpu_disabled) {
228 if (!task_runners.IsValid()) {
229 FML_LOG(
ERROR) <<
"Task runners to run the shell were invalid.";
233 auto shell = std::unique_ptr<Shell>(
234 new Shell(std::move(vm), task_runners, std::move(parent_merger),
235 resource_cache_limit_calculator,
settings,
236 std::make_shared<VolatilePathTracker>(
237 task_runners.GetUITaskRunner(),
238 !
settings.skia_deterministic_rendering_on_cpu),
248 std::promise<std::unique_ptr<Rasterizer>> rasterizer_promise;
249 auto rasterizer_future = rasterizer_promise.get_future();
250 std::promise<fml::TaskRunnerAffineWeakPtr<SnapshotDelegate>>
251 snapshot_delegate_promise;
252 auto snapshot_delegate_future = snapshot_delegate_promise.get_future();
254 task_runners.GetRasterTaskRunner(),
255 [&rasterizer_promise,
256 &snapshot_delegate_promise,
257 on_create_rasterizer,
261 TRACE_EVENT0(
"flutter",
"ShellSetupGPUSubsystem");
262 std::unique_ptr<Rasterizer> rasterizer(on_create_rasterizer(*shell));
263 rasterizer->SetImpellerContext(impeller_context);
264 snapshot_delegate_promise.set_value(rasterizer->GetSnapshotDelegate());
265 rasterizer_promise.set_value(std::move(rasterizer));
279 std::promise<std::shared_ptr<ShellIOManager>> io_manager_promise;
280 auto io_manager_future = io_manager_promise.get_future();
281 std::promise<fml::WeakPtr<ShellIOManager>> weak_io_manager_promise;
282 auto weak_io_manager_future = weak_io_manager_promise.get_future();
283 std::promise<fml::RefPtr<SkiaUnrefQueue>> unref_queue_promise;
284 auto unref_queue_future = unref_queue_promise.get_future();
285 auto io_task_runner =
shell->GetTaskRunners().GetIOTaskRunner();
292 [&io_manager_promise,
293 &weak_io_manager_promise,
295 &unref_queue_promise,
298 is_backgrounded_sync_switch =
shell->GetIsGpuDisabledSyncSwitch()
300 TRACE_EVENT0(
"flutter",
"ShellSetupIOSubsystem");
301 std::shared_ptr<ShellIOManager> io_manager;
302 if (parent_io_manager) {
303 io_manager = parent_io_manager;
305 io_manager = std::make_shared<ShellIOManager>(
306 platform_view_ptr->CreateResourceContext(),
307 is_backgrounded_sync_switch,
309 platform_view_ptr->GetImpellerContext()
312 weak_io_manager_promise.set_value(io_manager->GetWeakPtr());
313 unref_queue_promise.set_value(io_manager->GetSkiaUnrefQueue());
314 io_manager_promise.set_value(io_manager);
322 std::promise<std::unique_ptr<Engine>> engine_promise;
323 auto engine_future = engine_promise.get_future();
325 shell->GetTaskRunners().GetUITaskRunner(),
330 isolate_snapshot = std::move(isolate_snapshot),
331 vsync_waiter = std::move(vsync_waiter),
332 &weak_io_manager_future,
333 &snapshot_delegate_future,
338 TRACE_EVENT0(
"flutter",
"ShellSetupUISubsystem");
339 const auto& task_runners = shell->GetTaskRunners();
343 auto animator = std::make_unique<Animator>(*shell, task_runners,
344 std::move(vsync_waiter));
346 engine_promise.set_value(on_create_engine(
350 std::move(isolate_snapshot),
353 shell->GetSettings(),
355 weak_io_manager_future.get(),
356 unref_queue_future.get(),
357 snapshot_delegate_future.get(),
358 shell->volatile_path_tracker_,
359 shell->is_gpu_disabled_sync_switch_,
360 runtime_stage_backend
366 rasterizer_future.get(),
367 io_manager_future.get())
375std::unique_ptr<Shell> Shell::CreateWithSnapshot(
376 const PlatformData& platform_data,
377 const TaskRunners& task_runners,
379 const std::shared_ptr<ShellIOManager>& parent_io_manager,
380 const std::shared_ptr<ResourceCacheLimitCalculator>&
381 resource_cache_limit_calculator,
385 const Shell::CreateCallback<PlatformView>& on_create_platform_view,
386 const Shell::CreateCallback<Rasterizer>& on_create_rasterizer,
387 const Shell::EngineCreateCallback& on_create_engine,
388 bool is_gpu_disabled) {
390 PerformInitializationTasks(
settings);
394 const bool callbacks_valid =
395 on_create_platform_view && on_create_rasterizer && on_create_engine;
396 if (!task_runners.IsValid() || !callbacks_valid) {
401 std::unique_ptr<Shell>
shell;
402 auto platform_task_runner = task_runners.GetPlatformTaskRunner();
404 platform_task_runner,
407 parent_thread_merger,
409 resource_cache_limit_calculator,
410 task_runners = task_runners,
411 platform_data = platform_data,
414 isolate_snapshot = std::move(isolate_snapshot),
415 on_create_platform_view = on_create_platform_view,
416 on_create_rasterizer = on_create_rasterizer,
417 on_create_engine = on_create_engine,
418 is_gpu_disabled]()
mutable {
419 shell = CreateShellOnPlatformThread(std::move(vm),
420 parent_thread_merger,
422 resource_cache_limit_calculator,
426 std::move(isolate_snapshot),
427 on_create_platform_view,
428 on_create_rasterizer,
429 on_create_engine, is_gpu_disabled);
436Shell::Shell(DartVMRef vm,
437 const TaskRunners& task_runners,
439 const std::shared_ptr<ResourceCacheLimitCalculator>&
440 resource_cache_limit_calculator,
442 std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
443 bool is_gpu_disabled)
445 parent_raster_thread_merger_(
std::move(parent_merger)),
446 resource_cache_limit_calculator_(resource_cache_limit_calculator),
449 is_gpu_disabled_sync_switch_(new
fml::SyncSwitch(is_gpu_disabled)),
450 volatile_path_tracker_(
std::move(volatile_path_tracker)),
451 weak_factory_gpu_(nullptr),
452 weak_factory_(this) {
454 <<
"Software rendering is incompatible with Impeller.";
457 <<
"[Action Required] The application opted out of Impeller by either "
458 "using the --no-enable-impeller flag or FLTEnableImpeller=false "
459 "plist flag. This option is going to go away in an upcoming Flutter "
460 "release. Remove the explicit opt-out. If you need to opt-out, "
461 "report a bug describing the issue.";
463 FML_CHECK(vm_) <<
"Must have access to VM to create a shell.";
467 display_manager_ = std::make_unique<DisplayManager>();
468 resource_cache_limit_calculator->AddResourceCacheLimitItem(
469 weak_factory_.GetWeakPtr());
476 this->weak_factory_gpu_ =
477 std::make_unique<fml::TaskRunnerAffineWeakPtrFactory<Shell>>(this);
484 std::bind(&Shell::OnServiceProtocolScreenshot,
this,
485 std::placeholders::_1, std::placeholders::_2)};
488 std::bind(&Shell::OnServiceProtocolScreenshotSKP,
this,
489 std::placeholders::_1, std::placeholders::_2)};
492 std::bind(&Shell::OnServiceProtocolRunInView,
this, std::placeholders::_1,
493 std::placeholders::_2)};
494 service_protocol_handlers_
497 std::bind(&Shell::OnServiceProtocolFlushUIThreadTasks,
this,
498 std::placeholders::_1, std::placeholders::_2)};
499 service_protocol_handlers_
502 std::bind(&Shell::OnServiceProtocolSetAssetBundlePath,
this,
503 std::placeholders::_1, std::placeholders::_2)};
504 service_protocol_handlers_
507 std::bind(&Shell::OnServiceProtocolGetDisplayRefreshRate,
this,
508 std::placeholders::_1, std::placeholders::_2)};
511 std::bind(&Shell::OnServiceProtocolGetSkSLs,
this, std::placeholders::_1,
512 std::placeholders::_2)};
513 service_protocol_handlers_
516 std::bind(&Shell::OnServiceProtocolEstimateRasterCacheMemory,
this,
517 std::placeholders::_1, std::placeholders::_2)};
518 service_protocol_handlers_
521 std::bind(&Shell::OnServiceProtocolRenderFrameWithRasterStats,
this,
522 std::placeholders::_1, std::placeholders::_2)};
525 std::bind(&Shell::OnServiceProtocolReloadAssetFonts,
this,
526 std::placeholders::_1, std::placeholders::_2)};
531 PersistentCache::GetCacheForProcess()->RemoveWorkerTaskRunner(
535 vm_->GetServiceProtocol()->RemoveHandler(
this);
538 platform_latch, io_latch;
543 engine_->ShutdownPlatformIsolates();
544 platiso_latch.Signal();
546 platiso_latch.
Wait();
559 [
this, rasterizer = std::move(rasterizer_), &gpu_latch]()
mutable {
561 this->weak_factory_gpu_.reset();
570 &io_latch]()
mutable {
573 platform_view->ReleaseResourceContext();
586 &platform_latch]()
mutable {
587 platform_view.reset();
588 platform_latch.Signal();
590 platform_latch.Wait();
595 const std::string& initial_route,
600 bool is_gpu_disabled =
false;
601 GetIsGpuDisabledSyncSwitch()->Execute(
603 .SetIfFalse([&is_gpu_disabled] { is_gpu_disabled =
false; })
604 .SetIfTrue([&is_gpu_disabled] { is_gpu_disabled =
true; }));
605 std::unique_ptr<Shell>
result = CreateWithSnapshot(
607 io_manager_, resource_cache_limit_calculator_, GetSettings(), vm_,
608 vm_->GetVMData()->GetIsolateSnapshot(), on_create_platform_view,
609 on_create_rasterizer,
610 [
engine = this->engine_.get(), initial_route](
619 const std::shared_ptr<VolatilePathTracker>& volatile_path_tracker,
620 const std::shared_ptr<fml::SyncSwitch>& is_gpu_disabled_sync_switch,
622 return engine->Spawn(
629 std::move(snapshot_delegate),
630 is_gpu_disabled_sync_switch);
633 result->RunEngine(std::move(run_configuration));
648 [rasterizer = rasterizer_->GetWeakPtr(), trace_id = trace_id]() {
650 rasterizer->NotifyLowMemoryWarning();
660 RunEngine(std::move(run_configuration),
nullptr);
663void Shell::RunEngine(
668 if (!result_callback) {
671 platform_runner->PostTask(
672 [result_callback, run_result]() { result_callback(run_result); });
680 [run_configuration = std::move(run_configuration),
681 weak_engine = weak_engine_,
result]()
mutable {
684 <<
"Could not launch engine with configuration - no engine.";
685 result(Engine::RunStatus::Failure);
688 auto run_result = weak_engine->Run(std::move(run_configuration));
690 FML_LOG(
ERROR) <<
"Could not launch engine with configuration.";
697std::optional<DartErrorCode> Shell::GetUIIsolateLastError()
const {
704 switch (weak_engine_->GetUIIsolateLastError()) {
706 return DartErrorCode::CompilationError;
708 return DartErrorCode::ApiError;
710 return DartErrorCode::UnknownError;
712 return DartErrorCode::NoError;
714 return DartErrorCode::UnknownError;
717bool Shell::EngineHasLivePorts()
const {
725 return weak_engine_->UIIsolateHasLivePorts();
728bool Shell::IsSetup()
const {
732bool Shell::Setup(std::unique_ptr<PlatformView>
platform_view,
733 std::unique_ptr<Engine>
engine,
734 std::unique_ptr<Rasterizer> rasterizer,
735 const std::shared_ptr<ShellIOManager>& io_manager) {
745 platform_message_handler_ = platform_view_->GetPlatformMessageHandler();
746 route_messages_through_platform_thread_.store(
true);
748 [
self = weak_factory_.GetWeakPtr()] {
750 self->route_messages_through_platform_thread_.store(false);
753 engine_ = std::move(
engine);
754 rasterizer_ = std::move(rasterizer);
758 auto view_embedder = platform_view_->CreateExternalViewEmbedder();
759 rasterizer_->SetExternalViewEmbedder(view_embedder);
760 rasterizer_->SetSnapshotSurfaceProducer(
761 platform_view_->CreateSnapshotSurfaceProducer());
765 weak_engine_ = engine_->GetWeakPtr();
766 weak_rasterizer_ = rasterizer_->GetWeakPtr();
767 weak_platform_view_ = platform_view_->GetWeakPtr();
771 FML_DCHECK(added) <<
"Failed to add the implicit view";
775 if (!
settings_.prefetched_default_font_manager) {
779 engine->SetupDefaultFontManager();
787 PersistentCache::GetCacheForProcess()->AddWorkerTaskRunner(
790 PersistentCache::GetCacheForProcess()->SetIsDumpingSkp(
791 settings_.dump_skp_on_shader_compilation);
794 PersistentCache::GetCacheForProcess()->Purge();
811 return parent_raster_thread_merger_;
816 return weak_rasterizer_;
826 return weak_platform_view_;
839void Shell::OnPlatformViewCreated(std::unique_ptr<Surface>
surface) {
840 TRACE_EVENT0(
"flutter",
"Shell::OnPlatformViewCreated");
853 rasterizer_->DisableThreadMergerIfNeeded();
865 const bool should_post_raster_task =
866 !
task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread();
869 [&waiting_for_first_frame = waiting_for_first_frame_,
870 rasterizer = rasterizer_->GetWeakPtr(),
876 rasterizer->EnableThreadMergerIfNeeded();
877 rasterizer->Setup(std::move(surface));
880 waiting_for_first_frame.store(
true);
883 auto ui_task = [
engine = engine_->GetWeakPtr()] {
900 raster_task, should_post_raster_task, &latch] {
901 if (io_manager && !io_manager->GetResourceContext()) {
904 io_manager->NotifyResourceContextAvailable(resource_context);
912 if (should_post_raster_task) {
921 if (!should_post_raster_task) {
930void Shell::OnPlatformViewDestroyed() {
931 TRACE_EVENT0(
"flutter",
"Shell::OnPlatformViewDestroyed");
943 rasterizer_->DisableThreadMergerIfNeeded();
949 engine->NotifyDestroyed();
963 auto io_task = [io_manager =
io_manager_.get(), &latch]() {
966 io_manager->GetIsGpuDisabledSyncSwitch()->Execute(
968 [&] { io_manager->GetSkiaUnrefQueue()->Drain(); }));
974 auto raster_task = [rasterizer = rasterizer_->GetWeakPtr(),
981 rasterizer->EnableThreadMergerIfNeeded();
982 rasterizer->Teardown();
1000 rasterizer_->TeardownExternalViewEmbedder();
1004void Shell::OnPlatformViewScheduleFrame() {
1005 TRACE_EVENT0(
"flutter",
"Shell::OnPlatformViewScheduleFrame");
1011 engine->ScheduleFrame();
1017void Shell::OnPlatformViewSetViewportMetrics(int64_t view_id,
1018 const ViewportMetrics& metrics) {
1022 if (metrics.device_pixel_ratio <= 0 || metrics.physical_width <= 0 ||
1023 metrics.physical_height <= 0) {
1030 resource_cache_limit_ =
1031 metrics.physical_width * metrics.physical_height * 12 * 4;
1032 size_t resource_cache_max_bytes =
1033 resource_cache_limit_calculator_->GetResourceCacheMaxBytes();
1035 [rasterizer = rasterizer_->GetWeakPtr(), resource_cache_max_bytes] {
1037 rasterizer->SetResourceCacheMaxBytes(resource_cache_max_bytes, false);
1042 [
engine = engine_->GetWeakPtr(), view_id, metrics]() {
1044 engine->SetViewportMetrics(view_id, metrics);
1049 std::scoped_lock<std::mutex> lock(resize_mutex_);
1050 expected_frame_sizes_[view_id] =
1051 SkISize::Make(metrics.physical_width, metrics.physical_height);
1052 device_pixel_ratio_ = metrics.device_pixel_ratio;
1057void Shell::OnPlatformViewDispatchPlatformMessage(
1058 std::unique_ptr<PlatformMessage>
message) {
1060#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
1061 if (!
task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()) {
1062 std::scoped_lock lock(misbehaving_message_channels_mutex_);
1063 auto inserted = misbehaving_message_channels_.insert(
message->channel());
1064 if (inserted.second) {
1066 <<
"The '" <<
message->channel()
1067 <<
"' channel sent a message from native to Flutter on a "
1068 "non-platform thread. Platform channel messages must be sent on "
1069 "the platform thread. Failure to do so may result in data loss or "
1070 "crashes, and must be fixed in the plugin or application code "
1071 "creating that channel.\n"
1072 "See https://docs.flutter.dev/platform-integration/"
1073 "platform-channels#channels-and-platform-threading for more "
1084 engine->DispatchPlatformMessage(std::move(message));
1090void Shell::OnPlatformViewDispatchPointerDataPacket(
1091 std::unique_ptr<PointerDataPacket> packet) {
1093 "flutter",
"Shell::OnPlatformViewDispatchPointerDataPacket",
1094 1, &next_pointer_flow_id_);
1100 flow_id = next_pointer_flow_id_]()
mutable {
1102 engine->DispatchPointerDataPacket(std::move(packet), flow_id);
1105 next_pointer_flow_id_++;
1109void Shell::OnPlatformViewDispatchSemanticsAction(int32_t node_id,
1117 args = std::move(
args)]()
mutable {
1119 engine->DispatchSemanticsAction(node_id, action, std::move(args));
1125void Shell::OnPlatformViewSetSemanticsEnabled(
bool enabled) {
1130 [
engine = engine_->GetWeakPtr(), enabled] {
1132 engine->SetSemanticsEnabled(enabled);
1138void Shell::OnPlatformViewSetAccessibilityFeatures(int32_t
flags) {
1145 engine->SetAccessibilityFeatures(flags);
1151void Shell::OnPlatformViewRegisterTexture(
1152 std::shared_ptr<flutter::Texture>
texture) {
1157 [rasterizer = rasterizer_->GetWeakPtr(),
texture] {
1159 if (auto registry = rasterizer->GetTextureRegistry()) {
1160 registry->RegisterTexture(texture);
1167void Shell::OnPlatformViewUnregisterTexture(int64_t
texture_id) {
1172 [rasterizer = rasterizer_->GetWeakPtr(),
texture_id]() {
1174 if (auto registry = rasterizer->GetTextureRegistry()) {
1175 registry->UnregisterTexture(texture_id);
1182void Shell::OnPlatformViewMarkTextureFrameAvailable(int64_t
texture_id) {
1188 [rasterizer = rasterizer_->GetWeakPtr(),
texture_id]() {
1192 auto registry = rasterizer->GetTextureRegistry();
1204 texture->MarkNewFrameAvailable();
1210 engine->ScheduleFrame(false);
1223 rasterizer->SetNextFrameCallback(closure);
1229const Settings& Shell::OnPlatformViewGetSettings()
const {
1234void Shell::OnAnimatorBeginFrame(
fml::TimePoint frame_target_time,
1235 uint64_t frame_number) {
1241 std::scoped_lock time_recorder_lock(time_recorder_mutex_);
1242 latest_frame_target_time_.emplace(frame_target_time);
1245 engine_->BeginFrame(frame_target_time, frame_number);
1255 engine_->NotifyIdle(deadline);
1256 volatile_path_tracker_->OnFrame();
1260void Shell::OnAnimatorUpdateLatestFrameTargetTime(
1266 std::scoped_lock time_recorder_lock(time_recorder_mutex_);
1267 if (!latest_frame_target_time_) {
1268 latest_frame_target_time_ = frame_target_time;
1269 }
else if (latest_frame_target_time_ < frame_target_time) {
1270 latest_frame_target_time_ = frame_target_time;
1276void Shell::OnAnimatorDraw(std::shared_ptr<FramePipeline> pipeline) {
1280 [&waiting_for_first_frame = waiting_for_first_frame_,
1281 &waiting_for_first_frame_condition = waiting_for_first_frame_condition_,
1282 rasterizer = rasterizer_->GetWeakPtr(),
1283 weak_pipeline = std::weak_ptr<FramePipeline>(pipeline)]()
mutable {
1285 std::shared_ptr<FramePipeline> pipeline = weak_pipeline.lock();
1287 rasterizer->Draw(pipeline);
1290 if (waiting_for_first_frame.load()) {
1291 waiting_for_first_frame.store(false);
1292 waiting_for_first_frame_condition.notify_all();
1299void Shell::OnAnimatorDrawLastLayerTrees(
1300 std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) {
1304 [rasterizer = rasterizer_->GetWeakPtr(),
1305 frame_timings_recorder = std::move(frame_timings_recorder)]()
mutable {
1307 rasterizer->DrawLastLayerTrees(std::move(frame_timings_recorder));
1321 [view = platform_view_->GetWeakPtr(),
update = std::move(
update),
1322 actions = std::move(actions)] {
1324 view->UpdateSemantics(update, actions);
1330void Shell::OnEngineHandlePlatformMessage(
1331 std::unique_ptr<PlatformMessage>
message) {
1336 HandleEngineSkiaMessage(std::move(
message));
1340 if (platform_message_handler_) {
1341 if (route_messages_through_platform_thread_ &&
1342 !platform_message_handler_
1343 ->DoesHandlePlatformMessageOnPlatformThread()) {
1361 [weak_platform_message_handler =
1362 std::weak_ptr<PlatformMessageHandler>(platform_message_handler_),
1364 ui_task_runner->PostTask(
1367 auto platform_message_handler =
1368 weak_platform_message_handler.lock();
1369 if (platform_message_handler) {
1370 platform_message_handler->HandlePlatformMessage(
1376 platform_message_handler_->HandlePlatformMessage(std::move(
message));
1383 view->HandlePlatformMessage(std::move(message));
1389void Shell::OnEngineChannelUpdate(std::string
name,
bool listening) {
1393 [view = platform_view_->GetWeakPtr(),
name = std::move(
name), listening] {
1395 view->SendChannelUpdate(name, listening);
1400void Shell::HandleEngineSkiaMessage(std::unique_ptr<PlatformMessage>
message) {
1403 rapidjson::Document document;
1404 document.Parse(
reinterpret_cast<const char*
>(
data.GetMapping()),
1406 if (document.HasParseError() || !document.IsObject()) {
1409 auto root = document.GetObject();
1410 auto method =
root.FindMember(
"method");
1411 if (method->value !=
"Skia.setResourceCacheMaxBytes") {
1414 auto args =
root.FindMember(
"args");
1415 if (
args ==
root.MemberEnd() || !
args->value.IsInt()) {
1420 [rasterizer = rasterizer_->GetWeakPtr(), max_bytes =
args->value.GetInt(),
1421 response =
message->response()] {
1423 rasterizer->SetResourceCacheMaxBytes(static_cast<size_t>(max_bytes),
1429 std::vector<uint8_t>
data = {
'[',
't',
'r',
'u',
'e',
']'};
1431 std::make_unique<fml::DataMapping>(std::move(
data)));
1437void Shell::OnPreEngineRestart() {
1444 [view = platform_view_->GetWeakPtr(), &latch]() {
1446 view->OnPreEngineRestart();
1456void Shell::OnRootIsolateCreated() {
1457 if (is_added_to_service_protocol_) {
1460 auto description = GetServiceProtocolDescription();
1463 [
self = weak_factory_.GetWeakPtr(),
1464 description = std::move(description)]() {
1466 self->vm_->GetServiceProtocol()->AddHandler(self.get(), description);
1469 is_added_to_service_protocol_ =
true;
1473void Shell::UpdateIsolateDescription(
const std::string isolate_name,
1474 int64_t isolate_port) {
1475 Handler::Description description(isolate_port, isolate_name);
1476 vm_->GetServiceProtocol()->SetHandlerDescription(
this, description);
1479void Shell::SetNeedsReportTimings(
bool value) {
1480 needs_report_timings_ =
value;
1484std::unique_ptr<std::vector<std::string>> Shell::ComputePlatformResolvedLocale(
1485 const std::vector<std::string>& supported_locale_data) {
1486 return platform_view_->ComputePlatformResolvedLocales(supported_locale_data);
1490 intptr_t loading_unit_id,
1491 std::unique_ptr<const fml::Mapping> snapshot_data,
1492 std::unique_ptr<const fml::Mapping> snapshot_instructions) {
1494 [
engine = engine_->GetWeakPtr(), loading_unit_id,
1495 data = std::move(snapshot_data),
1496 instructions = std::move(snapshot_instructions)]()
mutable {
1498 engine->LoadDartDeferredLibrary(loading_unit_id, std::move(data),
1499 std::move(instructions));
1504void Shell::LoadDartDeferredLibraryError(intptr_t loading_unit_id,
1505 const std::string error_message,
1509 [
engine = weak_engine_, loading_unit_id, error_message, transient] {
1511 engine->LoadDartDeferredLibraryError(loading_unit_id, error_message,
1517void Shell::UpdateAssetResolverByType(
1518 std::unique_ptr<AssetResolver> updated_asset_resolver,
1519 AssetResolver::AssetResolverType
type) {
1524 asset_resolver = std::move(updated_asset_resolver)]()
mutable {
1526 engine->GetAssetManager()->UpdateResolverByType(
1527 std::move(asset_resolver), type);
1533void Shell::RequestDartDeferredLibrary(intptr_t loading_unit_id) {
1535 [view = platform_view_->GetWeakPtr(), loading_unit_id] {
1537 view->RequestDartDeferredLibrary(loading_unit_id);
1543double Shell::GetScaledFontSize(
double unscaled_font_size,
1544 int configuration_id)
const {
1545 return platform_view_->GetScaledFontSize(unscaled_font_size,
1549void Shell::ReportTimings() {
1553 auto timings = std::move(unreported_timings_);
1554 unreported_timings_ = {};
1557 engine->ReportTimings(timings);
1562size_t Shell::UnreportedFramesCount()
const {
1565 FML_DCHECK(unreported_timings_.size() % (FrameTiming::kStatisticsCount) == 0);
1566 return unreported_timings_.size() / (FrameTiming::kStatisticsCount);
1569void Shell::OnFrameRasterized(
const FrameTiming& timing) {
1575 if (
settings_.frame_rasterized_callback) {
1576 settings_.frame_rasterized_callback(timing);
1579 if (!needs_report_timings_) {
1583 size_t old_count = unreported_timings_.size();
1585 for (
auto phase : FrameTiming::kPhases) {
1586 unreported_timings_.push_back(
1587 timing.Get(phase).ToEpochDelta().ToMicroseconds());
1589 unreported_timings_.push_back(timing.GetLayerCacheCount());
1590 unreported_timings_.push_back(timing.GetLayerCacheBytes());
1591 unreported_timings_.push_back(timing.GetPictureCacheCount());
1592 unreported_timings_.push_back(timing.GetPictureCacheBytes());
1593 unreported_timings_.push_back(timing.GetFrameNumber());
1595 old_count + FrameTiming::kStatisticsCount);
1609 if (!first_frame_rasterized_ || UnreportedFramesCount() >= 100) {
1610 first_frame_rasterized_ =
true;
1612 }
else if (!frame_timings_report_scheduled_) {
1614 constexpr int kBatchTimeInMilliseconds = 1000;
1616 constexpr int kBatchTimeInMilliseconds = 100;
1622 frame_timings_report_scheduled_ =
true;
1624 [
self = weak_factory_gpu_->GetWeakPtr()]() {
1628 self->frame_timings_report_scheduled_ =
false;
1629 if (
self->UnreportedFramesCount() > 0) {
1630 self->ReportTimings();
1638 double display_refresh_rate = display_manager_->GetMainDisplayRefreshRate();
1639 if (display_refresh_rate > 0) {
1647 std::scoped_lock time_recorder_lock(time_recorder_mutex_);
1648 FML_CHECK(latest_frame_target_time_.has_value())
1649 <<
"GetLatestFrameTargetTime called before OnAnimatorBeginFrame";
1652 return latest_frame_target_time_.value();
1656bool Shell::ShouldDiscardLayerTree(int64_t view_id,
1658 std::scoped_lock<std::mutex> lock(resize_mutex_);
1659 auto expected_frame_size = ExpectedFrameSize(view_id);
1660 return !expected_frame_size.isEmpty() &&
1666 std::string_view method)
const {
1668 auto found = service_protocol_handlers_.find(method);
1669 if (found != service_protocol_handlers_.end()) {
1670 return found->second.first;
1676bool Shell::HandleServiceProtocolMessage(
1677 std::string_view method,
1678 const ServiceProtocolMap&
params,
1679 rapidjson::Document* response) {
1680 auto found = service_protocol_handlers_.find(method);
1681 if (found != service_protocol_handlers_.end()) {
1682 return found->second.second(
params, response);
1688ServiceProtocol::Handler::Description Shell::GetServiceProtocolDescription()
1692 if (!weak_engine_) {
1693 return ServiceProtocol::Handler::Description();
1697 weak_engine_->GetUIIsolateMainPort(),
1698 weak_engine_->GetUIIsolateName(),
1703 std::string error_details) {
1704 auto& allocator = response->GetAllocator();
1705 response->SetObject();
1708 response->AddMember(
"message",
"Invalid params", allocator);
1710 rapidjson::Value details(rapidjson::kObjectType);
1711 details.AddMember(
"details", std::move(error_details), allocator);
1712 response->AddMember(
"data", details, allocator);
1718 auto& allocator = response->GetAllocator();
1719 response->SetObject();
1720 const int64_t kJsonServerError = -32000;
1721 response->AddMember(
"code", kJsonServerError, allocator);
1722 response->AddMember(
"message", std::move(
message), allocator);
1726bool Shell::OnServiceProtocolScreenshot(
1727 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
1728 rapidjson::Document* response) {
1730 auto screenshot = rasterizer_->ScreenshotLastLayerTree(
1731 Rasterizer::ScreenshotType::CompressedImage,
true);
1732 if (screenshot.data) {
1733 response->SetObject();
1734 auto& allocator = response->GetAllocator();
1735 response->AddMember(
"type",
"Screenshot", allocator);
1736 rapidjson::Value
image;
1737 image.SetString(
static_cast<const char*
>(screenshot.data->data()),
1738 screenshot.data->size(), allocator);
1739 response->AddMember(
"screenshot",
image, allocator);
1747bool Shell::OnServiceProtocolScreenshotSKP(
1748 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
1749 rapidjson::Document* response) {
1753 response,
"Cannot capture SKP screenshot with Impeller enabled.");
1756 auto screenshot = rasterizer_->ScreenshotLastLayerTree(
1757 Rasterizer::ScreenshotType::SkiaPicture,
true);
1758 if (screenshot.data) {
1759 response->SetObject();
1760 auto& allocator = response->GetAllocator();
1761 response->AddMember(
"type",
"ScreenshotSkp", allocator);
1762 rapidjson::Value
skp;
1763 skp.SetString(
static_cast<const char*
>(screenshot.data->data()),
1764 screenshot.data->size(), allocator);
1765 response->AddMember(
"skp",
skp, allocator);
1773bool Shell::OnServiceProtocolRunInView(
1774 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
1775 rapidjson::Document* response) {
1778 if (
params.count(
"mainScript") == 0) {
1780 "'mainScript' parameter is missing.");
1784 if (
params.count(
"assetDirectory") == 0) {
1786 "'assetDirectory' parameter is missing.");
1790 std::string main_script_path =
1792 std::string asset_directory_path =
1795 auto main_script_file_mapping =
1799 auto isolate_configuration = IsolateConfiguration::CreateForKernel(
1800 std::move(main_script_file_mapping));
1802 RunConfiguration configuration(std::move(isolate_configuration));
1804 configuration.SetEntrypointAndLibrary(engine_->GetLastEntrypoint(),
1805 engine_->GetLastEntrypointLibrary());
1806 configuration.SetEntrypointArgs(engine_->GetLastEntrypointArgs());
1808 configuration.AddAssetResolver(std::make_unique<DirectoryAssetBundle>(
1815 auto old_asset_manager = engine_->GetAssetManager();
1816 if (old_asset_manager !=
nullptr) {
1817 for (
auto& old_resolver : old_asset_manager->TakeResolvers()) {
1818 if (old_resolver->IsValidAfterAssetManagerChange()) {
1819 configuration.AddAssetResolver(std::move(old_resolver));
1824 auto& allocator = response->GetAllocator();
1825 response->SetObject();
1826 if (engine_->Restart(std::move(configuration))) {
1827 response->AddMember(
"type",
"Success", allocator);
1828 auto new_description = GetServiceProtocolDescription();
1829 rapidjson::Value view(rapidjson::kObjectType);
1830 new_description.Write(
this, view, allocator);
1831 response->AddMember(
"view", view, allocator);
1834 FML_DLOG(
ERROR) <<
"Could not run configuration in engine.";
1836 "Could not run configuration in engine.");
1845bool Shell::OnServiceProtocolFlushUIThreadTasks(
1846 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
1847 rapidjson::Document* response) {
1855 response->SetObject();
1856 response->AddMember(
"type",
"Success", response->GetAllocator());
1860bool Shell::OnServiceProtocolGetDisplayRefreshRate(
1861 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
1862 rapidjson::Document* response) {
1864 response->SetObject();
1865 response->AddMember(
"type",
"DisplayRefreshRate", response->GetAllocator());
1866 response->AddMember(
"fps", display_manager_->GetMainDisplayRefreshRate(),
1867 response->GetAllocator());
1871double Shell::GetMainDisplayRefreshRate() {
1872 return display_manager_->GetMainDisplayRefreshRate();
1882 [
engine = engine_->GetWeakPtr(), factory = std::move(factory),
1885 engine->GetImageGeneratorRegistry()->AddFactory(factory, priority);
1890bool Shell::OnServiceProtocolGetSkSLs(
1891 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
1892 rapidjson::Document* response) {
1894 response->SetObject();
1895 response->AddMember(
"type",
"GetSkSLs", response->GetAllocator());
1897 rapidjson::Value shaders_json(rapidjson::kObjectType);
1899 PersistentCache* persistent_cache = PersistentCache::GetCacheForProcess();
1900 std::vector<PersistentCache::SkSLCache> sksls = persistent_cache->LoadSkSLs();
1901 for (
const auto& sksl : sksls) {
1902 size_t b64_size = Base64::EncodedSize(sksl.value->size());
1904 char* b64_char =
static_cast<char*
>(b64_data->
writable_data());
1905 Base64::Encode(sksl.value->data(), sksl.value->size(), b64_char);
1906 b64_char[b64_size] = 0;
1907 rapidjson::Value shader_value(b64_char, response->GetAllocator());
1908 std::string_view key_view(
reinterpret_cast<const char*
>(sksl.key->data()),
1911 if (!encode_result.first) {
1914 rapidjson::Value shader_key(encode_result.second, response->GetAllocator());
1915 shaders_json.AddMember(shader_key, shader_value, response->GetAllocator());
1918 response->AddMember(
"SkSLs", shaders_json, response->GetAllocator());
1922bool Shell::OnServiceProtocolEstimateRasterCacheMemory(
1923 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
1924 rapidjson::Document* response) {
1927 uint64_t layer_cache_byte_size = 0u;
1928 uint64_t picture_cache_byte_size = 0u;
1931 const auto& raster_cache = rasterizer_->compositor_context()->raster_cache();
1932 layer_cache_byte_size = raster_cache.EstimateLayerCacheByteSize();
1933 picture_cache_byte_size = raster_cache.EstimatePictureCacheByteSize();
1936 response->SetObject();
1937 response->AddMember(
"type",
"EstimateRasterCacheMemory",
1938 response->GetAllocator());
1939 response->AddMember<uint64_t>(
"layerBytes", layer_cache_byte_size,
1940 response->GetAllocator());
1941 response->AddMember<uint64_t>(
"pictureBytes", picture_cache_byte_size,
1942 response->GetAllocator());
1947bool Shell::OnServiceProtocolSetAssetBundlePath(
1948 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
1949 rapidjson::Document* response) {
1952 if (
params.count(
"assetDirectory") == 0) {
1954 "'assetDirectory' parameter is missing.");
1958 auto& allocator = response->GetAllocator();
1959 response->SetObject();
1961 auto asset_manager = std::make_shared<AssetManager>();
1963 if (!asset_manager->PushFront(std::make_unique<DirectoryAssetBundle>(
1975 auto old_asset_manager = engine_->GetAssetManager();
1976 if (old_asset_manager !=
nullptr) {
1977 for (
auto& old_resolver : old_asset_manager->TakeResolvers()) {
1978 if (old_resolver->IsValidAfterAssetManagerChange()) {
1979 asset_manager->PushBack(std::move(old_resolver));
1984 if (engine_->UpdateAssetManager(asset_manager)) {
1985 response->AddMember(
"type",
"Success", allocator);
1986 auto new_description = GetServiceProtocolDescription();
1987 rapidjson::Value view(rapidjson::kObjectType);
1988 new_description.Write(
this, view, allocator);
1989 response->AddMember(
"view", view, allocator);
2002 double device_pixel_ratio,
2004 rapidjson::Document* response) {
2005 auto& allocator = response->GetAllocator();
2016 result.AddMember(
"height",
bounds.height(), allocator);
2019 if (snapshot_bytes) {
2020 rapidjson::Value
image;
2022 const uint8_t*
data =
2023 reinterpret_cast<const uint8_t*
>(snapshot_bytes->
data());
2024 for (
size_t i = 0;
i < snapshot_bytes->
size();
i++) {
2032bool Shell::OnServiceProtocolRenderFrameWithRasterStats(
2033 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
2034 rapidjson::Document* response) {
2039 const char*
error =
"Raster status not supported on Impeller backend.";
2048 if (
auto last_layer_tree = rasterizer_->GetLastLayerTree(view_id)) {
2049 auto& allocator = response->GetAllocator();
2050 response->SetObject();
2051 response->AddMember(
"type",
"RenderFrameWithRasterStats", allocator);
2056 auto frame_timings_recorder = std::make_unique<FrameTimingsRecorder>();
2058 frame_timings_recorder->RecordVsync(now, now);
2059 frame_timings_recorder->RecordBuildStart(now);
2060 frame_timings_recorder->RecordBuildEnd(now);
2062 last_layer_tree->enable_leaf_layer_tracing(
true);
2063 rasterizer_->DrawLastLayerTrees(std::move(frame_timings_recorder));
2064 last_layer_tree->enable_leaf_layer_tracing(
false);
2066 rapidjson::Value snapshots;
2067 snapshots.SetArray();
2069 LayerSnapshotStore&
store =
2070 rasterizer_->compositor_context()->snapshot_store();
2071 for (
const LayerSnapshotData&
data :
store) {
2077 response->AddMember(
"snapshots", snapshots, allocator);
2079 const auto& frame_size = ExpectedFrameSize(view_id);
2080 response->AddMember(
"frame_width", frame_size.width(), allocator);
2081 response->AddMember(
"frame_height", frame_size.height(), allocator);
2086 "Failed to render the last frame with raster stats."
2087 " Rasterizer does not hold a valid last layer tree."
2088 " This could happen if this method was invoked before a frame was "
2096void Shell::SendFontChangeNotification() {
2099 rapidjson::Document document;
2100 document.SetObject();
2101 auto& allocator = document.GetAllocator();
2102 rapidjson::Value message_value;
2104 document.AddMember(
kTypeKey, message_value, allocator);
2106 rapidjson::StringBuffer
buffer;
2107 rapidjson::Writer<rapidjson::StringBuffer> writer(
buffer);
2108 document.Accept(writer);
2110 std::unique_ptr<PlatformMessage> fontsChangeMessage =
2111 std::make_unique<flutter::PlatformMessage>(
2114 OnPlatformViewDispatchPlatformMessage(std::move(fontsChangeMessage));
2117bool Shell::OnServiceProtocolReloadAssetFonts(
2118 const ServiceProtocol::Handler::ServiceProtocolMap&
params,
2119 rapidjson::Document* response) {
2124 engine_->GetFontCollection().RegisterFonts(engine_->GetAssetManager());
2125 engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache();
2126 SendFontChangeNotification();
2128 auto& allocator = response->GetAllocator();
2129 response->SetObject();
2130 response->AddMember(
"type",
"Success", allocator);
2135void Shell::OnPlatformViewAddView(int64_t view_id,
2136 const ViewportMetrics& viewport_metrics,
2142 <<
"Unexpected request to add the implicit view #"
2151 engine->AddView(view_id, viewport_metrics, callback);
2156void Shell::OnPlatformViewRemoveView(int64_t view_id,
2162 <<
"Unexpected request to remove the implicit view #"
2165 expected_frame_sizes_.erase(view_id);
2168 engine = engine_->GetWeakPtr(),
2169 rasterizer = rasterizer_->GetWeakPtr(),
2174 bool removed = engine->RemoveView(view_id);
2181 task_runners.GetRasterTaskRunner()->PostTask([rasterizer, view_id]() {
2183 rasterizer->CollectView(view_id);
2191 bool base64_encode) {
2193 switch (screenshot_type) {
2194 case Rasterizer::ScreenshotType::SkiaPicture:
2196 <<
"Impeller backend cannot produce ScreenshotType::SkiaPicture.";
2198 case Rasterizer::ScreenshotType::UncompressedImage:
2199 case Rasterizer::ScreenshotType::CompressedImage:
2200 case Rasterizer::ScreenshotType::SurfaceData:
2209 rasterizer = GetRasterizer(),
2215 screenshot = rasterizer->ScreenshotLastLayerTree(screenshot_type,
2226 if (
task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() ||
2227 task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) {
2229 "WaitForFirstFrame called from thread that can't wait "
2230 "because it is responsible for generating the frame.");
2234 auto now = std::chrono::steady_clock::now();
2236 auto desired_duration = std::chrono::milliseconds(
timeout.ToMilliseconds());
2238 now + (desired_duration > max_duration ? max_duration : desired_duration);
2240 std::unique_lock<std::mutex> lock(waiting_for_first_frame_mutex_);
2241 bool success = waiting_for_first_frame_condition_.wait_until(
2242 lock,
duration, [&waiting_for_first_frame = waiting_for_first_frame_] {
2243 return !waiting_for_first_frame.load();
2252bool Shell::ReloadSystemFonts() {
2259 engine_->SetupDefaultFontManager();
2260 engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache();
2263 SendFontChangeNotification();
2267std::shared_ptr<const fml::SyncSwitch> Shell::GetIsGpuDisabledSyncSwitch()
2269 return is_gpu_disabled_sync_switch_;
2274 switch (availability) {
2275 case GpuAvailability::kAvailable:
2276 is_gpu_disabled_sync_switch_->SetSwitch(
false);
2278 case GpuAvailability::kFlushAndMakeUnavailable: {
2283 io_manager->GetSkiaUnrefQueue()->Drain();
2289 case GpuAvailability::kUnavailable:
2290 is_gpu_disabled_sync_switch_->SetSwitch(
true);
2297void Shell::OnDisplayUpdates(std::vector<std::unique_ptr<Display>> displays) {
2301 std::vector<DisplayData> display_data;
2302 display_data.reserve(displays.size());
2303 for (
const auto& display : displays) {
2304 display_data.push_back(display->GetDisplayData());
2307 [
engine = engine_->GetWeakPtr(),
2308 display_data = std::move(display_data)]() {
2310 engine->SetDisplays(display_data);
2314 display_manager_->HandleDisplayUpdates(std::move(displays));
2321const std::shared_ptr<PlatformMessageHandler>&
2322Shell::GetPlatformMessageHandler()
const {
2323 return platform_message_handler_;
2326const std::weak_ptr<VsyncWaiter> Shell::GetVsyncWaiter()
const {
2330 return engine_->GetVsyncWaiter();
2333const std::shared_ptr<fml::ConcurrentTaskRunner>
2334Shell::GetConcurrentWorkerTaskRunner()
const {
2339 return vm_->GetConcurrentWorkerTaskRunner();
2342SkISize Shell::ExpectedFrameSize(int64_t view_id) {
2343 auto found = expected_frame_sizes_.find(view_id);
2344 if (found == expected_frame_sizes_.end()) {
2347 return found->second;
static sk_sp< SkData > MakeUninitialized(size_t length)
const void * data() const
static fml::RefPtr< const DartSnapshot > VMSnapshotFromSettings(const Settings &settings)
From the fields present in the given settings object, infer the core snapshot.
static fml::RefPtr< const DartSnapshot > IsolateSnapshotFromSettings(const Settings &settings)
From the fields present in the given settings object, infer the isolate snapshot.
static DartVMRef Create(const Settings &settings, fml::RefPtr< const DartSnapshot > vm_snapshot=nullptr, fml::RefPtr< const DartSnapshot > isolate_snapshot=nullptr)
Describes a running instance of the Dart VM. There may only be one running instance of the Dart VM in...
While the engine operates entirely on the UI task runner, it needs the capabilities of the other comp...
RunStatus
Indicates the result of the call to Engine::Run.
sk_sp< SkData > GetSnapshot() const
int64_t GetLayerUniqueId() const
fml::TimeDelta GetDuration() const
const SkISize & frame_size() const
static void SetCacheSkSL(bool value)
ScreenshotType
The type of the screenshot to obtain of the previously rendered layer tree.
Specifies all the configuration required by the runtime library to launch the root isolate....
static const std::string_view kSetAssetBundlePathExtensionName
static const std::string_view kReloadAssetFonts
static const std::string_view kScreenshotSkpExtensionName
static const std::string_view kScreenshotExtensionName
static const std::string_view kGetDisplayRefreshRateExtensionName
static const std::string_view kRunInViewExtensionName
static const std::string_view kEstimateRasterCacheMemoryExtensionName
static const std::string_view kGetSkSLsExtensionName
static const std::string_view kRenderFrameWithRasterStatsExtensionName
static const std::string_view kFlushUIThreadTasksExtensionName
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)
Creates a shell instance using the provided settings. The callbacks to create the various shell subco...
static std::pair< DartVMRef, fml::RefPtr< const DartSnapshot > > InferVmInitDataFromSettings(Settings &settings)
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, std::shared_ptr< VolatilePathTracker > volatile_path_tracker, const std::shared_ptr< fml::SyncSwitch > &gpu_disabled_switch, impeller::RuntimeStageBackend runtime_stage_type)> EngineCreateCallback
std::function< std::unique_ptr< T >(Shell &)> CreateCallback
fml::RefPtr< fml::TaskRunner > GetRasterTaskRunner() const
fml::RefPtr< fml::TaskRunner > GetUITaskRunner() const
fml::RefPtr< fml::TaskRunner > GetIOTaskRunner() const
fml::RefPtr< fml::TaskRunner > GetPlatformTaskRunner() const
A Mapping like NonOwnedMapping, but uses Free as its release proc.
static MallocMapping Copy(const T *begin, const T *end)
static void RunNowOrPostTask(const fml::RefPtr< fml::TaskRunner > &runner, const fml::closure &task)
virtual bool RunsTasksOnCurrentThread()
constexpr int64_t ToMicroseconds() const
static constexpr TimeDelta FromMilliseconds(int64_t millis)
DART_EXPORT void Dart_NotifyLowMemory(void)
static constexpr FlutterViewId kFlutterImplicitViewId
const EmbeddedViewParams * params
TaskRunners task_runners_
fml::WeakPtr< IOManager > io_manager_
FlutterSemanticsFlag flags
G_BEGIN_DECLS G_MODULE_EXPORT FlValue * args
FlKeyEvent uint64_t FlKeyResponderAsyncCallback callback
const uint8_t uint32_t uint32_t GError ** error
#define FML_DLOG(severity)
#define FML_LOG(severity)
#define FML_CHECK(condition)
#define FML_DCHECK(condition)
Dart_NativeFunction function
static float max(float r, float g, float b)
constexpr SkCodecs::Decoder Decoder()
void SK_API Register(Decoder d)
constexpr SkCodecs::Decoder Decoder()
constexpr SkCodecs::Decoder Decoder()
constexpr SkCodecs::Decoder Decoder()
SK_API bool Encode(SkWStream *dst, const SkPixmap &src, const Options &options)
constexpr SkCodecs::Decoder Decoder()
Optional< SkRect > bounds
sk_sp< const SkImage > image
constexpr SkCodecs::Decoder Decoder()
constexpr SkCodecs::Decoder Decoder()
static impeller::RuntimeStageBackend DetermineRuntimeStageBackend(const std::shared_ptr< impeller::Context > &impeller_context)
std::unordered_map< int32_t, SemanticsNode > SemanticsNodeUpdates
static void ServiceProtocolFailureError(rapidjson::Document *response, std::string message)
std::function< std::shared_ptr< ImageGenerator >(sk_sp< SkData > buffer)> ImageGeneratorFactory
ImageGeneratorFactory is the top level primitive for specifying an image decoder in Flutter....
std::unordered_map< int32_t, CustomAccessibilityAction > CustomAccessibilityActionUpdates
void InitSkiaEventTracer(bool enabled, const std::optional< std::vector< std::string > > &allowlist)
std::function< std::unique_ptr< PointerDataDispatcher >(PointerDataDispatcher::Delegate &)> PointerDataDispatcherMaker
Signature for constructing PointerDataDispatcher.
DEF_SWITCHES_START aot vmservice shared library name
static void LoadDartDeferredLibrary(JNIEnv *env, jobject obj, jlong shell_holder, jint jLoadingUnitId, jobjectArray jSearchPaths)
constexpr char kFontChange[]
static void NotifyLowMemoryWarning(JNIEnv *env, jobject obj, jlong shell_holder)
static void ServiceProtocolParameterError(rapidjson::Document *response, std::string error_details)
constexpr char kTypeKey[]
constexpr char kSystemChannel[]
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data vm service The hostname IP address on which the Dart VM Service should be served If not defaults to or::depending on whether ipv6 is specified vm service A custom Dart VM Service port The default is to pick a randomly available open port disable vm Disable the Dart VM Service The Dart VM Service is never available in release mode disable vm service Disable mDNS Dart VM Service publication Bind to the IPv6 localhost address for the Dart VM Service Ignored if vm service host is set endless trace buffer
EXPORTED void Spawn(const char *entrypoint, const char *route)
constexpr char kSkiaChannel[]
static rapidjson::Value SerializeLayerSnapshot(double device_pixel_ratio, const LayerSnapshotData &snapshot, rapidjson::Document *response)
GpuAvailability
Values for |Shell::SetGpuAvailability|.
void InitializeICU(const std::string &icu_data_path)
void InitializeICUFromMapping(std::unique_ptr< Mapping > mapping)
std::string FromURI(const std::string &uri)
void TraceSetAllowlist(const std::vector< std::string > &allowlist)
std::chrono::duration< double, std::milli > Milliseconds
void SetLogSettings(const LogSettings &settings)
constexpr LogSeverity kLogError
fml::UniqueFD OpenDirectory(const char *path, bool create_if_necessary, FilePermission permission)
internal::CopyableLambda< T > MakeCopyable(T lambda)
std::pair< bool, std::string > Base32Encode(std::string_view input)
constexpr Milliseconds kDefaultFrameBudget
constexpr LogSeverity kLogInfo
std::function< void()> closure
fml::UniqueFD OpenFile(const char *path, bool create_if_necessary, FilePermission permission)
This can open a directory on POSIX, but not on Windows.
Milliseconds RefreshRateToFrameBudget(T refresh_rate)
def timeout(deadline, cmd)
void SetLogHandler(std::function< void(const char *)> handler)
static constexpr SkISize MakeEmpty()
static constexpr SkISize Make(int32_t w, int32_t h)
A POD type used to return the screenshot data along with the size of the frame.
LogSeverity min_log_level
Represents the 2 code paths available when calling |SyncSwitch::Execute|.
Handlers & SetIfFalse(const std::function< void()> &handler)
Sets the handler that will be executed if the |SyncSwitch| is false.
std::shared_ptr< const fml::Mapping > data
#define TRACE_FLOW_BEGIN(category, name, id)
#define TRACE_EVENT0(category_group, name)
#define TRACE_EVENT_ASYNC_END0(category_group, name, id)
#define TRACE_EVENT0_WITH_FLOW_IDS(category_group, name, flow_id_count, flow_ids)
#define TRACE_EVENT_ASYNC_BEGIN0(category_group, name, id)