Flutter Engine Uber Docs
Docs for the entire Flutter Engine repo.
 
Loading...
Searching...
No Matches
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, const std::shared_ptr< fml::SyncSwitch > &gpu_disabled_switch, const std::shared_future< impeller::RuntimeStageBackend > &runtime_stage_backend)> 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.
 
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.
 
void RunEngine (RunConfiguration run_configuration)
 Starts an isolate for the given RunConfiguration.
 
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.
 
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.
 
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.
 
fml::TaskRunnerAffineWeakPtr< RasterizerGetRasterizer () const
 Rasterizers may only be accessed on the raster task runner.
 
fml::TaskRunnerAffineWeakPtr< 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.
 
fml::WeakPtr< PlatformViewGetPlatformView ()
 Platform views may only be accessed on the platform task runner.
 
fml::WeakPtr< ShellIOManagerGetIOManager ()
 The IO Manager may only be accessed on the IO task runner.
 
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.
 
void FlushMicrotaskQueue () const
 Used by embedders to flush the microtask queue. Required when running with merged platform and UI threads, in which case the embedder is responsible for flushing the microtask queue.
 
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.
 
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.
 
fml::Status WaitForFirstFrame (fml::TimeDelta timeout)
 Pauses the calling thread until the first frame is presented.
 
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.
 
std::optional< DartErrorCodeGetUIIsolateLastError () const
 Used by embedders to get the last error from the Dart UI Isolate, if one exists.
 
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.
 
bool EngineHasPendingMicrotasks () const
 Used by embedders to check if the Engine is running and has any microtasks that have been queued but have not yet run. The Flutter tester uses this as a signal that a test is still running.
 
std::shared_ptr< const fml::SyncSwitchGetIsGpuDisabledSyncSwitch () const override
 Accessor for the disable GPU SyncSwitch.
 
void SetGpuAvailability (GpuAvailability availability)
 Marks the GPU as available or unavailable.
 
DartVMGetDartVM ()
 Get a pointer to the Dart VM used by this running shell instance.
 
void OnDisplayUpdates (std::vector< std::unique_ptr< Display > > displays)
 Notifies the display manager of the updates.
 
double GetMainDisplayRefreshRate ()
 Queries the DisplayManager for the main display refresh rate.
 
void RegisterImageDecoder (ImageGeneratorFactory factory, int32_t priority)
 Install a new factory that can match against and decode image data.
 
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).
 
const std::weak_ptr< VsyncWaiterGetVsyncWaiter () const
 
const std::shared_ptr< fml::ConcurrentTaskRunnerGetConcurrentWorkerTaskRunner () const
 
- Public Member Functions inherited from flutter::PlatformView::Delegate
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.
 

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.
 
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 113 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 121 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, const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch, const std::shared_future<impeller::RuntimeStageBackend>& runtime_stage_backend)> flutter::Shell::EngineCreateCallback

Definition at line 137 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 596 of file shell.cc.

