Flutter Engine
engine.cc
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "flutter/shell/common/engine.h"
6 
7 #include <cstring>
8 #include <memory>
9 #include <string>
10 #include <utility>
11 #include <vector>
12 
13 #include "flutter/common/settings.h"
14 #include "flutter/fml/eintr_wrapper.h"
15 #include "flutter/fml/file.h"
16 #include "flutter/fml/make_copyable.h"
17 #include "flutter/fml/paths.h"
18 #include "flutter/fml/trace_event.h"
19 #include "flutter/fml/unique_fd.h"
20 #include "flutter/lib/snapshot/snapshot.h"
21 #include "flutter/lib/ui/text/font_collection.h"
22 #include "flutter/shell/common/animator.h"
23 #include "flutter/shell/common/platform_view.h"
24 #include "flutter/shell/common/shell.h"
25 #include "rapidjson/document.h"
26 #include "third_party/dart/runtime/include/dart_tools_api.h"
27 #include "third_party/skia/include/core/SkCanvas.h"
28 #include "third_party/skia/include/core/SkPictureRecorder.h"
29 
30 namespace flutter {
31 
32 static constexpr char kAssetChannel[] = "flutter/assets";
33 static constexpr char kLifecycleChannel[] = "flutter/lifecycle";
34 static constexpr char kNavigationChannel[] = "flutter/navigation";
35 static constexpr char kLocalizationChannel[] = "flutter/localization";
36 static constexpr char kSettingsChannel[] = "flutter/settings";
37 static constexpr char kIsolateChannel[] = "flutter/isolate";
38 
39 namespace {
40 fml::MallocMapping MakeMapping(const std::string& str) {
41  return fml::MallocMapping::Copy(str.c_str(), str.length());
42 }
43 } // namespace
44 
46  Delegate& delegate,
47  const PointerDataDispatcherMaker& dispatcher_maker,
48  std::shared_ptr<fml::ConcurrentTaskRunner> image_decoder_task_runner,
49  TaskRunners task_runners,
50  Settings settings,
51  std::unique_ptr<Animator> animator,
52  fml::WeakPtr<IOManager> io_manager,
53  const std::shared_ptr<FontCollection>& font_collection,
54  std::unique_ptr<RuntimeController> runtime_controller)
55  : delegate_(delegate),
56  settings_(std::move(settings)),
57  animator_(std::move(animator)),
58  runtime_controller_(std::move(runtime_controller)),
59  activity_running_(true),
60  have_surface_(false),
61  font_collection_(font_collection),
62  image_decoder_(task_runners, image_decoder_task_runner, io_manager),
63  task_runners_(std::move(task_runners)),
64  weak_factory_(this) {
65  pointer_data_dispatcher_ = dispatcher_maker(*this);
66 }
67 
69  const PointerDataDispatcherMaker& dispatcher_maker,
70  DartVM& vm,
71  fml::RefPtr<const DartSnapshot> isolate_snapshot,
72  TaskRunners task_runners,
73  const PlatformData& platform_data,
74  Settings settings,
75  std::unique_ptr<Animator> animator,
76  fml::WeakPtr<IOManager> io_manager,
77  fml::RefPtr<SkiaUnrefQueue> unref_queue,
78  fml::WeakPtr<SnapshotDelegate> snapshot_delegate,
79  std::shared_ptr<VolatilePathTracker> volatile_path_tracker)
80  : Engine(delegate,
81  dispatcher_maker,
82  vm.GetConcurrentWorkerTaskRunner(),
83  task_runners,
84  settings,
85  std::move(animator),
86  io_manager,
87  std::make_shared<FontCollection>(),
88  nullptr) {
89  runtime_controller_ = std::make_unique<RuntimeController>(
90  *this, // runtime delegate
91  &vm, // VM
92  std::move(isolate_snapshot), // isolate snapshot
93  settings_.idle_notification_callback, // idle notification callback
94  platform_data, // platform data
95  settings_.isolate_create_callback, // isolate create callback
96  settings_.isolate_shutdown_callback, // isolate shutdown callback
97  settings_.persistent_isolate_data, // persistent isolate data
99  task_runners_, // task runners
100  std::move(snapshot_delegate), // snapshot delegate
101  std::move(io_manager), // io manager
102  std::move(unref_queue), // Skia unref queue
103  image_decoder_.GetWeakPtr(), // image decoder
104  image_generator_registry_.GetWeakPtr(), // image generator registry
105  settings_.advisory_script_uri, // advisory script uri
106  settings_.advisory_script_entrypoint, // advisory script entrypoint
107  std::move(volatile_path_tracker), // volatile path tracker
108  });
109 }
110 
111 std::unique_ptr<Engine> Engine::Spawn(
112  Delegate& delegate,
113  const PointerDataDispatcherMaker& dispatcher_maker,
114  Settings settings,
115  std::unique_ptr<Animator> animator,
116  const std::string& initial_route) const {
117  auto result = std::make_unique<Engine>(
118  /*delegate=*/delegate,
119  /*dispatcher_maker=*/dispatcher_maker,
120  /*image_decoder_task_runner=*/
121  runtime_controller_->GetDartVM()->GetConcurrentWorkerTaskRunner(),
122  /*task_runners=*/task_runners_,
123  /*settings=*/settings,
124  /*animator=*/std::move(animator),
125  /*io_manager=*/runtime_controller_->GetIOManager(),
126  /*font_collection=*/font_collection_,
127  /*runtime_controller=*/nullptr);
128  result->runtime_controller_ = runtime_controller_->Spawn(
129  *result, // runtime delegate
130  settings_.advisory_script_uri, // advisory script uri
131  settings_.advisory_script_entrypoint, // advisory script entrypoint
132  settings_.idle_notification_callback, // idle notification callback
133  settings_.isolate_create_callback, // isolate create callback
134  settings_.isolate_shutdown_callback, // isolate shutdown callback
135  settings_.persistent_isolate_data // persistent isolate data
136  );
137  result->initial_route_ = initial_route;
138  return result;
139 }
140 
141 Engine::~Engine() = default;
142 
144  return weak_factory_.GetWeakPtr();
145 }
146 
148  TRACE_EVENT0("flutter", "Engine::SetupDefaultFontManager");
149  font_collection_->SetupDefaultFontManager(settings_.font_initialization_data);
150 }
151 
152 std::shared_ptr<AssetManager> Engine::GetAssetManager() {
153  return asset_manager_;
154 }
155 
157  return image_generator_registry_.GetWeakPtr();
158 }
159 
161  std::shared_ptr<AssetManager> new_asset_manager) {
162  if (asset_manager_ == new_asset_manager) {
163  return false;
164  }
165 
166  asset_manager_ = new_asset_manager;
167 
168  if (!asset_manager_) {
169  return false;
170  }
171 
172  // Using libTXT as the text engine.
173  font_collection_->RegisterFonts(asset_manager_);
174 
175  if (settings_.use_test_fonts) {
176  font_collection_->RegisterTestFonts();
177  }
178 
179  return true;
180 }
181 
182 bool Engine::Restart(RunConfiguration configuration) {
183  TRACE_EVENT0("flutter", "Engine::Restart");
184  if (!configuration.IsValid()) {
185  FML_LOG(ERROR) << "Engine run configuration was invalid.";
186  return false;
187  }
188  delegate_.OnPreEngineRestart();
189  runtime_controller_ = runtime_controller_->Clone();
190  UpdateAssetManager(nullptr);
191  return Run(std::move(configuration)) == Engine::RunStatus::Success;
192 }
193 
195  if (!configuration.IsValid()) {
196  FML_LOG(ERROR) << "Engine run configuration was invalid.";
197  return RunStatus::Failure;
198  }
199 
200  last_entry_point_ = configuration.GetEntrypoint();
201  last_entry_point_library_ = configuration.GetEntrypointLibrary();
202 
203  UpdateAssetManager(configuration.GetAssetManager());
204 
205  // If the embedding prefetched the default font manager, then set up the
206  // font manager later in the engine launch process. This makes it less
207  // likely that the setup will need to wait for the prefetch to complete.
208  if (settings_.prefetched_default_font_manager) {
210  }
211 
212  if (runtime_controller_->IsRootIsolateRunning()) {
214  }
215 
216  if (!runtime_controller_->LaunchRootIsolate(
217  settings_, //
218  configuration.GetEntrypoint(), //
219  configuration.GetEntrypointLibrary(), //
220  configuration.TakeIsolateConfiguration()) //
221  ) {
222  return RunStatus::Failure;
223  }
224 
225  auto service_id = runtime_controller_->GetRootIsolateServiceID();
226  if (service_id.has_value()) {
227  std::unique_ptr<PlatformMessage> service_id_message =
228  std::make_unique<flutter::PlatformMessage>(
229  kIsolateChannel, MakeMapping(service_id.value()), nullptr);
230  HandlePlatformMessage(std::move(service_id_message));
231  }
232 
234 }
235 
236 void Engine::BeginFrame(fml::TimePoint frame_time, uint64_t frame_number) {
237  TRACE_EVENT0("flutter", "Engine::BeginFrame");
238  runtime_controller_->BeginFrame(frame_time, frame_number);
239 }
240 
241 void Engine::ReportTimings(std::vector<int64_t> timings) {
242  TRACE_EVENT0("flutter", "Engine::ReportTimings");
243  runtime_controller_->ReportTimings(std::move(timings));
244 }
245 
246 void Engine::NotifyIdle(int64_t deadline) {
247  auto trace_event = std::to_string(deadline - Dart_TimelineGetMicros());
248  TRACE_EVENT1("flutter", "Engine::NotifyIdle", "deadline_now_delta",
249  trace_event.c_str());
250  runtime_controller_->NotifyIdle(deadline);
251 }
252 
253 std::optional<uint32_t> Engine::GetUIIsolateReturnCode() {
254  return runtime_controller_->GetRootIsolateReturnCode();
255 }
256 
258  return runtime_controller_->GetMainPort();
259 }
260 
262  return runtime_controller_->GetIsolateName();
263 }
264 
266  return runtime_controller_->HasLivePorts();
267 }
268 
270  return runtime_controller_->GetLastError();
271 }
272 
274  have_surface_ = true;
275  ScheduleFrame();
276 }
277 
279  have_surface_ = false;
280  StopAnimator();
281 }
282 
284  bool dimensions_changed =
285  viewport_metrics_.physical_height != metrics.physical_height ||
286  viewport_metrics_.physical_width != metrics.physical_width ||
287  viewport_metrics_.device_pixel_ratio != metrics.device_pixel_ratio;
288  viewport_metrics_ = metrics;
289  runtime_controller_->SetViewportMetrics(viewport_metrics_);
290  if (animator_) {
291  if (dimensions_changed) {
292  animator_->SetDimensionChangePending();
293  }
294  if (have_surface_) {
295  ScheduleFrame();
296  }
297  }
298 }
299 
300 void Engine::DispatchPlatformMessage(std::unique_ptr<PlatformMessage> message) {
301  std::string channel = message->channel();
302  if (channel == kLifecycleChannel) {
303  if (HandleLifecyclePlatformMessage(message.get())) {
304  return;
305  }
306  } else if (channel == kLocalizationChannel) {
307  if (HandleLocalizationPlatformMessage(message.get())) {
308  return;
309  }
310  } else if (channel == kSettingsChannel) {
311  HandleSettingsPlatformMessage(message.get());
312  return;
313  } else if (!runtime_controller_->IsRootIsolateRunning() &&
314  channel == kNavigationChannel) {
315  // If there's no runtime_, we may still need to set the initial route.
316  HandleNavigationPlatformMessage(std::move(message));
317  return;
318  }
319 
320  if (runtime_controller_->IsRootIsolateRunning() &&
321  runtime_controller_->DispatchPlatformMessage(std::move(message))) {
322  return;
323  }
324 
325  FML_DLOG(WARNING) << "Dropping platform message on channel: " << channel;
326 }
327 
328 bool Engine::HandleLifecyclePlatformMessage(PlatformMessage* message) {
329  const auto& data = message->data();
330  std::string state(reinterpret_cast<const char*>(data.GetMapping()),
331  data.GetSize());
332  if (state == "AppLifecycleState.paused" ||
333  state == "AppLifecycleState.detached") {
334  activity_running_ = false;
335  StopAnimator();
336  } else if (state == "AppLifecycleState.resumed" ||
337  state == "AppLifecycleState.inactive") {
338  activity_running_ = true;
339  StartAnimatorIfPossible();
340  }
341 
342  // Always schedule a frame when the app does become active as per API
343  // recommendation
344  // https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive?language=objc
345  if (state == "AppLifecycleState.resumed" && have_surface_) {
346  ScheduleFrame();
347  }
348  runtime_controller_->SetLifecycleState(state);
349  // Always forward these messages to the framework by returning false.
350  return false;
351 }
352 
353 bool Engine::HandleNavigationPlatformMessage(
354  std::unique_ptr<PlatformMessage> message) {
355  const auto& data = message->data();
356 
357  rapidjson::Document document;
358  document.Parse(reinterpret_cast<const char*>(data.GetMapping()),
359  data.GetSize());
360  if (document.HasParseError() || !document.IsObject()) {
361  return false;
362  }
363  auto root = document.GetObject();
364  auto method = root.FindMember("method");
365  if (method->value != "setInitialRoute") {
366  return false;
367  }
368  auto route = root.FindMember("args");
369  initial_route_ = std::move(route->value.GetString());
370  return true;
371 }
372 
373 bool Engine::HandleLocalizationPlatformMessage(PlatformMessage* message) {
374  const auto& data = message->data();
375 
376  rapidjson::Document document;
377  document.Parse(reinterpret_cast<const char*>(data.GetMapping()),
378  data.GetSize());
379  if (document.HasParseError() || !document.IsObject()) {
380  return false;
381  }
382  auto root = document.GetObject();
383  auto method = root.FindMember("method");
384  if (method == root.MemberEnd()) {
385  return false;
386  }
387  const size_t strings_per_locale = 4;
388  if (method->value == "setLocale") {
389  // Decode and pass the list of locale data onwards to dart.
390  auto args = root.FindMember("args");
391  if (args == root.MemberEnd() || !args->value.IsArray()) {
392  return false;
393  }
394 
395  if (args->value.Size() % strings_per_locale != 0) {
396  return false;
397  }
398  std::vector<std::string> locale_data;
399  for (size_t locale_index = 0; locale_index < args->value.Size();
400  locale_index += strings_per_locale) {
401  if (!args->value[locale_index].IsString() ||
402  !args->value[locale_index + 1].IsString()) {
403  return false;
404  }
405  locale_data.push_back(args->value[locale_index].GetString());
406  locale_data.push_back(args->value[locale_index + 1].GetString());
407  locale_data.push_back(args->value[locale_index + 2].GetString());
408  locale_data.push_back(args->value[locale_index + 3].GetString());
409  }
410 
411  return runtime_controller_->SetLocales(locale_data);
412  }
413  return false;
414 }
415 
416 void Engine::HandleSettingsPlatformMessage(PlatformMessage* message) {
417  const auto& data = message->data();
418  std::string jsonData(reinterpret_cast<const char*>(data.GetMapping()),
419  data.GetSize());
420  if (runtime_controller_->SetUserSettingsData(std::move(jsonData)) &&
421  have_surface_) {
422  ScheduleFrame();
423  }
424 }
425 
427  std::unique_ptr<PointerDataPacket> packet,
428  uint64_t trace_flow_id) {
429  TRACE_EVENT0("flutter", "Engine::DispatchPointerDataPacket");
430  TRACE_FLOW_STEP("flutter", "PointerEvent", trace_flow_id);
431  pointer_data_dispatcher_->DispatchPacket(std::move(packet), trace_flow_id);
432 }
433 
434 void Engine::DispatchKeyDataPacket(std::unique_ptr<KeyDataPacket> packet,
436  TRACE_EVENT0("flutter", "Engine::DispatchKeyDataPacket");
437  if (runtime_controller_) {
438  runtime_controller_->DispatchKeyDataPacket(*packet, std::move(callback));
439  }
440 }
441 
445  runtime_controller_->DispatchSemanticsAction(id, action, std::move(args));
446 }
447 
448 void Engine::SetSemanticsEnabled(bool enabled) {
449  runtime_controller_->SetSemanticsEnabled(enabled);
450 }
451 
453  runtime_controller_->SetAccessibilityFeatures(flags);
454 }
455 
456 void Engine::StopAnimator() {
457  animator_->Stop();
458 }
459 
460 void Engine::StartAnimatorIfPossible() {
461  if (activity_running_ && have_surface_) {
462  animator_->Start();
463  }
464 }
465 
466 std::string Engine::DefaultRouteName() {
467  if (!initial_route_.empty()) {
468  return initial_route_;
469  }
470  return "/";
471 }
472 
473 void Engine::ScheduleFrame(bool regenerate_layer_tree) {
474  StartAnimatorIfPossible();
475  animator_->RequestFrame(regenerate_layer_tree);
476 }
477 
478 void Engine::Render(std::unique_ptr<flutter::LayerTree> layer_tree) {
479  if (!layer_tree) {
480  return;
481  }
482 
483  // Ensure frame dimensions are sane.
484  if (layer_tree->frame_size().isEmpty() ||
485  layer_tree->device_pixel_ratio() <= 0.0f) {
486  return;
487  }
488 
489  animator_->Render(std::move(layer_tree));
490 }
491 
492 void Engine::UpdateSemantics(SemanticsNodeUpdates update,
494  delegate_.OnEngineUpdateSemantics(std::move(update), std::move(actions));
495 }
496 
497 void Engine::HandlePlatformMessage(std::unique_ptr<PlatformMessage> message) {
498  if (message->channel() == kAssetChannel) {
499  HandleAssetPlatformMessage(std::move(message));
500  } else {
501  delegate_.OnEngineHandlePlatformMessage(std::move(message));
502  }
503 }
504 
505 void Engine::OnRootIsolateCreated() {
506  delegate_.OnRootIsolateCreated();
507 }
508 
509 void Engine::UpdateIsolateDescription(const std::string isolate_name,
510  int64_t isolate_port) {
511  delegate_.UpdateIsolateDescription(isolate_name, isolate_port);
512 }
513 
514 std::unique_ptr<std::vector<std::string>> Engine::ComputePlatformResolvedLocale(
515  const std::vector<std::string>& supported_locale_data) {
516  return delegate_.ComputePlatformResolvedLocale(supported_locale_data);
517 }
518 
519 void Engine::SetNeedsReportTimings(bool needs_reporting) {
520  delegate_.SetNeedsReportTimings(needs_reporting);
521 }
522 
524  return *font_collection_;
525 }
526 
527 void Engine::DoDispatchPacket(std::unique_ptr<PointerDataPacket> packet,
528  uint64_t trace_flow_id) {
529  animator_->EnqueueTraceFlowId(trace_flow_id);
530  if (runtime_controller_) {
531  runtime_controller_->DispatchPointerDataPacket(*packet);
532  }
533 }
534 
536  const fml::closure& callback) {
537  animator_->ScheduleSecondaryVsyncCallback(id, callback);
538 }
539 
540 void Engine::HandleAssetPlatformMessage(
541  std::unique_ptr<PlatformMessage> message) {
542  fml::RefPtr<PlatformMessageResponse> response = message->response();
543  if (!response) {
544  return;
545  }
546  const auto& data = message->data();
547  std::string asset_name(reinterpret_cast<const char*>(data.GetMapping()),
548  data.GetSize());
549 
550  if (asset_manager_) {
551  std::unique_ptr<fml::Mapping> asset_mapping =
552  asset_manager_->GetAsMapping(asset_name);
553  if (asset_mapping) {
554  response->Complete(std::move(asset_mapping));
555  return;
556  }
557  }
558 
559  response->CompleteEmpty();
560 }
561 
562 const std::string& Engine::GetLastEntrypoint() const {
563  return last_entry_point_;
564 }
565 
566 const std::string& Engine::GetLastEntrypointLibrary() const {
567  return last_entry_point_library_;
568 }
569 
570 // |RuntimeDelegate|
571 void Engine::RequestDartDeferredLibrary(intptr_t loading_unit_id) {
572  return delegate_.RequestDartDeferredLibrary(loading_unit_id);
573 }
574 
576  intptr_t loading_unit_id,
577  std::unique_ptr<const fml::Mapping> snapshot_data,
578  std::unique_ptr<const fml::Mapping> snapshot_instructions) {
579  if (runtime_controller_->IsRootIsolateRunning()) {
580  runtime_controller_->LoadDartDeferredLibrary(
581  loading_unit_id, std::move(snapshot_data),
582  std::move(snapshot_instructions));
583  } else {
584  LoadDartDeferredLibraryError(loading_unit_id, "No running root isolate.",
585  true);
586  }
587 }
588 
589 void Engine::LoadDartDeferredLibraryError(intptr_t loading_unit_id,
590  const std::string error_message,
591  bool transient) {
592  if (runtime_controller_->IsRootIsolateRunning()) {
593  runtime_controller_->LoadDartDeferredLibraryError(loading_unit_id,
594  error_message, transient);
595  }
596 }
597 
598 } // namespace flutter
virtual void Complete(std::unique_ptr< fml::Mapping > data)=0
G_BEGIN_DECLS FlValue * args
bool IsValid() const
A valid run configuration only guarantees that the engine should be able to find the assets and the i...
std::string advisory_script_entrypoint
Definition: settings.h:153
std::shared_ptr< AssetManager > GetAssetManager() const
virtual void OnRootIsolateCreated()=0
Notifies the shell that the root isolate is created. Currently, this information is to add to the ser...
While the engine operates entirely on the UI task runner, it needs the capabilities of the other comp...
Definition: engine.h:140
fml::closure isolate_shutdown_callback
Definition: settings.h:223
Dart_Port GetUIIsolateMainPort()
Gets the main port of the root isolate. Since the isolate is created immediately in the constructor o...
Definition: engine.cc:257
~Engine() override
Destroys the engine engine. Called by the shell on the UI task runner. The running root isolate is te...
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:90
void DispatchPointerDataPacket(std::unique_ptr< PointerDataPacket > packet, uint64_t trace_flow_id)
Notifies the engine that the embedder has sent it a pointer data packet. A pointer data packet may co...
Definition: engine.cc:426
MockDelegate delegate_
#define TRACE_FLOW_STEP(category, name, id)
Definition: trace_event.h:133
static constexpr char kSettingsChannel[]
Definition: engine.cc:36
std::string advisory_script_uri
Definition: settings.h:150
std::unique_ptr< IsolateConfiguration > TakeIsolateConfiguration()
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.
virtual std::unique_ptr< std::vector< std::string > > ComputePlatformResolvedLocale(const std::vector< std::string > &supported_locale_data)=0
Directly invokes platform-specific APIs to compute the locale the platform would have natively resolv...
void OnOutputSurfaceCreated()
Indicates to the Flutter application that it has obtained a rendering surface. This is a good opportu...
Definition: engine.cc:273
fml::closure isolate_create_callback
Definition: settings.h:219
void SetAccessibilityFeatures(int32_t flags)
Notifies the engine that the embedder has expressed an opinion about where the flags to set on the ac...
Definition: engine.cc:452
tonic::DartErrorHandleType GetUIIsolateLastError()
Errors that are unhandled on the Dart message loop are kept for further inspection till the next unha...
Definition: engine.cc:269
fml::WeakPtr< Engine > GetWeakPtr() const
Definition: engine.cc:143
void DispatchPlatformMessage(std::unique_ptr< PlatformMessage > message)
Notifies the engine that the embedder has sent it a message. This call originates in the platform vie...
Definition: engine.cc:300
void DispatchKeyDataPacket(std::unique_ptr< KeyDataPacket > packet, KeyDataResponse callback)
Notifies the engine that the embedder has sent it a key data packet. A key data packet contains one k...
Definition: engine.cc:434
Definition: ref_ptr.h:252
const std::string & GetEntrypoint() const
std::unordered_map< int32_t, SemanticsNode > SemanticsNodeUpdates
GAsyncResult * result
static constexpr char kIsolateChannel[]
Definition: engine.cc:37
void SetupDefaultFontManager()
Setup default font manager according to specific platform.
Definition: engine.cc:147
bool prefetched_default_font_manager
Definition: settings.h:186
#define FML_LOG(severity)
Definition: logging.h:65
virtual void OnPreEngineRestart()=0
Notifies the delegate that the root isolate of the application is about to be discarded and a new iso...
std::function< std::unique_ptr< PointerDataDispatcher >(PointerDataDispatcher::Delegate &)> PointerDataDispatcherMaker
Signature for constructing PointerDataDispatcher.
bool UpdateAssetManager(std::shared_ptr< AssetManager > asset_manager)
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.
Definition: engine.cc:160
std::unique_ptr< RuntimeController > runtime_controller_
const std::string & GetEntrypointLibrary() const
void ScheduleFrame()
Definition: engine.h:801
bool Restart(RunConfiguration configuration)
Tears down an existing root isolate, reuses the components of that isolate and attempts to launch a n...
Definition: engine.cc:182
FlKeyEvent FlKeyResponderAsyncCallback callback
DartErrorHandleType
Definition: dart_error.h:18
FontCollection & GetFontCollection() override
Definition: engine.cc:523
std::shared_ptr< AssetManager > GetAssetManager()
Definition: engine.cc:152
std::function< void()> closure
Definition: closure.h:14
Specifies all the configuration required by the runtime library to launch the root isolate...
static constexpr char kNavigationChannel[]
Definition: engine.cc:34
virtual void OnEngineUpdateSemantics(SemanticsNodeUpdates updates, CustomAccessibilityActionUpdates actions)=0
When the accessibility tree has been updated by the Flutter application, this new information needs t...
SemanticsAction action
std::optional< uint32_t > GetUIIsolateReturnCode()
As described in the discussion for UIIsolateHasLivePorts, the "done-ness" of a Dart application is tr...
Definition: engine.cc:253
The subset of state which is owned by the shell or engine and passed through the RuntimeController in...
Definition: ui_dart_state.h:43
static constexpr char kAssetChannel[]
Definition: engine.cc:32
RunStatus Run(RunConfiguration configuration)
Moves the root isolate to the DartIsolate::Phase::Running phase on a successful call to this method...
Definition: engine.cc:194
virtual void SetNeedsReportTimings(bool needs_reporting)=0
Notifies the shell that the application has an opinion about whether its frame timings need to be rep...
static MallocMapping Copy(const T *begin, const T *end)
Definition: mapping.h:147
virtual void RequestDartDeferredLibrary(intptr_t loading_unit_id)=0
Invoked when the Dart VM requests that a deferred library be loaded. Notifies the engine that the def...
bool UIIsolateHasLivePorts()
It is an unexpected challenge to determine when a Dart application is "done". The application cannot ...
Definition: engine.cc:265
#define TRACE_EVENT1(category_group, name, arg1_name, arg1_val)
Definition: trace_event.h:94
Describes a running instance of the Dart VM. There may only be one running instance of the Dart VM in...
Definition: dart_vm.h:61
std::unique_ptr< Engine > Spawn(Delegate &delegate, const PointerDataDispatcherMaker &dispatcher_maker, Settings settings, std::unique_ptr< Animator > animator, const std::string &initial_route) const
Create a Engine that shares as many resources as possible with the calling Engine such that together ...
Definition: engine.cc:111
void NotifyIdle(int64_t deadline)
Notifies the engine that the UI task runner is not expected to undertake a new frame workload till a ...
Definition: engine.cc:246
void OnOutputSurfaceDestroyed()
Indicates to the Flutter application that a previously acquired rendering surface has been lost...
Definition: engine.cc:278
A Mapping like NonOwnedMapping, but uses Free as its release proc.
Definition: mapping.h:129
void DispatchSemanticsAction(int id, SemanticsAction action, fml::MallocMapping args)
Notifies the engine that the embedder encountered an accessibility related action on the specified no...
Definition: engine.cc:442
const fml::MallocMapping & data() const
TaskRunners task_runners_
std::function< void(bool)> KeyDataResponse
std::unique_ptr< Animator > animator_
void ReportTimings(std::vector< int64_t > timings)
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.
Definition: engine.cc:241
#define FML_DLOG(severity)
Definition: logging.h:85
RunStatus
Indicates the result of the call to Engine::Run.
Definition: engine.h:80
void ScheduleSecondaryVsyncCallback(uintptr_t id, const fml::closure &callback) override
Schedule a secondary callback to be executed right after the main VsyncWaiter::AsyncWaitForVsync call...
Definition: engine.cc:535
std::shared_ptr< const fml::Mapping > persistent_isolate_data
Definition: settings.h:276
static constexpr char kLocalizationChannel[]
Definition: engine.cc:35
fml::WeakPtr< ImageDecoder > GetWeakPtr() const
void BeginFrame(fml::TimePoint frame_time, uint64_t frame_number)
Notifies the engine that it is time to begin working on a new frame previously scheduled via a call t...
Definition: engine.cc:236
const std::string & GetLastEntrypoint() const
Get the last Entrypoint that was used in the RunConfiguration when |Engine::Run| was called...
Definition: engine.cc:562
std::unordered_map< int32_t, CustomAccessibilityAction > CustomAccessibilityActionUpdates
void DoDispatchPacket(std::unique_ptr< PointerDataPacket > packet, uint64_t trace_flow_id) override
Definition: engine.cc:527
const std::string & GetLastEntrypointLibrary() const
Get the last Entrypoint Library that was used in the RunConfiguration when |Engine::Run| was called...
Definition: engine.cc:566
void LoadDartDeferredLibrary(intptr_t loading_unit_id, std::unique_ptr< const fml::Mapping > snapshot_data, std::unique_ptr< const fml::Mapping > snapshot_instructions)
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.
Definition: engine.cc:575
Settings settings_
static constexpr char kLifecycleChannel[]
Definition: engine.cc:33
fml::WeakPtr< ImageGeneratorRegistry > GetImageGeneratorRegistry()
Get the ImageGeneratorRegistry associated with the current engine.
Definition: engine.cc:156
uint32_t font_initialization_data
Definition: settings.h:195
virtual void UpdateIsolateDescription(const std::string isolate_name, int64_t isolate_port)=0
Notifies the shell of the name of the root isolate and its port when that isolate is launched...
Engine(Delegate &delegate, const PointerDataDispatcherMaker &dispatcher_maker, std::shared_ptr< fml::ConcurrentTaskRunner > image_decoder_task_runner, TaskRunners task_runners, Settings settings, std::unique_ptr< Animator > animator, fml::WeakPtr< IOManager > io_manager, const std::shared_ptr< FontCollection > &font_collection, std::unique_ptr< RuntimeController > runtime_controller)
Creates an instance of the engine with a supplied RuntimeController. Use the other constructor except...
Definition: engine.cc:45
void SetSemanticsEnabled(bool enabled)
Notifies the engine that the embedder has expressed an opinion about whether the accessibility tree s...
Definition: engine.cc:448
AtkStateType state
std::string GetUIIsolateName()
Gets the debug name of the root isolate. But default, the debug name of the isolate is derived from i...
Definition: engine.cc:261
void LoadDartDeferredLibraryError(intptr_t loading_unit_id, const std::string error_message, bool transient)
Indicates to the dart VM that the request to load a deferred library with the specified loading unit ...
Definition: engine.cc:589
void SetViewportMetrics(const ViewportMetrics &metrics)
Updates the viewport metrics for the currently running Flutter application. The viewport metrics deta...
Definition: engine.cc:283
virtual void OnEngineHandlePlatformMessage(std::unique_ptr< PlatformMessage > message)=0
When the Flutter application has a message to send to the underlying platform, the message needs to b...
DEF_SWITCHES_START snapshot asset Path to the directory containing the four files specified by VmSnapshotInstructions and IsolateSnapshotInstructions vm snapshot The VM instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present isolate snapshot The isolate instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present icu symbol Prefix for the symbols representing ICU data linked into the Flutter library dart flags
Definition: switches.h:66
fml::WeakPtr< ImageGeneratorRegistry > GetWeakPtr() const
std::function< void(int64_t)> idle_notification_callback
Definition: settings.h:237