Flutter Engine
The Flutter Engine
Classes | Public Types | Public Member Functions | Friends | List of all members
flutter::Engine Class Referencefinal

#include <engine.h>

Inheritance diagram for flutter::Engine:
flutter::RuntimeDelegate flutter::PointerDataDispatcher::Delegate

Classes

class  Delegate
 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. More...
 

Public Types

enum class  RunStatus { Success , FailureAlreadyRunning , Failure }
 Indicates the result of the call to Engine::Run. More...
 

Public Member Functions

 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)
 Creates an instance of the engine with a supplied RuntimeController. Use the other constructor except for tests. More...
 
 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, std::shared_ptr< VolatilePathTracker > volatile_path_tracker, const std::shared_ptr< fml::SyncSwitch > &gpu_disabled_switch, impeller::RuntimeStageBackend runtime_stage_type=impeller::RuntimeStageBackend::kSkSL)
 Creates an instance of the engine. This is done by the Shell on the UI task runner. More...
 
std::unique_ptr< EngineSpawn (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
 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. More...
 
 ~Engine () override
 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. More...
 
fml::WeakPtr< EngineGetWeakPtr () const
 
RunStatus Run (RunConfiguration configuration)
 Moves the root isolate to the DartIsolate::Phase::Running phase on a successful call to this method. More...
 
bool Restart (RunConfiguration configuration)
 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. More...
 
void SetupDefaultFontManager ()
 Setup default font manager according to specific platform. More...
 
bool UpdateAssetManager (const 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. More...
 
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 to Engine::ScheduleFrame. This call originates in the animator. More...
 
void NotifyIdle (fml::TimeDelta deadline)
 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. More...
 
void NotifyDestroyed ()
 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. More...
 
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. More...
 
Dart_Port GetUIIsolateMainPort ()
 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. More...
 
std::string GetUIIsolateName ()
 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. More...
 
bool UIIsolateHasLivePorts ()
 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. More...
 
tonic::DartErrorHandleType GetUIIsolateLastError ()
 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. More...
 
std::optional< uint32_t > GetUIIsolateReturnCode ()
 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. More...
 
void AddView (int64_t view_id, const ViewportMetrics &view_metrics, std::function< void(bool added)> callback)
 Notify the Flutter application that a new view is available. More...
 
bool RemoveView (int64_t view_id)
 Notify the Flutter application that a view is no longer available. More...
 
void SetViewportMetrics (int64_t view_id, const ViewportMetrics &metrics)
 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. More...
 
void SetDisplays (const std::vector< DisplayData > &displays)
 Updates the display metrics for the currently running Flutter application. More...
 
void DispatchPlatformMessage (std::unique_ptr< PlatformMessage > message)
 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. More...
 
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 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. More...
 
void DispatchSemanticsAction (int node_id, SemanticsAction action, fml::MallocMapping args)
 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. More...
 
void SetSemanticsEnabled (bool enabled)
 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. More...
 
void SetAccessibilityFeatures (int32_t flags)
 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. More...
 
void ScheduleFrame (bool regenerate_layer_trees) override
 
void ScheduleFrame ()
 
void OnAllViewsRendered () override
 
FontCollectionGetFontCollection () override
 
std::shared_ptr< AssetManagerGetAssetManager () override
 
fml::WeakPtr< ImageDecoderGetImageDecoderWeakPtr ()
 
fml::WeakPtr< ImageGeneratorRegistryGetImageGeneratorRegistry ()
 Get the ImageGeneratorRegistry associated with the current engine. More...
 
void DoDispatchPacket (std::unique_ptr< PointerDataPacket > packet, uint64_t trace_flow_id) override
 
void ScheduleSecondaryVsyncCallback (uintptr_t id, const fml::closure &callback) override
 Schedule a secondary callback to be executed right after the main VsyncWaiter::AsyncWaitForVsync callback (which is added by Animator::RequestFrame). More...
 
const std::string & GetLastEntrypoint () const
 Get the last Entrypoint that was used in the RunConfiguration when |Engine::Run| was called. More...
 
const std::string & GetLastEntrypointLibrary () const
 Get the last Entrypoint Library that was used in the RunConfiguration when |Engine::Run| was called. More...
 
const std::vector< std::string > & GetLastEntrypointArgs () const
 Get the last Entrypoint Arguments that was used in the RunConfiguration when |Engine::Run| was called.This is only valid in debug mode. More...
 
const std::string & InitialRoute () const
 Getter for the initial route. This can be set with a platform message. More...
 
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. More...
 
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 id has failed. More...
 
const RuntimeControllerGetRuntimeController () const
 Accessor for the RuntimeController. More...
 
const std::weak_ptr< VsyncWaiterGetVsyncWaiter () const
 
void ShutdownPlatformIsolates ()
 Shuts down all registered platform isolates. Must be called from the platform thread. More...
 
virtual std::string DefaultRouteName ()=0
 
virtual void ScheduleFrame (bool regenerate_layer_trees=true)=0
 
virtual void OnAllViewsRendered ()=0
 
virtual void Render (int64_t view_id, std::unique_ptr< flutter::LayerTree > layer_tree, float device_pixel_ratio)=0
 
virtual void UpdateSemantics (SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions)=0
 
virtual void HandlePlatformMessage (std::unique_ptr< PlatformMessage > message)=0
 
virtual FontCollectionGetFontCollection ()=0
 
virtual std::shared_ptr< AssetManagerGetAssetManager ()=0
 
virtual void OnRootIsolateCreated ()=0
 
virtual void UpdateIsolateDescription (const std::string isolate_name, int64_t isolate_port)=0
 
virtual void SetNeedsReportTimings (bool value)=0
 
virtual std::unique_ptr< std::vector< std::string > > ComputePlatformResolvedLocale (const std::vector< std::string > &supported_locale_data)=0
 
virtual void RequestDartDeferredLibrary (intptr_t loading_unit_id)=0
 
virtual std::weak_ptr< PlatformMessageHandlerGetPlatformMessageHandler () const =0
 
virtual void SendChannelUpdate (std::string name, bool listening)=0
 
virtual double GetScaledFontSize (double unscaled_font_size, int configuration_id) const =0
 

Friends

class testing::ShellTest
 

Additional Inherited Members

- Protected Member Functions inherited from flutter::RuntimeDelegate
virtual ~RuntimeDelegate ()
 

Detailed Description

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 also
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.

Definition at line 73 of file engine.h.

Member Enumeration Documentation

◆ RunStatus

enum class flutter::Engine::RunStatus
strong

Indicates the result of the call to Engine::Run.

Enumerator
Success 

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.

FailureAlreadyRunning 

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.

Failure 

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.

Definition at line 78 of file engine.h.

78 {
79 // NOLINTBEGIN(readability-identifier-naming)
80 //--------------------------------------------------------------------------
81 /// The call to |Engine::Run| was successful and the root isolate is in the
82 /// `DartIsolate::Phase::Running` phase with its entry-point invocation
83 /// already pending in the task queue.
84 ///
85 Success,
86
87 //--------------------------------------------------------------------------
88 /// The engine can only manage a single instance of a root isolate. If a
89 /// previous call to run the root isolate was successful, subsequent calls
90 /// to run the isolate (even if the new run configuration is different) will
91 /// be rejected.
92 ///
93 /// It is up to the caller to decide to re-purpose the running isolate,
94 /// terminate it, or use another shell to host the new isolate. This is
95 /// mostly used by embedders which have a fire-and-forget strategy to root
96 /// isolate launch. For example, the application may try to "launch" an
97 /// isolate when the embedders launches or resumes from a paused state. That
98 /// the isolate is running is not necessarily a failure condition for them.
99 /// But from the engine's perspective, the run configuration was rejected.
100 ///
101 FailureAlreadyRunning,
102
103 //--------------------------------------------------------------------------
104 /// Used to indicate to the embedder that a root isolate was not already
105 /// running but the run configuration was not valid and root isolate could
106 /// not be moved into the `DartIsolate::Phase::Running` phase.
107 ///
108 /// The caller must attempt the run call again with a valid configuration.
109 /// The set of all failure modes is massive and can originate from a variety
110 /// of sub-components. The engine will attempt to log the same when
111 /// possible. With the aid of logs, the common causes of failure are:
112 ///
113 /// * AOT assets were given to JIT/DBC mode VM's and vice-versa.
114 /// * The assets could not be found in the asset manager. Callers must make
115 /// sure their run configuration asset managers have been correctly set
116 /// up.
117 /// * The assets themselves were corrupt or invalid. Callers must make sure
118 /// their asset delivery mechanisms are sound.
119 /// * The application entry-point or the root library of the entry-point
120 /// specified in the run configuration was invalid. Callers must make sure
121 /// that the entry-point is present in the application. If the name of the
122 /// entrypoint is not "main" in the root library, callers must also ensure
123 /// that the snapshotting process has not tree-shaken away this
124 /// entrypoint. This requires the decoration of the entrypoint with the
125 /// `@pragma('vm:entry-point')` directive. This problem will manifest in
126 /// AOT mode operation of the Dart VM.
127 ///
128 Failure,
129 // NOLINTEND(readability-identifier-naming)
130 };

Constructor & Destructor Documentation

◆ Engine() [1/2]

flutter::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 
)

Creates an instance of the engine with a supplied RuntimeController. Use the other constructor except for tests.

Definition at line 40 of file engine.cc.

51 : delegate_(delegate),
52 settings_(settings),
53 animator_(std::move(animator)),
54 runtime_controller_(std::move(runtime_controller)),
55 font_collection_(font_collection),
56 image_decoder_(ImageDecoder::Make(settings_,
57 task_runners,
58 image_decoder_task_runner,
59 io_manager,
60 gpu_disabled_switch)),
61 task_runners_(task_runners),
62 weak_factory_(this) {
63 pointer_data_dispatcher_ = dispatcher_maker(*this);
64}
static std::unique_ptr< ImageDecoder > Make(const Settings &settings, const TaskRunners &runners, std::shared_ptr< fml::ConcurrentTaskRunner > concurrent_task_runner, fml::WeakPtr< IOManager > io_manager, const std::shared_ptr< fml::SyncSwitch > &gpu_disabled_switch)

◆ Engine() [2/2]

flutter::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,
std::shared_ptr< VolatilePathTracker volatile_path_tracker,
const std::shared_ptr< fml::SyncSwitch > &  gpu_disabled_switch,
impeller::RuntimeStageBackend  runtime_stage_type = impeller::RuntimeStageBackend::kSkSL 
)