600 {task_runners_.GetIOTaskRunner(),
601 std::bind(&Shell::OnServiceProtocolGetPipelineUsage, this,
602 std::placeholders::_1, std::placeholders::_2)};
603}
604
606#if !SLIMPELLER
608 task_runners_.GetIOTaskRunner());
609#endif // !SLIMPELLER
610
611 vm_->GetServiceProtocol()->RemoveHandler(this);
612
613 fml::AutoResetWaitableEvent platiso_latch, ui_latch, gpu_latch,
614 platform_latch, io_latch;
615
617 task_runners_.GetPlatformTaskRunner(),
618 fml::MakeCopyable([this, &platiso_latch]() mutable {
619 engine_->ShutdownPlatformIsolates();
620 platiso_latch.Signal();
621 }));
622 platiso_latch.Wait();
623
625 task_runners_.GetUITaskRunner(),
626 fml::MakeCopyable([this, &ui_latch]() mutable {
627 engine_.reset();
628 ui_latch.Signal();
629 }));
630 ui_latch.Wait();
631
633 task_runners_.GetRasterTaskRunner(),
635 [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable {
636 rasterizer.reset();
637 this->weak_factory_gpu_.reset();
638 gpu_latch.Signal();
639 }));
640 gpu_latch.Wait();
641
643 task_runners_.GetIOTaskRunner(),
644 fml::MakeCopyable([io_manager = std::move(io_manager_),
645 platform_view = platform_view_.get(),
646 &io_latch]() mutable {
647 std::weak_ptr<ShellIOManager> weak_io_manager(io_manager);
648 io_manager.reset();
649
650 // If the IO manager is not being used by any other spawned shells,
651 // then detach the resource context from the IO thread.
652 if (platform_view && weak_io_manager.expired()) {
653 platform_view->ReleaseResourceContext();
654 }
655 io_latch.Signal();
656 }));
657
658 io_latch.Wait();
659
660 // The platform view must go last because it may be holding onto platform side
661 // counterparts to resources owned by subsystems running on other threads. For
662 // example, the NSOpenGLContext on the Mac.
664 task_runners_.GetPlatformTaskRunner(),
665 fml::MakeCopyable([platform_view = std::move(platform_view_),
666 &platform_latch]() mutable {
667 platform_view.reset();
668 platform_latch.Signal();
669 }));
670 platform_latch.Wait();
671
672 if (settings_.merged_platform_ui_thread ==
674 // Move the UI task runner back to its original thread to enable shutdown of
675 // that thread.
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:530
void RemoveWorkerTaskRunner(const fml::RefPtr< fml::TaskRunner > &task_runner)
static PersistentCache * GetCacheForProcess()
~Shell()
Destroys the shell. This is a synchronous operation and synchronous barrier blocks are introduced on ...
Definition shell.cc:596
fml::RefPtr< fml::TaskRunner > GetRasterTaskRunner() const
fml::RefPtr< fml::TaskRunner > GetUITaskRunner() const
fml::RefPtr< fml::TaskRunner > GetIOTaskRunner() const
fml::RefPtr< fml::TaskRunner > GetPlatformTaskRunner() const
static void RunNowOrPostTask(const fml::RefPtr< fml::TaskRunner > &runner, const fml::closure &task)
internal::CopyableLambda< T > MakeCopyable(T lambda)
MergedPlatformUIThread merged_platform_ui_thread
Definition settings.h:379

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 222 of file shell.cc.

228 {
229 // This must come first as it initializes tracing.
230 PerformInitializationTasks(settings);
231
232 TRACE_EVENT0("flutter", "Shell::Create");
233
234 auto [vm, isolate_snapshot] = InferVmInitDataFromSettings(settings);
235 auto resource_cache_limit_calculator =
236 std::make_shared<ResourceCacheLimitCalculator>(
237 settings.resource_cache_max_bytes_threshold);
238
239 return CreateWithSnapshot(platform_data, //
240 task_runners, //
241 /*parent_thread_merger=*/nullptr, //
242 /*parent_io_manager=*/nullptr, //
243 resource_cache_limit_calculator, //
244 settings, //
245 std::move(vm), //
246 std::move(isolate_snapshot), //
247 on_create_platform_view, //
248 on_create_rasterizer, //
249 CreateEngine, is_gpu_disabled);
250}
static std::pair< DartVMRef, fml::RefPtr< const DartSnapshot > > InferVmInitDataFromSettings(Settings &settings)
Definition shell.cc:206
#define TRACE_EVENT0(category_group, name)

References InferVmInitDataFromSettings(), flutter::Settings::resource_cache_max_bytes_threshold, and TRACE_EVENT0.

Referenced by flutter::AndroidShellHolder::AndroidShellHolder(), flutter::EmbedderEngine::LaunchShell(), flutter::RunTester(), flutter::StartupAndShutdownShell(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ 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 817 of file shell.cc.

818 :
820 case tonic::kNoError:
822 }
824}
825
826bool Shell::EngineHasLivePorts() const {
bool EngineHasLivePorts() const
Used by embedders to check if the Engine is running and has any live ports remaining....
Definition shell.cc:817
@ NoError
No error has occurred.
@ UnknownError
The Dart error code for an unknown error.
@ kNoError
Definition dart_error.h:68

Referenced by flutter::ScriptCompletionTaskObserver::DidProcessTask().

◆ EngineHasPendingMicrotasks()

bool flutter::Shell::EngineHasPendingMicrotasks ( ) const

Used by embedders to check if the Engine is running and has any microtasks that have been queued but have not yet run. The Flutter tester uses this as a signal that a test is still running.

Returns
Returns if the shell has an engine and the engine has pending microtasks.

Definition at line 828 of file shell.cc.

830 {
831 return false;
832 }
833
834 return weak_engine_->UIIsolateHasLivePorts();
835}
836
bool EngineHasPendingMicrotasks() const
Used by embedders to check if the Engine is running and has any microtasks that have been queued but ...
Definition shell.cc:828

