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

#include <shell.h>

Inheritance diagram for flutter::Shell:
flutter::PlatformView::Delegate flutter::Animator::Delegate flutter::Engine::Delegate flutter::Rasterizer::Delegate flutter::ServiceProtocol::Handler flutter::ResourceCacheLimitItem

Public Types

template<class T >
using CreateCallback = std::function< std::unique_ptr< T >(Shell &)>
 
typedef std::function< std::unique_ptr< Engine >(Engine::Delegate &delegate, const PointerDataDispatcherMaker &dispatcher_maker, DartVM &vm, fml::RefPtr< const DartSnapshot > isolate_snapshot, TaskRunners task_runners, const PlatformData &platform_data, Settings settings, std::unique_ptr< Animator > animator, fml::WeakPtr< IOManager > io_manager, fml::RefPtr< SkiaUnrefQueue > unref_queue, fml::TaskRunnerAffineWeakPtr< SnapshotDelegate > snapshot_delegate, std::shared_ptr< VolatilePathTracker > volatile_path_tracker, const std::shared_ptr< fml::SyncSwitch > &gpu_disabled_switch, impeller::RuntimeStageBackend runtime_stage_type)> EngineCreateCallback
 
- Public Types inherited from flutter::PlatformView::Delegate
using AddViewCallback = PlatformView::AddViewCallback
 
using RemoveViewCallback = PlatformView::RemoveViewCallback
 
using KeyDataResponse = std::function< void(bool)>
 
- Public Types inherited from flutter::ServiceProtocol::Handler
using ServiceProtocolMap = std::map< std::string_view, std::string_view >
 

Public Member Functions

 ~Shell ()
 Destroys the shell. This is a synchronous operation and synchronous barrier blocks are introduced on the various threads to ensure shutdown of all shell sub-components before this method returns. More...
 
std::unique_ptr< ShellSpawn (RunConfiguration run_configuration, const std::string &initial_route, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer) const
 Creates one Shell from another Shell where the created Shell takes the opportunity to share any internal components it can. This results is a Shell that has a smaller startup time cost and a smaller memory footprint than an Shell created with the Create function. More...
 
void RunEngine (RunConfiguration run_configuration)
 Starts an isolate for the given RunConfiguration. More...
 
void RunEngine (RunConfiguration run_configuration, const std::function< void(Engine::RunStatus)> &result_callback)
 Starts an isolate for the given RunConfiguration. The result_callback will be called with the status of the operation. More...
 
const SettingsGetSettings () const override
 
const TaskRunnersGetTaskRunners () const override
 If callers wish to interact directly with any shell subcomponents, they must (on the platform thread) obtain a task runner that the component is designed to run on and a weak pointer to that component. They may then post a task to that task runner, do the validity check on that task runner before performing any operation on that component. This accessor allows callers to access the task runners for this shell. More...
 
const fml::RefPtr< fml::RasterThreadMergerGetParentRasterThreadMerger () const override
 Getting the raster thread merger from parent shell, it can be a null RefPtr when it's a root Shell or the embedder_->SupportsDynamicThreadMerging() returns false. More...
 
fml::TaskRunnerAffineWeakPtr< RasterizerGetRasterizer () const
 Rasterizers may only be accessed on the raster task runner. More...
 
fml::WeakPtr< EngineGetEngine ()
 Engines may only be accessed on the UI thread. This method is deprecated, and implementers should instead use other API available on the Shell or the PlatformView. More...
 
fml::WeakPtr< PlatformViewGetPlatformView ()
 Platform views may only be accessed on the platform task runner. More...
 
fml::WeakPtr< ShellIOManagerGetIOManager ()
 The IO Manager may only be accessed on the IO task runner. More...
 
void NotifyLowMemoryWarning () const
 Used by embedders to notify that there is a low memory warning. The shell will attempt to purge caches. Current, only the rasterizer cache is purged. More...
 
bool IsSetup () const
 Used by embedders to check if all shell subcomponents are initialized. It is the embedder's responsibility to make this call before accessing any other shell method. A shell that is not set up must be discarded and another one created with updated settings. More...
 
Rasterizer::Screenshot Screenshot (Rasterizer::ScreenshotType type, bool base64_encode)
 Captures a screenshot and optionally Base64 encodes the data of the last layer tree rendered by the rasterizer in this shell. More...
 
fml::Status WaitForFirstFrame (fml::TimeDelta timeout)
 Pauses the calling thread until the first frame is presented. More...
 
bool ReloadSystemFonts ()
 Used by embedders to reload the system fonts in FontCollection. It also clears the cached font families and send system channel message to framework to rebuild affected widgets. More...
 
std::optional< DartErrorCodeGetUIIsolateLastError () const
 Used by embedders to get the last error from the Dart UI Isolate, if one exists. More...
 
bool EngineHasLivePorts () const
 Used by embedders to check if the Engine is running and has any live ports remaining. For example, the Flutter tester uses this method to check whether it should continue to wait for a running test or not. More...
 
std::shared_ptr< const fml::SyncSwitchGetIsGpuDisabledSyncSwitch () const override
 Accessor for the disable GPU SyncSwitch. More...
 
void SetGpuAvailability (GpuAvailability availability)
 Marks the GPU as available or unavailable. More...
 
DartVMGetDartVM ()
 Get a pointer to the Dart VM used by this running shell instance. More...
 
void OnDisplayUpdates (std::vector< std::unique_ptr< Display > > displays)
 Notifies the display manager of the updates. More...
 
double GetMainDisplayRefreshRate ()
 Queries the DisplayManager for the main display refresh rate. More...
 
void RegisterImageDecoder (ImageGeneratorFactory factory, int32_t priority)
 Install a new factory that can match against and decode image data. More...
 
const std::shared_ptr< PlatformMessageHandler > & GetPlatformMessageHandler () const override
 Returns the delegate object that handles PlatformMessage's from Flutter to the host platform (and its responses). More...
 
const std::weak_ptr< VsyncWaiterGetVsyncWaiter () const
 