Creates an instance of the engine. This is done by the Shell on the UI task runner.

Parameters
delegateThe 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.
dispatcher_makerThe 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.
vmAn instance of the running Dart VM.
[in]isolate_snapshotThe 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.
[in]task_runnersThe task runners used by the shell that hosts this engine.
[in]settingsThe settings used to initialize the shell and the engine.
[in]animatorThe animator used to schedule frames.
[in]snapshot_delegateThe 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.
[in]io_managerThe IO manager used by this root isolate to schedule tasks that manage resources on the GPU.

Definition at line 66 of file engine.cc.

80 : Engine(delegate,
81 dispatcher_maker,
82 vm.GetConcurrentWorkerTaskRunner(),
83 task_runners,
85 std::move(animator),
86 io_manager,
87 std::make_shared<FontCollection>(),
88 nullptr,
89 gpu_disabled_switch) {
90 runtime_controller_ = std::make_unique<RuntimeController>(
91 *this, // runtime delegate
92 &vm, // VM
93 std::move(isolate_snapshot), // isolate snapshot
94 settings_.idle_notification_callback, // idle notification callback
95 platform_data, // platform data
96 settings_.isolate_create_callback, // isolate create callback
97 settings_.isolate_shutdown_callback, // isolate shutdown callback
98 settings_.persistent_isolate_data, // persistent isolate data
99 UIDartState::Context{
100 task_runners_, // task runners
101 std::move(snapshot_delegate), // snapshot delegate
102 std::move(io_manager), // io manager
103 unref_queue, // Skia unref queue
104 image_decoder_->GetWeakPtr(), // image decoder
105 image_generator_registry_.GetWeakPtr(), // image generator registry
106 settings_.advisory_script_uri, // advisory script uri
107 settings_.advisory_script_entrypoint, // advisory script entrypoint
108 std::move(volatile_path_tracker), // volatile path tracker
109 vm.GetConcurrentWorkerTaskRunner(), // concurrent task runner
110 settings_.enable_impeller, // enable impeller
111 runtime_stage_type, // runtime stage type
112 });
113}
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)
Creates an instance of the engine with a supplied RuntimeController. Use the other constructor except...
Definition: engine.cc:40
std::shared_ptr< const fml::Mapping > persistent_isolate_data
Definition: settings.h:337
fml::closure isolate_shutdown_callback
Definition: settings.h:284
fml::closure isolate_create_callback
Definition: settings.h:280
std::function< void(int64_t)> idle_notification_callback
Definition: settings.h:298