Referenced by flutter::ScriptCompletionTaskObserver::DidProcessTask().

◆ FlushMicrotaskQueue()

void flutter::Shell::FlushMicrotaskQueue ( ) const

Used by embedders to flush the microtask queue. Required when running with merged platform and UI threads, in which case the embedder is responsible for flushing the microtask queue.

Definition at line 753 of file shell.cc.

◆ GetConcurrentWorkerTaskRunner()

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

Definition at line 2467 of file shell.cc.

2468 {
2469 if (!engine_) {
2470 return {};
2471 }
2472 return engine_->GetVsyncWaiter();
2473}

◆ 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 945 of file shell.cc.

Referenced by flutter::testing::TEST_F().

◆ GetEngine()

fml::TaskRunnerAffineWeakPtr< 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 930 of file shell.cc.

930 {
931 return parent_raster_thread_merger_;
932}
933

◆ 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 940 of file shell.cc.

◆ 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 2400 of file shell.cc.

Referenced by flutter::testing::ShellTestPlatformViewBuilder::operator()(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ GetMainDisplayRefreshRate()

double flutter::Shell::GetMainDisplayRefreshRate ( )

Queries the DisplayManager for the main display refresh rate.

Definition at line 2047 of file shell.cc.

2047 {
2049 response->SetObject();
virtual bool RunsTasksOnCurrentThread()
#define FML_DCHECK(condition)
Definition logging.h:122

References FML_DCHECK, flutter::TaskRunners::GetUITaskRunner(), and fml::TaskRunner::RunsTasksOnCurrentThread().

Referenced by flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ 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 920 of file shell.cc.

921 {
922 return settings_;
923}

◆ 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 2455 of file shell.cc.

◆ 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 935 of file shell.cc.

Referenced by flutter::ConfigureShell(), flutter::testing::ShellTest::DispatchPointerData(), FlutterEngineSetNextFrameCallback(), flutter::RunTester(), flutter::testing::TEST_F(), and flutter::testing::ShellTest::VSyncFlush().

◆ 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 925 of file shell.cc.

925 {
926 return task_runners_;
927}
928

Referenced by flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ GetSettings()

const Settings & flutter::Shell::GetSettings ( ) const
overridevirtual

◆ 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 916 of file shell.cc.

Referenced by flutter::testing::ShellTest::DispatchPointerData(), flutter::testing::GetRasterizerResourceCacheBytesSync(), InferMetalPlatformViewCreationCallback(), InferOpenGLPlatformViewCreationCallback(), InferSoftwarePlatformViewCreationCallback(), InferVulkanPlatformViewCreationCallback(), flutter::testing::ShellTest::NotifyIdle(), flutter::testing::ShellTestPlatformViewBuilder::operator()(), flutter::testing::ShellTest::PlatformViewNotifyCreated(), flutter::testing::ShellTest::PlatformViewNotifyDestroyed(), flutter::testing::ShellTest::PumpOneFrame(), flutter::testing::RasterizerIsTornDown(), flutter::testing::ShellTest::RestartEngine(), flutter::testing::ShellTest::RunEngine(), flutter::RunTester(), flutter::testing::ShellTest::SendEnginePlatformMessage(), flutter::testing::ShellTest::SetViewportMetrics(), flutter::Spawn(), flutter::StartupAndShutdownShell(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::ValidateShell(), and flutter::testing::ShellTest::VSyncFlush().

◆ 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 797 of file shell.cc.

798 {
799 FML_LOG(ERROR) << "Could not launch engine with configuration.";
800 }
801
802 result(run_result);
803 }));
804}
805
806std::optional<DartErrorCode> Shell::GetUIIsolateLastError() const {
807 FML_DCHECK(is_set_up_);
809
810 if (!weak_engine_) {
811 return std::nullopt;
812 }
813 switch (weak_engine_->GetUIIsolateLastError()) {
std::optional< DartErrorCode > GetUIIsolateLastError() const
Used by embedders to get the last error from the Dart UI Isolate, if one exists.
Definition shell.cc:797
#define FML_LOG(severity)
Definition logging.h:101
@ CompilationError
The Dart error code for a compilation error.
@ kCompilationErrorType
Definition dart_error.h:71

Referenced by flutter::ScriptCompletionTaskObserver::DidProcessTask().

◆ GetVsyncWaiter()

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

Definition at line 2459 of file shell.cc.

2459 {
2460 return fml::TimePoint::Now();
2461}
2462
2463const std::shared_ptr<PlatformMessageHandler>&
const std::shared_ptr< PlatformMessageHandler > & GetPlatformMessageHandler() const override
Returns the delegate object that handles PlatformMessage's from Flutter to the host platform (and its...
Definition shell.cc:2455
static TimePoint Now()
Definition time_point.cc:49

References fml::TimePoint::Now().

◆ InferVmInitDataFromSettings()

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

Definition at line 206 of file shell.cc.

206 {
207 // Always use the `vm_snapshot` and `isolate_snapshot` provided by the
208 // settings to launch the VM. If the VM is already running, the snapshot
209 // arguments are ignored.
210 auto vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings);
211 auto isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings);
212 auto vm = DartVMRef::Create(settings, vm_snapshot, isolate_snapshot);
213
214 // If the settings did not specify an `isolate_snapshot`, fall back to the
215 // one the VM was launched with.
216 if (!isolate_snapshot) {
217 isolate_snapshot = vm->GetVMData()->GetIsolateSnapshot();
218 }
219 return {std::move(vm), isolate_snapshot};
220}
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)