const std::shared_ptr< fml::ConcurrentTaskRunnerGetConcurrentWorkerTaskRunner () const
 
- Public Member Functions inherited from flutter::PlatformView::Delegate
virtual void OnPlatformViewCreated (std::unique_ptr< Surface > surface)=0
 Notifies the delegate that the platform view was created with the given render surface. This surface is platform (iOS, Android) and client-rendering API (OpenGL, Software, Metal, Vulkan) specific. This is usually a sign to the rasterizer to set up and begin rendering to that surface. More...
 
virtual void OnPlatformViewDestroyed ()=0
 Notifies the delegate that the platform view was destroyed. This is usually a sign to the rasterizer to suspend rendering a previously configured surface and collect any intermediate resources. More...
 
virtual void OnPlatformViewScheduleFrame ()=0
 Notifies the delegate that the platform needs to schedule a frame to regenerate the layer tree and redraw the surface. More...
 
virtual void OnPlatformViewAddView (int64_t view_id, const ViewportMetrics &viewport_metrics, AddViewCallback callback)=0
 Allocate resources for a new non-implicit view and inform Dart about the view, and on success, schedules a new frame. More...
 
virtual void OnPlatformViewRemoveView (int64_t view_id, RemoveViewCallback callback)=0
 Deallocate resources for a removed view and inform Dart about the removal. More...
 
virtual void OnPlatformViewSetNextFrameCallback (const fml::closure &closure)=0
 Notifies the delegate that the specified callback needs to be invoked after the rasterizer is done rendering the next frame. This callback will be called on the render thread and it is caller responsibility to perform any re-threading as necessary. Due to the asynchronous nature of rendering in Flutter, embedders usually add a placeholder over the contents in which Flutter is going to render when Flutter is first initialized. This callback may be used as a signal to remove that placeholder. More...
 
virtual void OnPlatformViewSetViewportMetrics (int64_t view_id, const ViewportMetrics &metrics)=0
 Notifies the delegate the viewport metrics of a view have been updated. The rasterizer will need to be reconfigured to render the frame in the updated viewport metrics. More...
 
virtual void OnPlatformViewDispatchPlatformMessage (std::unique_ptr< PlatformMessage > message)=0
 Notifies the delegate that the platform has dispatched a platform message from the embedder to the Flutter application. This message must be forwarded to the running isolate hosted by the engine on the UI thread. More...
 
virtual void OnPlatformViewDispatchPointerDataPacket (std::unique_ptr< PointerDataPacket > packet)=0
 Notifies the delegate that the platform view has encountered a pointer event. This pointer event needs to be forwarded to the running root isolate hosted by the engine on the UI thread. More...
 
virtual void OnPlatformViewDispatchSemanticsAction (int32_t node_id, SemanticsAction action, fml::MallocMapping args)=0
 Notifies the delegate that the platform view has encountered an accessibility related action on the specified node. This event must be forwarded to the running root isolate hosted by the engine on the UI thread. More...
 
virtual void OnPlatformViewSetSemanticsEnabled (bool enabled)=0
 Notifies the delegate that the embedder has expressed an opinion about whether the accessibility tree needs to be enabled or disabled. This information needs to be forwarded to the root isolate running on the UI thread. More...
 
virtual void OnPlatformViewSetAccessibilityFeatures (int32_t flags)=0
 Notifies the delegate that the embedder has expressed an opinion about the features to enable in the accessibility tree. More...
 
virtual void OnPlatformViewRegisterTexture (std::shared_ptr< Texture > texture)=0
 Notifies the delegate that the embedder has specified a texture that it want the rasterizer to composite within the Flutter layer tree. All textures must have a unique identifier. When the rasterizer encounters an external texture within its hierarchy, it gives the embedder a chance to update that texture on the raster thread before it composites the same on-screen. More...
 
virtual void OnPlatformViewUnregisterTexture (int64_t texture_id)=0
 Notifies the delegate that the embedder will no longer attempt to composite the specified texture within the layer tree. This allows the rasterizer to collect associated resources. More...
 
virtual void OnPlatformViewMarkTextureFrameAvailable (int64_t texture_id)=0
 Notifies the delegate that the embedder has updated the contents of the texture with the specified identifier. Typically, Flutter will only render a frame if there is an updated layer tree. However, in cases where the layer tree is static but one of the externally composited textures has been updated by the embedder, the embedder needs to notify the rasterizer to render a new frame. In such cases, the existing layer tree may be reused with the frame composited with all updated external textures. More...
 
virtual void LoadDartDeferredLibrary (intptr_t loading_unit_id, std::unique_ptr< const fml::Mapping > snapshot_data, std::unique_ptr< const fml::Mapping > snapshot_instructions)=0
 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...
 
virtual void LoadDartDeferredLibraryError (intptr_t loading_unit_id, const std::string error_message, bool transient)=0
 Indicates to the dart VM that the request to load a deferred library with the specified loading unit id has failed. More...
 
virtual void UpdateAssetResolverByType (std::unique_ptr< AssetResolver > updated_asset_resolver, AssetResolver::AssetResolverType type)=0
 Replaces the asset resolver handled by the engine's AssetManager of the specified type with updated_asset_resolver. The matching AssetResolver is removed and replaced with updated_asset_resolvers. More...
 
virtual const SettingsOnPlatformViewGetSettings () const =0
 Called by the platform view on the platform thread to get the settings object associated with the platform view instance. More...
 
virtual void OnAnimatorBeginFrame (fml::TimePoint frame_target_time, uint64_t frame_number)=0
 
virtual void OnAnimatorNotifyIdle (fml::TimeDelta deadline)=0
 
virtual void OnAnimatorUpdateLatestFrameTargetTime (fml::TimePoint frame_target_time)=0
 
virtual void OnAnimatorDraw (std::shared_ptr< FramePipeline > pipeline)=0
 
virtual void OnAnimatorDrawLastLayerTrees (std::unique_ptr< FrameTimingsRecorder > frame_timings_recorder)=0
 