◆ ~Engine()

flutter::Engine::~Engine ( )
overridedefault

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.

Member Function Documentation

◆ AddView()

void flutter::Engine::AddView ( int64_t  view_id,
const ViewportMetrics view_metrics,
std::function< void(bool added)>  callback 
)

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.
Parameters
[in]view_idThe ID of the new view.
[in]viewport_metricsThe initial viewport metrics for the view.
[in]callbackCallback that will be invoked once the engine attempts to add the view.

Definition at line 300 of file engine.cc.

302 {
303 runtime_controller_->AddView(view_id, view_metrics, std::move(callback));
304}
FlKeyEvent uint64_t FlKeyResponderAsyncCallback callback

◆ BeginFrame()

void flutter::Engine::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 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.
Parameters
[in]frame_timeThe point at which the current frame interval began. May be used by animation interpolators, physics simulations, etc..
[in]frame_numberThe frame number recorded by the animator. Used by the framework to associate frame specific debug information with frame timings and timeline events.

Definition at line 263 of file engine.cc.

263 {
264 runtime_controller_->BeginFrame(frame_time, frame_number);
265}

◆ DispatchPlatformMessage()

void flutter::Engine::DispatchPlatformMessage ( std::unique_ptr< PlatformMessage message)

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.

Parameters
[in]messageThe message sent from the embedder to the Dart application.