References flutter::DartVMRef::Create(), flutter::DartSnapshot::IsolateSnapshotFromSettings(), and flutter::DartSnapshot::VMSnapshotFromSettings().

Referenced by Create().

◆ 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 839 of file shell.cc.

841 {

Referenced by flutter::RunTester(), flutter::testing::ValidateDestroyPlatformView(), and flutter::testing::ValidateShell().

◆ 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 731 of file shell.cc.

740 {
741 auto trace_id = fml::tracing::TraceNonce();
742 TRACE_EVENT_ASYNC_BEGIN0("flutter", "Shell::NotifyLowMemoryWarning",
743 trace_id);
744 // This does not require a current isolate but does require a running VM.
745 // Since a valid shell will not be returned to the embedder without a valid
746 // DartVMRef, we can be certain that this is a safe spot to assume a VM is
747 // running.
748 ::Dart_NotifyLowMemory();
749
750 task_runners_.GetRasterTaskRunner()->PostTask(
751 [rasterizer = rasterizer_->GetWeakPtr(), trace_id = trace_id]() {
virtual void PostTask(const fml::closure &task) override
size_t TraceNonce()
#define TRACE_EVENT_ASYNC_BEGIN0(category_group, name, id)

◆ OnDisplayUpdates()

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

Notifies the display manager of the updates.

Definition at line 2430 of file shell.cc.

2431 :
2432 is_gpu_disabled_sync_switch_->SetSwitch(true);
2433 return;
2434 default:
2435 FML_DCHECK(false);
2436 }
2437}
2438
2439void Shell::OnDisplayUpdates(std::vector<std::unique_ptr<Display>> displays) {
2440 FML_DCHECK(is_set_up_);
2442
2443 std::vector<DisplayData> display_data;
2444 display_data.reserve(displays.size());
2445 for (const auto& display : displays) {
2446 display_data.push_back(display->GetDisplayData());
2447 }
void OnDisplayUpdates(std::vector< std::unique_ptr< Display > > displays)
Notifies the display manager of the updates.
Definition shell.cc:2430
std::vector< FlutterEngineDisplay > * displays

Referenced by flutter::ConfigureShell().

◆ 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 2051 of file shell.cc.

2056 {
2057 return display_manager_->GetMainDisplayRefreshRate();
2058}
2059
2061 int32_t priority) {
2063 FML_DCHECK(is_set_up_);
2064
void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority)
Install a new factory that can match against and decode image data.
Definition shell.cc:2051
std::function< std::shared_ptr< ImageGenerator >(sk_sp< SkData > buffer)> ImageGeneratorFactory
ImageGeneratorFactory is the top level primitive for specifying an image decoder in Flutter....

◆ 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 2385 of file shell.cc.

2387 {
2388 return fml::Status();
2389 } else {
2391 }
2392}
2393
2395 FML_DCHECK(is_set_up_);
2397
2398 if (!engine_) {
bool ReloadSystemFonts()
Used by embedders to reload the system fonts in FontCollection. It also clears the cached font famili...
Definition shell.cc:2385

◆ RunEngine() [1/2]

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

Starts an isolate for the given RunConfiguration.

Definition at line 759 of file shell.cc.

Referenced by flutter::RunTester().

◆ 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 763 of file shell.cc.

763 {
764 engine_->FlushMicrotaskQueue();
765 }
766}
767
768void Shell::RunEngine(RunConfiguration run_configuration) {
769 RunEngine(std::move(run_configuration), nullptr);
770}
771
773 RunConfiguration run_configuration,
774 const std::function<void(Engine::RunStatus)>& result_callback) {
775 auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(),
776 result_callback](Engine::RunStatus run_result) {
777 if (!result_callback) {
778 return;
779 }
780 platform_runner->PostTask(
781 [result_callback, run_result]() { result_callback(run_result); });
782 };
783 FML_DCHECK(is_set_up_);
785
787 task_runners_.GetUITaskRunner(),
789 [run_configuration = std::move(run_configuration),
790 weak_engine = weak_engine_, result]() mutable {
791 if (!weak_engine) {
792 FML_LOG(ERROR)
793 << "Could not launch engine with configuration - no engine.";
794 result(Engine::RunStatus::Failure);
795 return;
RunStatus
Indicates the result of the call to Engine::Run.
Definition engine.h:74
void RunEngine(RunConfiguration run_configuration)
Starts an isolate for the given RunConfiguration.
Definition shell.cc:759

◆ 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 2322 of file shell.cc.

2324 {
2325 if (engine) {
2326 engine->SendViewFocusEvent(event);
2327 }
2328 });
2329}
2330
2331Rasterizer::Screenshot Shell::Screenshot(
2332 Rasterizer::ScreenshotType screenshot_type,
2333 bool base64_encode) {
2334 if (settings_.enable_impeller) {
2335 switch (screenshot_type) {
2337 FML_LOG(ERROR)
2338 << "Impeller backend cannot produce ScreenshotType::SkiaPicture.";
2339 return {};
2343 break;
2344 }
2345 }
2346 TRACE_EVENT0("flutter", "Shell::Screenshot");
2348 Rasterizer::Screenshot screenshot;
2350 task_runners_.GetRasterTaskRunner(), [&latch, //
2351 rasterizer = GetRasterizer(), //
2352 &screenshot, //
2353 screenshot_type, //
2354 base64_encode //
2355 ]() {
ScreenshotType
The type of the screenshot to obtain of the previously rendered layer tree.
Definition rasterizer.h:348
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 r...
Definition shell.cc:2322
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the raster task runner.
Definition shell.cc:925
FlutterEngine engine
Definition main.cc:84

◆ SetGpuAvailability()

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

Marks the GPU as available or unavailable.

Definition at line 2405 of file shell.cc.

2410 {
2411 return is_gpu_disabled_sync_switch_;
2412}
2413
2414void Shell::SetGpuAvailability(GpuAvailability availability) {
2416 switch (availability) {
2418 is_gpu_disabled_sync_switch_->SetSwitch(false);
2419 return;
2423 task_runners_.GetIOTaskRunner(),
2424 [io_manager = io_manager_.get(), &latch]() {
2425 io_manager->GetSkiaUnrefQueue()->Drain();
2426 latch.Signal();
2427 });
2428 latch.Wait();
void SetGpuAvailability(GpuAvailability availability)
Marks the GPU as available or unavailable.
Definition shell.cc:2405
GpuAvailability
Values for |Shell::SetGpuAvailability|.
Definition shell.h:64
@ 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 677 of file shell.cc.

680 {
681 task_queues->Unmerge(platform_queue_id, ui_queue_id);
682 }
683 }
684}
685
686std::unique_ptr<Shell> Shell::Spawn(
687 RunConfiguration run_configuration,
688 const std::string& initial_route,
689 const CreateCallback<PlatformView>& on_create_platform_view,
690 const CreateCallback<Rasterizer>& on_create_rasterizer) const {
691 FML_DCHECK(task_runners_.IsValid());
692
693 if (settings_.merged_platform_ui_thread ==
695 // Spawning engines that share the same task runners can result in
696 // deadlocks when the UI task runner is moved to the platform thread.
697 FML_LOG(ERROR) << "MergedPlatformUIThread::kMergeAfterLaunch does not "
698 "support spawning";
699 return nullptr;
700 }
701
702 // It's safe to store this value since it is set on the platform thread.
703 bool is_gpu_disabled = false;
706 .SetIfFalse([&is_gpu_disabled] { is_gpu_disabled = false; })
707 .SetIfTrue([&is_gpu_disabled] { is_gpu_disabled = true; }));
708 std::unique_ptr<Shell> result = CreateWithSnapshot(
709 PlatformData{}, task_runners_, rasterizer_->GetRasterThreadMerger(),
710 io_manager_, resource_cache_limit_calculator_, GetSettings(), vm_,
711 vm_->GetVMData()->GetIsolateSnapshot(), on_create_platform_view,
712 on_create_rasterizer,
713 [engine = this->engine_.get(), initial_route](
714 Engine::Delegate& delegate,
715 const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm,
716 const fml::RefPtr<const DartSnapshot>& isolate_snapshot,
717 const TaskRunners& task_runners, const PlatformData& platform_data,
718 const Settings& settings, std::unique_ptr<Animator> animator,
719 const fml::WeakPtr<IOManager>& io_manager,
720 const fml::RefPtr<SkiaUnrefQueue>& unref_queue,
722 const std::shared_ptr<fml::SyncSwitch>& is_gpu_disabled_sync_switch,
723 const std::shared_future<impeller::RuntimeStageBackend>&
724 runtime_stage_backend) {
725 return engine->Spawn(
726 /*delegate=*/delegate,
727 /*dispatcher_maker=*/dispatcher_maker,
728 /*settings=*/settings,
729 /*animator=*/std::move(animator),
std::shared_ptr< const DartVMData > GetVMData() const
The VM and isolate snapshots used by this running Dart VM instance.
Definition dart_vm.cc:522
std::unique_ptr< Shell > Spawn(RunConfiguration run_configuration, const std::string &initial_route, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer) const
Creates one Shell from another Shell where the created Shell takes the opportunity to share any inter...
Definition shell.cc:677
const Settings & GetSettings() const override
Definition shell.cc:912
std::shared_ptr< const fml::SyncSwitch > GetIsGpuDisabledSyncSwitch() const override
Accessor for the disable GPU SyncSwitch.
Definition shell.cc:2400
std::function< std::unique_ptr< PointerDataDispatcher >(PointerDataDispatcher::Delegate &)> PointerDataDispatcherMaker
Signature for constructing PointerDataDispatcher.
Represents the 2 code paths available when calling |SyncSwitchExecute|.
Definition sync_switch.h:35

Referenced by flutter::Spawn().

◆ 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 2357 of file shell.cc.

2366 {
2367 FML_DCHECK(is_set_up_);
2368 if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() ||
2369 task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) {
2371 "WaitForFirstFrame called from thread that can't wait "
2372 "because it is responsible for generating the frame.");
2373 }
2374
2375 // Check for overflow.
2376 auto now = std::chrono::steady_clock::now();
2377 auto max_duration = std::chrono::steady_clock::time_point::max() - now;
2378 auto desired_duration = std::chrono::milliseconds(timeout.ToMilliseconds());
2379 auto duration =
2380 now + (desired_duration > max_duration ? max_duration : desired_duration);
2381
2382 std::unique_lock<std::mutex> lock(waiting_for_first_frame_mutex_);
2383 bool success = waiting_for_first_frame_condition_.wait_until(
constexpr int64_t ToMilliseconds() const
Definition time_delta.h:63

Friends And Related Symbol Documentation

◆ testing::ShellTest

friend class testing::ShellTest
friend

Definition at line 827 of file shell.h.


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