virtual void OnEngineUpdateSemantics (SemanticsNodeUpdates updates, CustomAccessibilityActionUpdates actions)=0
 When the accessibility tree has been updated by the Flutter application, this new information needs to be conveyed to the underlying platform. The engine delegates this task to the shell via this call. The engine cannot access the underlying platform directly because of threading considerations. Most platform specific APIs to convey accessibility information are only safe to access on the platform task runner while the engine is running on the UI task runner. More...
 
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 be forwarded to the platform on the appropriate thread (via the platform task runner). The engine delegates this task to the shell via this method. More...
 
virtual void OnPreEngineRestart ()=0
 Notifies the delegate that the root isolate of the application is about to be discarded and a new isolate with the same runtime started in its place. This should only happen in the Flutter "debug" runtime mode in the cold-restart scenario. The embedder may need to reset native resource in response to the restart. More...
 
virtual void OnRootIsolateCreated ()=0
 Notifies the shell that the root isolate is created. Currently, this information is to add to the service protocol list of available root isolates running in the VM and their names so that the appropriate isolate can be selected in the tools for debugging and instrumentation. More...
 
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, restarted (in the cold-restart scenario) or the application itself updates the name of the root isolate (via PlatformDispatcher.setIsolateDebugName in platform_dispatcher.dart). The name of the isolate is meaningless to the engine but is used in instrumentation and tooling. Currently, this information is to update the service protocol list of available root isolates running in the VM and their names so that the appropriate isolate can be selected in the tools for debugging and instrumentation. More...
 
virtual void SetNeedsReportTimings (bool needs_reporting)=0
 Notifies the shell that the application has an opinion about whether its frame timings need to be reported backed to it. Due to the asynchronous nature of rendering in Flutter, it is not possible for the application to determine the total time it took to render a specific frame. While the layer-tree is constructed on the UI thread, it needs to be rendering on the raster thread. Dart code cannot execute on this thread. So any instrumentation about the frame times gathered on this thread needs to be aggregated and sent back to the UI thread for processing in Dart. More...
 
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 resolved to. More...
 
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 deferred library identified by the specified loading unit id should be downloaded and loaded into the Dart VM via LoadDartDeferredLibrary More...
 
virtual fml::TimePoint GetCurrentTimePoint ()=0
 Returns the current fml::TimePoint. This method is primarily provided to allow tests to control Any methods that rely on advancing the clock. More...
 
virtual const std::shared_ptr< PlatformMessageHandler > & GetPlatformMessageHandler () const =0
 Returns the delegate object that handles PlatformMessage's from Flutter to the host platform (and its responses). More...
 
virtual void OnEngineChannelUpdate (std::string name, bool listening)=0
 Invoked when a listener is registered on a platform channel. More...
 
virtual double GetScaledFontSize (double unscaled_font_size, int configuration_id) const =0
 Synchronously invokes platform-specific APIs to apply the system text scaling on the given unscaled font size. More...
 
virtual void OnFrameRasterized (const FrameTiming &frame_timing)=0
 Notifies the delegate that a frame has been rendered. The rasterizer collects profiling information for each part of the frame workload. This profiling information is made available to the delegate for forwarding to subsystems interested in collecting such profiles. Currently, the shell (the delegate) forwards this to the engine where Dart code can react to this information. More...
 
virtual fml::Milliseconds GetFrameBudget ()=0
 
virtual fml::TimePoint GetLatestFrameTargetTime () const =0
 
virtual const TaskRunnersGetTaskRunners () const =0
 Task runners used by the shell. More...
 
virtual const fml::RefPtr< fml::RasterThreadMergerGetParentRasterThreadMerger () const =0
 The raster thread merger from parent shell's rasterizer. More...
 
virtual std::shared_ptr< const fml::SyncSwitchGetIsGpuDisabledSyncSwitch () const =0
 
virtual const SettingsGetSettings () const =0
 
virtual bool ShouldDiscardLayerTree (int64_t view_id, const flutter::LayerTree &tree)=0
 
virtual fml::RefPtr< fml::TaskRunnerGetServiceProtocolHandlerTaskRunner (std::string_view method) const =0
 
virtual Description GetServiceProtocolDescription () const =0
 
virtual bool HandleServiceProtocolMessage (std::string_view method, const ServiceProtocolMap &params, rapidjson::Document *response)=0
 
virtual size_t GetResourceCacheLimit ()=0
 

Static Public Member Functions

static std::unique_ptr< ShellCreate (const PlatformData &platform_data, const TaskRunners &task_runners, Settings settings, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer, bool is_gpu_disabled=false)
 Creates a shell instance using the provided settings. The callbacks to create the various shell subcomponents will be called on the appropriate threads before this method returns. If this is the first instance of a shell in the process, this call also bootstraps the Dart VM. More...
 
static std::pair< DartVMRef, fml::RefPtr< const DartSnapshot > > InferVmInitDataFromSettings (Settings &settings)
 

Friends

class testing::ShellTest
 

Additional Inherited Members

- Protected Member Functions inherited from flutter::ResourceCacheLimitItem
virtual ~ResourceCacheLimitItem ()=default
 

Detailed Description

Perhaps the single most important class in the Flutter engine repository. When embedders create a Flutter application, they are referring to the creation of an instance of a shell. Creation and destruction of the shell is synchronous and the embedder only holds a unique pointer to the shell. The shell does not create the threads its primary components run on. Instead, it is the embedder's responsibility to create threads and give the shell task runners for those threads. Due to deterministic destruction of the shell, the embedder can terminate all threads immediately after collecting the shell. The shell must be created and destroyed on the same thread, but, different shells (i.e. a separate instances of a Flutter application) may be run on different threads simultaneously. The task runners themselves do not have to be unique. If all task runner references given to the shell during shell creation point to the same task runner, the Flutter application is effectively single threaded.

The shell is the central nervous system of the Flutter application. None of the shell components are thread safe and must be created, accessed and destroyed on the same thread. To interact with one another, the various components delegate to the shell for communication. Instead of using back pointers to the shell, a delegation pattern is used by all components that want to communicate with one another. Because of this, the shell implements the delegate interface for all these components.