Definition at line 316 of file engine.cc.

316 {
317 std::string channel = message->channel();
318 if (channel == kLifecycleChannel) {
319 if (HandleLifecyclePlatformMessage(message.get())) {
320 return;
321 }
322 } else if (channel == kLocalizationChannel) {
323 if (HandleLocalizationPlatformMessage(message.get())) {
324 return;
325 }
326 } else if (channel == kSettingsChannel) {
327 HandleSettingsPlatformMessage(message.get());
328 return;
329 } else if (!runtime_controller_->IsRootIsolateRunning() &&
330 channel == kNavigationChannel) {
331 // If there's no runtime_, we may still need to set the initial route.
332 HandleNavigationPlatformMessage(std::move(message));
333 return;
334 }
335
336 if (runtime_controller_->IsRootIsolateRunning() &&
337 runtime_controller_->DispatchPlatformMessage(std::move(message))) {
338 return;
339 }
340
341 FML_DLOG(WARNING) << "Dropping platform message on channel: " << channel;
342}
#define FML_DLOG(severity)
Definition: logging.h:102
Win32Message message
static constexpr char kSettingsChannel[]
Definition: engine.cc:31
static constexpr char kLocalizationChannel[]
Definition: engine.cc:30
static constexpr char kNavigationChannel[]
Definition: engine.cc:29
static constexpr char kLifecycleChannel[]
Definition: engine.cc:28

◆ DispatchPointerDataPacket()

void flutter::Engine::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 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.

Parameters
[in]packetThe pointer data packet containing multiple input events.
[in]trace_flow_idThe 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.

Definition at line 433 of file engine.cc.

435 {
436 TRACE_EVENT0_WITH_FLOW_IDS("flutter", "Engine::DispatchPointerDataPacket",
437 /*flow_id_count=*/1,
438 /*flow_ids=*/&trace_flow_id);
439 TRACE_FLOW_STEP("flutter", "PointerEvent", trace_flow_id);
440 pointer_data_dispatcher_->DispatchPacket(std::move(packet), trace_flow_id);
441}
#define TRACE_FLOW_STEP(category, name, id)
Definition: trace_event.h:193
#define TRACE_EVENT0_WITH_FLOW_IDS(category_group, name, flow_id_count, flow_ids)
Definition: trace_event.h:126

◆ DispatchSemanticsAction()

void flutter::Engine::DispatchSemanticsAction ( int  node_id,
SemanticsAction  action,
fml::MallocMapping  args 
)

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.

Parameters
[in]node_idThe identifier of the accessibility node.
[in]actionThe accessibility related action performed on the node of the specified ID.
[in]argsOptional data that applies to the specified action.

Definition at line 443 of file engine.cc.

445 {
446 runtime_controller_->DispatchSemanticsAction(node_id, action,
447 std::move(args));
448}
G_BEGIN_DECLS G_MODULE_EXPORT FlValue * args

◆ DoDispatchPacket()

void flutter::Engine::DoDispatchPacket ( std::unique_ptr< PointerDataPacket packet,
uint64_t  trace_flow_id 
)
overridevirtual

Actually dispatch the packet using Engine's animator_ and runtime_controller_.

Implements flutter::PointerDataDispatcher::Delegate.

Definition at line 528 of file engine.cc.

529 {
530 animator_->EnqueueTraceFlowId(trace_flow_id);
531 if (runtime_controller_) {
532 runtime_controller_->DispatchPointerDataPacket(*packet);
533 }
534}

◆ GetAssetManager()

std::shared_ptr< AssetManager > flutter::Engine::GetAssetManager ( )
overridevirtual

Implements flutter::RuntimeDelegate.

Definition at line 164 of file engine.cc.

164 {
165 return asset_manager_;
166}

◆ GetFontCollection()

FontCollection & flutter::Engine::GetFontCollection ( )
overridevirtual

Implements flutter::RuntimeDelegate.

Definition at line 524 of file engine.cc.

524 {
525 return *font_collection_;
526}

◆ GetImageDecoderWeakPtr()

fml::WeakPtr< ImageDecoder > flutter::Engine::GetImageDecoderWeakPtr ( )

Definition at line 168 of file engine.cc.

168 {
169 return image_decoder_->GetWeakPtr();
170}

◆ GetImageGeneratorRegistry()

fml::WeakPtr< ImageGeneratorRegistry > flutter::Engine::GetImageGeneratorRegistry ( )

Get the ImageGeneratorRegistry associated with the current engine.

Returns
The engine's ImageGeneratorRegistry.

Definition at line 172 of file engine.cc.

172 {
173 return image_generator_registry_.GetWeakPtr();
174}
fml::WeakPtr< ImageGeneratorRegistry > GetWeakPtr() const

◆ GetLastEntrypoint()

const std::string & flutter::Engine::GetLastEntrypoint ( ) const

Get the last Entrypoint that was used in the RunConfiguration when |Engine::Run| was called.

Definition at line 563 of file engine.cc.

563 {
564 return last_entry_point_;
565}

◆ GetLastEntrypointArgs()

const std::vector< std::string > & flutter::Engine::GetLastEntrypointArgs ( ) const

Get the last Entrypoint Arguments that was used in the RunConfiguration when |Engine::Run| was called.This is only valid in debug mode.

Definition at line 571 of file engine.cc.

571 {
572 return last_entry_point_args_;
573}

◆ GetLastEntrypointLibrary()

const std::string & flutter::Engine::GetLastEntrypointLibrary ( ) const

Get the last Entrypoint Library that was used in the RunConfiguration when |Engine::Run| was called.

Definition at line 567 of file engine.cc.

567 {
568 return last_entry_point_library_;
569}

◆ GetRuntimeController()

const RuntimeController * flutter::Engine::GetRuntimeController ( ) const
inline

Accessor for the RuntimeController.

Definition at line 965 of file engine.h.

965 {
966 return runtime_controller_.get();
967 }

◆ GetUIIsolateLastError()

tonic::DartErrorHandleType flutter::Engine::GetUIIsolateLastError ( )

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.

Returns
The ui isolate last error.

Definition at line 296 of file engine.cc.

296 {
297 return runtime_controller_->GetLastError();
298}

◆ GetUIIsolateMainPort()

Dart_Port flutter::Engine::GetUIIsolateMainPort ( )

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.

Returns
The main port of the root isolate.

Definition at line 284 of file engine.cc.

284 {
285 return runtime_controller_->GetMainPort();
286}

◆ GetUIIsolateName()

std::string flutter::Engine::GetUIIsolateName ( )

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.

Returns
The debug name of the root isolate.

Definition at line 288 of file engine.cc.

288 {
289 return runtime_controller_->GetIsolateName();
290}

◆ GetUIIsolateReturnCode()

std::optional< uint32_t > flutter::Engine::GetUIIsolateReturnCode ( )

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 also
UIIsolateHasLivePorts
Returns
The return code (if specified) by the isolate.

Definition at line 280 of file engine.cc.

280 {
281 return runtime_controller_->GetRootIsolateReturnCode();
282}

◆ GetVsyncWaiter()

const std::weak_ptr< VsyncWaiter > flutter::Engine::GetVsyncWaiter ( ) const

Definition at line 612 of file engine.cc.

612 {
613 return animator_->GetVsyncWaiter();
614}

◆ GetWeakPtr()

fml::WeakPtr< Engine > flutter::Engine::GetWeakPtr ( ) const
Returns
The pointer to this instance of the engine. The engine may only be accessed safely on the UI task runner.