All shell methods accessed by the embedder may only be called on the platform task runner. In case the embedder wants to directly access a shell subcomponent, it is the embedder's responsibility to acquire a weak pointer to that component and post a task to the task runner used by the component to access its methods. The shell must also be destroyed on the platform task runner.

There is no explicit API to bootstrap and shutdown the Dart VM. The first instance of the shell in the process bootstraps the Dart VM and the destruction of the last shell instance destroys the same. Since different shells may be created and destroyed on different threads. VM bootstrap may happen on one thread but its collection on another. This behavior is thread safe.

Definition at line 112 of file shell.h.

Member Typedef Documentation

◆ CreateCallback

template<class T >
using flutter::Shell::CreateCallback = std::function<std::unique_ptr<T>(Shell&)>

Definition at line 120 of file shell.h.

◆ EngineCreateCallback

typedef std::function<std::unique_ptr<Engine>( Engine::Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm, fml::RefPtr<const DartSnapshot> isolate_snapshot, TaskRunners task_runners, const PlatformData& platform_data, Settings settings, std::unique_ptr<Animator> animator, fml::WeakPtr<IOManager> io_manager, fml::RefPtr<SkiaUnrefQueue> unref_queue, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, std::shared_ptr<VolatilePathTracker> volatile_path_tracker, const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch, impeller::RuntimeStageBackend runtime_stage_type)> flutter::Shell::EngineCreateCallback

Definition at line 136 of file shell.h.

Constructor & Destructor Documentation

◆ ~Shell()

flutter::Shell::~Shell ( )

Destroys the shell. This is a synchronous operation and synchronous barrier blocks are introduced on the various threads to ensure shutdown of all shell sub-components before this method returns.

Definition at line 529 of file shell.cc.

529 {
530#if !SLIMPELLER
532 task_runners_.GetIOTaskRunner());
533#endif // !SLIMPELLER
534
535 vm_->GetServiceProtocol()->RemoveHandler(this);
536
537 fml::AutoResetWaitableEvent platiso_latch, ui_latch, gpu_latch,
538 platform_latch, io_latch;
539
541 task_runners_.GetPlatformTaskRunner(),
542 fml::MakeCopyable([this, &platiso_latch]() mutable {
543 engine_->ShutdownPlatformIsolates();
544 platiso_latch.Signal();
545 }));
546 platiso_latch.Wait();
547
549 task_runners_.GetUITaskRunner(),
550 fml::MakeCopyable([this, &ui_latch]() mutable {
551 engine_.reset();
552 ui_latch.Signal();
553 }));
554 ui_latch.Wait();
555
557 task_runners_.GetRasterTaskRunner(),
559 [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable {
560 rasterizer.reset();
561 this->weak_factory_gpu_.reset();
562 gpu_latch.Signal();
563 }));
564 gpu_latch.Wait();
565
567 task_runners_.GetIOTaskRunner(),
568 fml::MakeCopyable([io_manager = std::move(io_manager_),
569 platform_view = platform_view_.get(),
570 &io_latch]() mutable {
571 io_manager.reset();
572 if (platform_view) {
573 platform_view->ReleaseResourceContext();
574 }
575 io_latch.Signal();
576 }));
577
578 io_latch.Wait();
579
580 // The platform view must go last because it may be holding onto platform side
581 // counterparts to resources owned by subsystems running on other threads. For
582 // example, the NSOpenGLContext on the Mac.
584 task_runners_.GetPlatformTaskRunner(),
585 fml::MakeCopyable([platform_view = std::move(platform_view_),
586 &platform_latch]() mutable {
587 platform_view.reset();
588 platform_latch.Signal();
589 }));
590 platform_latch.Wait();
591}
std::unique_ptr< flutter::PlatformViewIOS > platform_view
std::shared_ptr< ServiceProtocol > GetServiceProtocol() const
The service protocol instance associated with this running Dart VM instance. This object manages nati...
Definition: dart_vm.cc:544
void RemoveWorkerTaskRunner(const fml::RefPtr< fml::TaskRunner > &task_runner)
static PersistentCache * GetCacheForProcess()
fml::RefPtr< fml::TaskRunner > GetRasterTaskRunner() const
Definition: task_runners.cc:42
fml::RefPtr< fml::TaskRunner > GetUITaskRunner() const
Definition: task_runners.cc:34
fml::RefPtr< fml::TaskRunner > GetIOTaskRunner() const
Definition: task_runners.cc:38
fml::RefPtr< fml::TaskRunner > GetPlatformTaskRunner() const
Definition: task_runners.cc:30
static void RunNowOrPostTask(const fml::RefPtr< fml::TaskRunner > &runner, const fml::closure &task)
Definition: task_runner.cc:55
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition: make_copyable.h:57

Member Function Documentation

◆ Create()

std::unique_ptr< Shell > flutter::Shell::Create ( const PlatformData platform_data,
const TaskRunners task_runners,
Settings  settings,
const CreateCallback< PlatformView > &  on_create_platform_view,
const CreateCallback< Rasterizer > &  on_create_rasterizer,
bool  is_gpu_disabled = false 
)
static

Creates a shell instance using the provided settings. The callbacks to create the various shell subcomponents will be called on the appropriate threads before this method returns. If this is the first instance of a shell in the process, this call also bootstraps the Dart VM.

Note
The root isolate which will run this Shell's Dart code takes its instructions from the passed in settings. This allows embedders to host multiple Shells with different Dart code.
Parameters
[in]task_runnersThe task runners
[in]settingsThe settings
[in]on_create_platform_viewThe callback that must return a platform view. This will be called on the platform task runner before this method returns.
[in]on_create_rasterizerThat callback that must provide a valid rasterizer. This will be called on the render task runner before this method returns.
[in]is_gpu_disabledThe default value for the switch that turns off the GPU.
Returns
A full initialized shell if the settings and callbacks are valid. The root isolate has been created but not yet launched. It may be launched by obtaining the engine weak pointer and posting a task onto the UI task runner with a valid run configuration to run the isolate. The embedder must always check the validity of the shell (using the IsSetup call) immediately after getting a pointer to it.

Definition at line 169 of file shell.cc.

175 {
176 // This must come first as it initializes tracing.
177 PerformInitializationTasks(settings);
178
179 TRACE_EVENT0("flutter", "Shell::Create");
180
181 auto [vm, isolate_snapshot] = InferVmInitDataFromSettings(settings);
182 auto resource_cache_limit_calculator =
183 std::make_shared<ResourceCacheLimitCalculator>(
184 settings.resource_cache_max_bytes_threshold);
185
186 return CreateWithSnapshot(platform_data, //
187 task_runners, //
188 /*parent_thread_merger=*/nullptr, //
189 /*parent_io_manager=*/nullptr, //
190 resource_cache_limit_calculator, //
191 settings, //
192 std::move(vm), //
193 std::move(isolate_snapshot), //
194 on_create_platform_view, //
195 on_create_rasterizer, //
196 CreateEngine, is_gpu_disabled);
197}
static std::pair< DartVMRef, fml::RefPtr< const DartSnapshot > > InferVmInitDataFromSettings(Settings &settings)
Definition: shell.cc:153
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:131

◆ EngineHasLivePorts()

bool flutter::Shell::EngineHasLivePorts ( ) const

Used by embedders to check if the Engine is running and has any live ports remaining. For example, the Flutter tester uses this method to check whether it should continue to wait for a running test or not.

Returns
Returns if the shell has an engine and the engine has any live Dart ports.

Definition at line 717 of file shell.cc.

717 {
718 FML_DCHECK(is_set_up_);
720
721 if (!weak_engine_) {
722 return false;
723 }
724
725 return weak_engine_->UIIsolateHasLivePorts();
726}
virtual bool RunsTasksOnCurrentThread()
Definition: task_runner.cc:43
#define FML_DCHECK(condition)
Definition: logging.h:103

◆ GetConcurrentWorkerTaskRunner()

const std::shared_ptr< fml::ConcurrentTaskRunner > flutter::Shell::GetConcurrentWorkerTaskRunner ( ) const

Definition at line 2334 of file shell.cc.

2334 {
2335 FML_DCHECK(vm_);
2336 if (!vm_) {
2337 return nullptr;
2338 }
2339 return vm_->GetConcurrentWorkerTaskRunner();
2340}
std::shared_ptr< fml::ConcurrentTaskRunner > GetConcurrentWorkerTaskRunner() const
The task runner whose tasks may be executed concurrently on a pool of worker threads....
Definition: dart_vm.cc:553

◆ GetDartVM()

DartVM * flutter::Shell::GetDartVM ( )

Get a pointer to the Dart VM used by this running shell instance.

Returns
The Dart VM pointer.

Definition at line 834 of file shell.cc.

834 {
835 return &vm_;
836}

◆ GetEngine()

fml::WeakPtr< Engine > flutter::Shell::GetEngine ( )

Engines may only be accessed on the UI thread. This method is deprecated, and implementers should instead use other API available on the Shell or the PlatformView.

Returns
A weak pointer to the engine.

Definition at line 819 of file shell.cc.

819 {
820 FML_DCHECK(is_set_up_);
821 return weak_engine_;
822}

◆ GetIOManager()

fml::WeakPtr< ShellIOManager > flutter::Shell::GetIOManager ( )

The IO Manager may only be accessed on the IO task runner.

Returns
A weak pointer to the IO manager.

Definition at line 829 of file shell.cc.

829 {
830 FML_DCHECK(is_set_up_);
831 return io_manager_->GetWeakPtr();
832}

◆ GetIsGpuDisabledSyncSwitch()

std::shared_ptr< const fml::SyncSwitch > flutter::Shell::GetIsGpuDisabledSyncSwitch ( ) const
overridevirtual

Accessor for the disable GPU SyncSwitch.

Implements flutter::Rasterizer::Delegate.

Definition at line 2267 of file shell.cc.

2268 {
2269 return is_gpu_disabled_sync_switch_;
2270}

◆ GetMainDisplayRefreshRate()

double flutter::Shell::GetMainDisplayRefreshRate ( )

Queries the DisplayManager for the main display refresh rate.

Definition at line 1871 of file shell.cc.

1871 {
1872 return display_manager_->GetMainDisplayRefreshRate();
1873}

◆ GetParentRasterThreadMerger()

const fml::RefPtr< fml::RasterThreadMerger > flutter::Shell::GetParentRasterThreadMerger ( ) const
overridevirtual

Getting the raster thread merger from parent shell, it can be a null RefPtr when it's a root Shell or the embedder_->SupportsDynamicThreadMerging() returns false.

Returns
The raster thread merger used by the parent shell.

Implements flutter::Rasterizer::Delegate.

Definition at line 809 of file shell.cc.

810 {
811 return parent_raster_thread_merger_;
812}

◆ GetPlatformMessageHandler()

const std::shared_ptr< PlatformMessageHandler > & flutter::Shell::GetPlatformMessageHandler ( ) const
overridevirtual

Returns the delegate object that handles PlatformMessage's from Flutter to the host platform (and its responses).

Implements flutter::Engine::Delegate.

Definition at line 2322 of file shell.cc.

2322 {
2323 return platform_message_handler_;
2324}

◆ GetPlatformView()

fml::WeakPtr< PlatformView > flutter::Shell::GetPlatformView ( )

Platform views may only be accessed on the platform task runner.

Returns
A weak pointer to the platform view.

Definition at line 824 of file shell.cc.

824 {
825 FML_DCHECK(is_set_up_);
826 return weak_platform_view_;
827}

◆ GetRasterizer()

fml::TaskRunnerAffineWeakPtr< Rasterizer > flutter::Shell::GetRasterizer ( ) const

Rasterizers may only be accessed on the raster task runner.

Returns
A weak pointer to the rasterizer.

Definition at line 814 of file shell.cc.

814 {
815 FML_DCHECK(is_set_up_);
816 return weak_rasterizer_;
817}

◆ GetSettings()

const Settings & flutter::Shell::GetSettings ( ) const
overridevirtual
Returns
The settings used to launch this shell.

Implements flutter::Rasterizer::Delegate.

Definition at line 801 of file shell.cc.

801 {
802 return settings_;
803}

◆ GetTaskRunners()

const TaskRunners & flutter::Shell::GetTaskRunners ( ) const
overridevirtual

If callers wish to interact directly with any shell subcomponents, they must (on the platform thread) obtain a task runner that the component is designed to run on and a weak pointer to that component. They may then post a task to that task runner, do the validity check on that task runner before performing any operation on that component. This accessor allows callers to access the task runners for this shell.

Returns
The task runners current in use by the shell.

Implements flutter::Rasterizer::Delegate.

Definition at line 805 of file shell.cc.

805 {
806 return task_runners_;
807}

◆ GetUIIsolateLastError()

std::optional< DartErrorCode > flutter::Shell::GetUIIsolateLastError ( ) const

Used by embedders to get the last error from the Dart UI Isolate, if one exists.

Returns
Returns the last error code from the UI Isolate.

Definition at line 697 of file shell.cc.

697 {
698 FML_DCHECK(is_set_up_);
700
701 if (!weak_engine_) {
702 return std::nullopt;
703 }
704 switch (weak_engine_->GetUIIsolateLastError()) {
711 case tonic::kNoError:
713 }
715}
@ CompilationError
The Dart error code for a compilation error.
@ ApiError
The Dart error code for an API error.
@ NoError
No error has occurred.
@ UnknownError
The Dart error code for an unknown error.
@ kApiErrorType
Definition: dart_error.h:70
@ kCompilationErrorType
Definition: dart_error.h:71
@ kUnknownErrorType
Definition: dart_error.h:69
@ kNoError
Definition: dart_error.h:68

◆ GetVsyncWaiter()

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

Definition at line 2326 of file shell.cc.

2326 {
2327 if (!engine_) {
2328 return {};
2329 }
2330 return engine_->GetVsyncWaiter();
2331}

◆ InferVmInitDataFromSettings()

std::pair< DartVMRef, fml::RefPtr< const DartSnapshot > > flutter::Shell::InferVmInitDataFromSettings ( Settings settings)
static

Definition at line 153 of file shell.cc.

153 {
154 // Always use the `vm_snapshot` and `isolate_snapshot` provided by the
155 // settings to launch the VM. If the VM is already running, the snapshot
156 // arguments are ignored.
159 auto vm = DartVMRef::Create(settings, vm_snapshot, isolate_snapshot);
160
161 // If the settings did not specify an `isolate_snapshot`, fall back to the
162 // one the VM was launched with.
163 if (!isolate_snapshot) {
164 isolate_snapshot = vm->GetVMData()->GetIsolateSnapshot();
165 }
166 return {std::move(vm), isolate_snapshot};
167}
static fml::RefPtr< const DartSnapshot > VMSnapshotFromSettings(const Settings &settings)
From the fields present in the given settings object, infer the core snapshot.
static fml::RefPtr< const DartSnapshot > IsolateSnapshotFromSettings(const Settings &settings)
From the fields present in the given settings object, infer the isolate snapshot.
static DartVMRef Create(const Settings &settings, fml::RefPtr< const DartSnapshot > vm_snapshot=nullptr, fml::RefPtr< const DartSnapshot > isolate_snapshot=nullptr)

◆ IsSetup()

bool flutter::Shell::IsSetup ( ) const

Used by embedders to check if all shell subcomponents are initialized. It is the embedder's responsibility to make this call before accessing any other shell method. A shell that is not set up must be discarded and another one created with updated settings.

Returns
Returns if the shell has been set up. Once set up, this does not change for the life-cycle of the shell.

Definition at line 728 of file shell.cc.

728 {
729 return is_set_up_;
730}

◆ NotifyLowMemoryWarning()

void flutter::Shell::NotifyLowMemoryWarning ( ) const

Used by embedders to notify that there is a low memory warning. The shell will attempt to purge caches. Current, only the rasterizer cache is purged.

Definition at line 637 of file shell.cc.

637 {
638 auto trace_id = fml::tracing::TraceNonce();
639 TRACE_EVENT_ASYNC_BEGIN0("flutter", "Shell::NotifyLowMemoryWarning",
640 trace_id);
641 // This does not require a current isolate but does require a running VM.
642 // Since a valid shell will not be returned to the embedder without a valid
643 // DartVMRef, we can be certain that this is a safe spot to assume a VM is
644 // running.
646
647 task_runners_.GetRasterTaskRunner()->PostTask(
648 [rasterizer = rasterizer_->GetWeakPtr(), trace_id = trace_id]() {
649 if (rasterizer) {
650 rasterizer->NotifyLowMemoryWarning();
651 }
652 TRACE_EVENT_ASYNC_END0("flutter", "Shell::NotifyLowMemoryWarning",
653 trace_id);
654 });
655 // The IO Manager uses resource cache limits of 0, so it is not necessary
656 // to purge them.
657}
virtual void PostTask(const fml::closure &task) override
Definition: task_runner.cc:24
DART_EXPORT void Dart_NotifyLowMemory(void)
size_t TraceNonce()
Definition: trace_event.cc:385
#define TRACE_EVENT_ASYNC_END0(category_group, name, id)
Definition: trace_event.h:161
#define TRACE_EVENT_ASYNC_BEGIN0(category_group, name, id)
Definition: trace_event.h:157

◆ OnDisplayUpdates()

void flutter::Shell::OnDisplayUpdates ( std::vector< std::unique_ptr< Display > >  displays)

Notifies the display manager of the updates.

Definition at line 2297 of file shell.cc.

2297 {
2298 FML_DCHECK(is_set_up_);
2300
2301 std::vector<DisplayData> display_data;
2302 display_data.reserve(displays.size());
2303 for (const auto& display : displays) {
2304 display_data.push_back(display->GetDisplayData());
2305 }
2306 task_runners_.GetUITaskRunner()->PostTask(
2307 [engine = engine_->GetWeakPtr(),
2308 display_data = std::move(display_data)]() {
2309 if (engine) {
2310 engine->SetDisplays(display_data);
2311 }
2312 });
2313
2314 display_manager_->HandleDisplayUpdates(std::move(displays));
2315}
FlutterEngine engine
Definition: main.cc:68

◆ RegisterImageDecoder()

void flutter::Shell::RegisterImageDecoder ( ImageGeneratorFactory  factory,
int32_t  priority 
)

Install a new factory that can match against and decode image data.

Parameters
[in]factoryCallback that produces ImageGenerators for compatible input data.
[in]priorityThe priority used to determine the order in which factories are tried. Higher values mean higher priority. The built-in Skia decoders are installed at priority 0, and so a priority > 0 takes precedent over the builtin decoders. When multiple decoders are added with the same priority, those which are added earlier take precedent.
See also
CreateCompatibleGenerator

Definition at line 1875 of file shell.cc.

1876 {
1878 FML_DCHECK(is_set_up_);
1879
1881 task_runners_.GetUITaskRunner(),
1882 [engine = engine_->GetWeakPtr(), factory = std::move(factory),
1883 priority]() {
1884 if (engine) {
1885 engine->GetImageGeneratorRegistry()->AddFactory(factory, priority);
1886 }
1887 });
1888}

◆ ReloadSystemFonts()

bool flutter::Shell::ReloadSystemFonts ( )

Used by embedders to reload the system fonts in FontCollection. It also clears the cached font families and send system channel message to framework to rebuild affected widgets.

Returns
Returns if shell reloads system fonts successfully.

Definition at line 2252 of file shell.cc.

2252 {
2253 FML_DCHECK(is_set_up_);
2255
2256 if (!engine_) {
2257 return false;
2258 }
2259 engine_->SetupDefaultFontManager();
2260 engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache();
2261 // After system fonts are reloaded, we send a system channel message
2262 // to notify flutter framework.
2263 SendFontChangeNotification();
2264 return true;
2265}

◆ RunEngine() [1/2]

void flutter::Shell::RunEngine ( RunConfiguration  run_configuration)

Starts an isolate for the given RunConfiguration.

Definition at line 659 of file shell.cc.

659 {
660 RunEngine(std::move(run_configuration), nullptr);
661}
void RunEngine(RunConfiguration run_configuration)
Starts an isolate for the given RunConfiguration.
Definition: shell.cc:659

◆ RunEngine() [2/2]

void flutter::Shell::RunEngine ( RunConfiguration  run_configuration,
const std::function< void(Engine::RunStatus)> &  result_callback 
)

Starts an isolate for the given RunConfiguration. The result_callback will be called with the status of the operation.

Definition at line 663 of file shell.cc.

665 {
666 auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(),
667 result_callback](Engine::RunStatus run_result) {
668 if (!result_callback) {
669 return;
670 }
671 platform_runner->PostTask(
672 [result_callback, run_result]() { result_callback(run_result); });
673 };
674 FML_DCHECK(is_set_up_);
676
678 task_runners_.GetUITaskRunner(),
680 [run_configuration = std::move(run_configuration),
681 weak_engine = weak_engine_, result]() mutable {
682 if (!weak_engine) {
683 FML_LOG(ERROR)
684 << "Could not launch engine with configuration - no engine.";
685 result(Engine::RunStatus::Failure);
686 return;
687 }
688 auto run_result = weak_engine->Run(std::move(run_configuration));
690 FML_LOG(ERROR) << "Could not launch engine with configuration.";
691 }
692
693 result(run_result);
694 }));
695}
RunStatus
Indicates the result of the call to Engine::Run.
Definition: engine.h:78
if(end==-1)
GAsyncResult * result
#define FML_LOG(severity)
Definition: logging.h:82
#define ERROR(message)
Definition: elf_loader.cc:260

◆ Screenshot()

Rasterizer::Screenshot flutter::Shell::Screenshot ( Rasterizer::ScreenshotType  type,
bool  base64_encode 
)

Captures a screenshot and optionally Base64 encodes the data of the last layer tree rendered by the rasterizer in this shell.

Parameters
[in]typeThe type of screenshot to capture.
[in]base64_encodeIf the screenshot data should be base64 encoded.
Returns
The screenshot result.

Definition at line 2189 of file shell.cc.

2191 {
2192 if (settings_.enable_impeller) {
2193 switch (screenshot_type) {
2195 FML_LOG(ERROR)
2196 << "Impeller backend cannot produce ScreenshotType::SkiaPicture.";
2197 return {};
2201 break;
2202 }
2203 }
2204 TRACE_EVENT0("flutter", "Shell::Screenshot");
2206 Rasterizer::Screenshot screenshot;
2208 task_runners_.GetRasterTaskRunner(), [&latch, //
2209 rasterizer = GetRasterizer(), //
2210 &screenshot, //
2211 screenshot_type, //
2212 base64_encode //
2213 ]() {
2214 if (rasterizer) {
2215 screenshot = rasterizer->ScreenshotLastLayerTree(screenshot_type,
2216 base64_encode);
2217 }
2218 latch.Signal();
2219 });
2220 latch.Wait();
2221 return screenshot;
2222}
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the raster task runner.
Definition: shell.cc:814
bool enable_impeller
Definition: settings.h:229

◆ SetGpuAvailability()

void flutter::Shell::SetGpuAvailability ( GpuAvailability  availability)

Marks the GPU as available or unavailable.

Definition at line 2272 of file shell.cc.

2272 {
2274 switch (availability) {
2276 is_gpu_disabled_sync_switch_->SetSwitch(false);
2277 return;
2281 task_runners_.GetIOTaskRunner(),
2282 [io_manager = io_manager_.get(), &latch]() {
2283 io_manager->GetSkiaUnrefQueue()->Drain();
2284 latch.Signal();
2285 });
2286 latch.Wait();
2287 }
2288 // FALLTHROUGH
2290 is_gpu_disabled_sync_switch_->SetSwitch(true);
2291 return;
2292 default:
2293 FML_DCHECK(false);
2294 }
2295}
@ kAvailable
Indicates that GPU operations should be permitted.

◆ Spawn()

std::unique_ptr< Shell > flutter::Shell::Spawn ( RunConfiguration  run_configuration,
const std::string &  initial_route,
const CreateCallback< PlatformView > &  on_create_platform_view,
const CreateCallback< Rasterizer > &  on_create_rasterizer 
) const

Creates one Shell from another Shell where the created Shell takes the opportunity to share any internal components it can. This results is a Shell that has a smaller startup time cost and a smaller memory footprint than an Shell created with the Create function.

The new Shell is returned in a running state so RunEngine shouldn't be called again on the Shell. Once running, the second Shell is mostly independent from the original Shell and the original Shell doesn't need to keep running for the spawned Shell to keep functioning.

Parameters
[in]run_configurationA RunConfiguration used to run the Isolate associated with this new Shell. It doesn't have to be the same configuration as the current Shell but it needs to be in the same snapshot or AOT.
See also
http://flutter.dev/go/multiple-engines

Definition at line 593 of file shell.cc.

597 {
598 FML_DCHECK(task_runners_.IsValid());
599 // It's safe to store this value since it is set on the platform thread.
600 bool is_gpu_disabled = false;
603 .SetIfFalse([&is_gpu_disabled] { is_gpu_disabled = false; })
604 .SetIfTrue([&is_gpu_disabled] { is_gpu_disabled = true; }));
605 std::unique_ptr<Shell> result = CreateWithSnapshot(
606 PlatformData{}, task_runners_, rasterizer_->GetRasterThreadMerger(),
607 io_manager_, resource_cache_limit_calculator_, GetSettings(), vm_,
608 vm_->GetVMData()->GetIsolateSnapshot(), on_create_platform_view,
609 on_create_rasterizer,
610 [engine = this->engine_.get(), initial_route](
611 Engine::Delegate& delegate,
612 const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm,
613 const fml::RefPtr<const DartSnapshot>& isolate_snapshot,
614 const TaskRunners& task_runners, const PlatformData& platform_data,
615 const Settings& settings, std::unique_ptr<Animator> animator,
616 const fml::WeakPtr<IOManager>& io_manager,
617 const fml::RefPtr<SkiaUnrefQueue>& unref_queue,
619 const std::shared_ptr<VolatilePathTracker>& volatile_path_tracker,
620 const std::shared_ptr<fml::SyncSwitch>& is_gpu_disabled_sync_switch,
621 impeller::RuntimeStageBackend runtime_stage_backend) {
622 return engine->Spawn(
623 /*delegate=*/delegate,
624 /*dispatcher_maker=*/dispatcher_maker,
625 /*settings=*/settings,
626 /*animator=*/std::move(animator),
627 /*initial_route=*/initial_route,
628 /*io_manager=*/io_manager,
629 /*snapshot_delegate=*/std::move(snapshot_delegate),
630 /*gpu_disabled_switch=*/is_gpu_disabled_sync_switch);
631 },
632 is_gpu_disabled);
633 result->RunEngine(std::move(run_configuration));
634 return result;
635}
std::shared_ptr< const DartVMData > GetVMData() const
The VM and isolate snapshots used by this running Dart VM instance.
Definition: dart_vm.cc:536
const Settings & GetSettings() const override
Definition: shell.cc:801
std::shared_ptr< const fml::SyncSwitch > GetIsGpuDisabledSyncSwitch() const override
Accessor for the disable GPU SyncSwitch.
Definition: shell.cc:2267
bool IsValid() const
Definition: task_runners.cc:46
std::function< std::unique_ptr< PointerDataDispatcher >(PointerDataDispatcher::Delegate &)> PointerDataDispatcherMaker
Signature for constructing PointerDataDispatcher.
Represents the 2 code paths available when calling |SyncSwitch::Execute|.
Definition: sync_switch.h:35

◆ WaitForFirstFrame()

fml::Status flutter::Shell::WaitForFirstFrame ( fml::TimeDelta  timeout)

Pauses the calling thread until the first frame is presented.

Parameters
[in]timeoutThe duration to wait before timing out. If this duration would cause an overflow when added to std::chrono::steady_clock::now(), this method will wait indefinitely for the first frame.
Returns
'kOk' when the first frame has been presented before the timeout successfully, 'kFailedPrecondition' if called from the GPU or UI thread, 'kDeadlineExceeded' if there is a timeout.

Definition at line 2224 of file shell.cc.

2224 {
2225 FML_DCHECK(is_set_up_);
2226 if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() ||
2227 task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) {
2229 "WaitForFirstFrame called from thread that can't wait "
2230 "because it is responsible for generating the frame.");
2231 }
2232
2233 // Check for overflow.
2234 auto now = std::chrono::steady_clock::now();
2235 auto max_duration = std::chrono::steady_clock::time_point::max() - now;
2236 auto desired_duration = std::chrono::milliseconds(timeout.ToMilliseconds());
2237 auto duration =
2238 now + (desired_duration > max_duration ? max_duration : desired_duration);
2239
2240 std::unique_lock<std::mutex> lock(waiting_for_first_frame_mutex_);
2241 bool success = waiting_for_first_frame_condition_.wait_until(
2242 lock, duration, [&waiting_for_first_frame = waiting_for_first_frame_] {
2243 return !waiting_for_first_frame.load();
2244 });
2245 if (success) {
2246 return fml::Status();
2247 } else {
2249 }
2250}
double duration
Definition: examples.cpp:30
static float max(float r, float g, float b)
Definition: hsl.cpp:49
def timeout(deadline, cmd)
Task::Status Status
Definition: TaskList.cpp:15

Friends And Related Function Documentation

◆ testing::ShellTest

friend class testing::ShellTest
friend

Definition at line 792 of file shell.h.


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