Definition at line 155 of file engine.cc.

155 {
156 return weak_factory_.GetWeakPtr();
157}

◆ InitialRoute()

const std::string & flutter::Engine::InitialRoute ( ) const
inline

Getter for the initial route. This can be set with a platform message.

Definition at line 898 of file engine.h.

898{ return initial_route_; }

◆ LoadDartDeferredLibrary()

void flutter::Engine::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.

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.

Parameters
[in]loading_unit_idThe unique id of the deferred library's loading unit, as passed in by RequestDartDeferredLibrary.
[in]snapshot_dataDart snapshot data of the loading unit's shared library.
[in]snapshot_dataDart snapshot instructions of the loading unit's shared library.

Definition at line 589 of file engine.cc.

592 {
593 if (runtime_controller_->IsRootIsolateRunning()) {
594 runtime_controller_->LoadDartDeferredLibrary(
595 loading_unit_id, std::move(snapshot_data),
596 std::move(snapshot_instructions));
597 } else {
598 LoadDartDeferredLibraryError(loading_unit_id, "No running root isolate.",
599 true);
600 }
601}
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:603

◆ LoadDartDeferredLibraryError()

void flutter::Engine::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 id has failed.

The dart future returned by the initiating loadLibrary() call will complete with an error.

Parameters
[in]loading_unit_idThe unique id of the deferred library's loading unit, as passed in by RequestDartDeferredLibrary.
[in]error_messageThe error message that will appear in the dart Future.
[in]transientA 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.

Definition at line 603 of file engine.cc.

605 {
606 if (runtime_controller_->IsRootIsolateRunning()) {
607 runtime_controller_->LoadDartDeferredLibraryError(loading_unit_id,
608 error_message, transient);
609 }
610}

◆ NotifyDestroyed()

void flutter::Engine::NotifyDestroyed ( )

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.

Definition at line 275 of file engine.cc.

275 {
276 TRACE_EVENT0("flutter", "Engine::NotifyDestroyed");
277 runtime_controller_->NotifyDestroyed();
278}
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:131

◆ NotifyIdle()

void flutter::Engine::NotifyIdle ( fml::TimeDelta  deadline)

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.

Parameters
[in]deadlineThe deadline is used by the VM to determine if the corresponding sweep can be performed within the deadline.

Definition at line 271 of file engine.cc.

271 {
272 runtime_controller_->NotifyIdle(deadline);
273}

◆ OnAllViewsRendered()

void flutter::Engine::OnAllViewsRendered ( )
overridevirtual

Implements flutter::RuntimeDelegate.

Definition at line 469 of file engine.cc.

469 {
470 animator_->OnAllViewsRendered();
471}

◆ RemoveView()

bool flutter::Engine::RemoveView ( int64_t  view_id)

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.

Parameters
[in]view_idThe ID of the view.
Returns
Whether the view was removed.

Definition at line 306 of file engine.cc.

306 {
307 return runtime_controller_->RemoveView(view_id);
308}

◆ ReportTimings()

void flutter::Engine::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.

See also
FrameTiming
Parameters
[in]timingsCollection 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.

Definition at line 267 of file engine.cc.

267 {
268 runtime_controller_->ReportTimings(std::move(timings));
269}

◆ Restart()

bool flutter::Engine::Restart ( RunConfiguration  configuration)

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.
Parameters
[in]configurationThe configuration used to launch the new isolate.
Returns
Whether the restart was successful. If not, the engine and its shell must be discarded.

Definition at line 201 of file engine.cc.

201 {
202 TRACE_EVENT0("flutter", "Engine::Restart");
203 if (!configuration.IsValid()) {
204 FML_LOG(ERROR) << "Engine run configuration was invalid.";
205 return false;
206 }
207 delegate_.OnPreEngineRestart();
208 runtime_controller_ = runtime_controller_->Clone();
209 UpdateAssetManager(nullptr);
210 return Run(std::move(configuration)) == Engine::RunStatus::Success;
211}
virtual void OnPreEngineRestart()=0
Notifies the delegate that the root isolate of the application is about to be discarded and a new iso...
RunStatus Run(RunConfiguration configuration)
Moves the root isolate to the DartIsolate::Phase::Running phase on a successful call to this method.
Definition: engine.cc:213
bool UpdateAssetManager(const std::shared_ptr< AssetManager > &asset_manager)
Updates the asset manager referenced by the root isolate of a Flutter application....
Definition: engine.cc:176
#define FML_LOG(severity)
Definition: logging.h:82
#define ERROR(message)
Definition: elf_loader.cc:260

◆ Run()

Engine::RunStatus flutter::Engine::Run ( RunConfiguration  configuration)

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).

Parameters
[in]configurationThe configuration used to run the root isolate. The configuration must be valid.
Returns
The result of the call to run the root isolate.

Definition at line 213 of file engine.cc.

213 {
214 if (!configuration.IsValid()) {
215 FML_LOG(ERROR) << "Engine run configuration was invalid.";
216 return RunStatus::Failure;
217 }
218
219 last_entry_point_ = configuration.GetEntrypoint();
220 last_entry_point_library_ = configuration.GetEntrypointLibrary();
221#if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG)
222 // This is only used to support restart.
223 last_entry_point_args_ = configuration.GetEntrypointArgs();
224#endif
225
226 UpdateAssetManager(configuration.GetAssetManager());
227
228 if (runtime_controller_->IsRootIsolateRunning()) {
230 }
231
232 // If the embedding prefetched the default font manager, then set up the
233 // font manager later in the engine launch process. This makes it less
234 // likely that the setup will need to wait for the prefetch to complete.
235 auto root_isolate_create_callback = [&]() {
236 if (settings_.prefetched_default_font_manager) {
238 }
239 };
240
241 if (!runtime_controller_->LaunchRootIsolate(
242 settings_, //
243 root_isolate_create_callback, //
244 configuration.GetEntrypoint(), //
245 configuration.GetEntrypointLibrary(), //
246 configuration.GetEntrypointArgs(), //
247 configuration.TakeIsolateConfiguration()) //
248 ) {
249 return RunStatus::Failure;
250 }
251
252 auto service_id = runtime_controller_->GetRootIsolateServiceID();
253 if (service_id.has_value()) {
254 std::unique_ptr<PlatformMessage> service_id_message =
255 std::make_unique<flutter::PlatformMessage>(
256 kIsolateChannel, MakeMapping(service_id.value()), nullptr);
257 HandlePlatformMessage(std::move(service_id_message));
258 }
259
261}
void SetupDefaultFontManager()
Setup default font manager according to specific platform.
Definition: engine.cc:159
static constexpr char kIsolateChannel[]
Definition: engine.cc:32
bool prefetched_default_font_manager
Definition: settings.h:219

◆ ScheduleFrame() [1/2]

void flutter::Engine::ScheduleFrame ( )
inline

Schedule a frame with the default parameter of regenerating the layer tree.

Definition at line 845 of file engine.h.

845{ ScheduleFrame(true); }
void ScheduleFrame()
Definition: engine.h:845

◆ ScheduleFrame() [2/2]

void flutter::Engine::ScheduleFrame ( bool  regenerate_layer_trees)
overridevirtual

Implements flutter::RuntimeDelegate.

Definition at line 465 of file engine.cc.

465 {
466 animator_->RequestFrame(regenerate_layer_trees);
467}

◆ ScheduleSecondaryVsyncCallback()

void flutter::Engine::ScheduleSecondaryVsyncCallback ( uintptr_t  id,
const fml::closure callback 
)
overridevirtual

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.

Implements flutter::PointerDataDispatcher::Delegate.

Definition at line 536 of file engine.cc.

537 {
538 animator_->ScheduleSecondaryVsyncCallback(id, callback);
539}

◆ SetAccessibilityFeatures()

void flutter::Engine::SetAccessibilityFeatures ( int32_t  flags)

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.

Parameters
[in]flagsThe features to enable in the accessibility tree.

Definition at line 454 of file engine.cc.

454 {
455 runtime_controller_->SetAccessibilityFeatures(flags);
456}
FlutterSemanticsFlag flags

◆ SetDisplays()

void flutter::Engine::SetDisplays ( const std::vector< DisplayData > &  displays)

Updates the display metrics for the currently running Flutter application.

Parameters
[in]displaysA complete list of displays

Definition at line 616 of file engine.cc.

616 {
617 runtime_controller_->SetDisplays(displays);
619}

◆ SetSemanticsEnabled()

void flutter::Engine::SetSemanticsEnabled ( bool  enabled)

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.

Parameters
[in]enabledWhether the accessibility tree is enabled or disabled.

Definition at line 450 of file engine.cc.

450 {
451 runtime_controller_->SetSemanticsEnabled(enabled);
452}

◆ SetupDefaultFontManager()

void flutter::Engine::SetupDefaultFontManager ( )

Setup default font manager according to specific platform.

Definition at line 159 of file engine.cc.

159 {
160 TRACE_EVENT0("flutter", "Engine::SetupDefaultFontManager");
161 font_collection_->SetupDefaultFontManager(settings_.font_initialization_data);
162}
uint32_t font_initialization_data
Definition: settings.h:254

◆ SetViewportMetrics()

void flutter::Engine::SetViewportMetrics ( int64_t  view_id,
const ViewportMetrics metrics 
)

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 also
ViewportMetrics
Parameters
[in]view_idThe ID for the view that metrics describes.
[in]metricsThe metrics.

Definition at line 310 of file engine.cc.

311 {
312 runtime_controller_->SetViewportMetrics(view_id, metrics);
314}

◆ ShutdownPlatformIsolates()

void flutter::Engine::ShutdownPlatformIsolates ( )

Shuts down all registered platform isolates. Must be called from the platform thread.

Definition at line 621 of file engine.cc.

621 {
622 runtime_controller_->ShutdownPlatformIsolates();
623}

◆ Spawn()

std::unique_ptr< Engine > flutter::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

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.

This should only be called on running Engines.

Returns
A new Engine with a running isolate.
See also
Engine::Engine
DartIsolate::SpawnIsolate

Definition at line 115 of file engine.cc.

123 {
124 auto result = std::make_unique<Engine>(
125 /*delegate=*/delegate,
126 /*dispatcher_maker=*/dispatcher_maker,
127 /*image_decoder_task_runner=*/
128 runtime_controller_->GetDartVM()->GetConcurrentWorkerTaskRunner(),
129 /*task_runners=*/task_runners_,
130 /*settings=*/settings,
131 /*animator=*/std::move(animator),
132 /*io_manager=*/io_manager,
133 /*font_collection=*/font_collection_,
134 /*runtime_controller=*/nullptr,
135 /*gpu_disabled_switch=*/gpu_disabled_switch);
136 result->runtime_controller_ = runtime_controller_->Spawn(
137 /*p_client=*/*result,
138 /*advisory_script_uri=*/settings.advisory_script_uri,
139 /*advisory_script_entrypoint=*/settings.advisory_script_entrypoint,
140 /*idle_notification_callback=*/settings.idle_notification_callback,
141 /*isolate_create_callback=*/settings.isolate_create_callback,
142 /*isolate_shutdown_callback=*/settings.isolate_shutdown_callback,
143 /*persistent_isolate_data=*/settings.persistent_isolate_data,
144 /*io_manager=*/io_manager,
145 /*image_decoder=*/result->GetImageDecoderWeakPtr(),
146 /*image_generator_registry=*/result->GetImageGeneratorRegistry(),
147 /*snapshot_delegate=*/std::move(snapshot_delegate));
148 result->initial_route_ = initial_route;
149 result->asset_manager_ = asset_manager_;
150 return result;
151}
GAsyncResult * result

◆ UIIsolateHasLivePorts()

bool flutter::Engine::UIIsolateHasLivePorts ( )

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.

Returns
Check if the root isolate has any live ports.

Definition at line 292 of file engine.cc.

292 {
293 return runtime_controller_->HasLivePorts();
294}

◆ UpdateAssetManager()

bool flutter::Engine::UpdateAssetManager ( const 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.

Parameters
[in]asset_managerThe new asset manager to use for the running root isolate.
Returns
If the asset manager was successfully replaced. This may fail if the new asset manager is invalid.

Definition at line 176 of file engine.cc.

177 {
178 if (asset_manager_ && new_asset_manager &&
179 *asset_manager_ == *new_asset_manager) {
180 return false;
181 }
182
183 asset_manager_ = new_asset_manager;
184
185 if (!asset_manager_) {
186 return false;
187 }
188
189 // Using libTXT as the text engine.
190 if (settings_.use_asset_fonts) {
191 font_collection_->RegisterFonts(asset_manager_);
192 }
193
194 if (settings_.use_test_fonts) {
195 font_collection_->RegisterTestFonts();
196 }
197
198 return true;
199}
bool use_asset_fonts
Definition: settings.h:215

Friends And Related Function Documentation

◆ testing::ShellTest

friend class testing::ShellTest
friend

Definition at line 1033 of file engine.h.


The documentation for this class was generated from the following files: