Flutter Engine
 
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 591 of file shell.cc.

594 {
595 task_runners_.GetPlatformTaskRunner(),
596 std::bind(&Shell::OnServiceProtocolReloadAssetFonts, this,
597 std::placeholders::_1, std::placeholders::_2)};
598}
599
601#if !SLIMPELLER
603 task_runners_.GetIOTaskRunner());
604#endif // !SLIMPELLER
605
606 vm_->GetServiceProtocol()->RemoveHandler(this);
607
608 fml::AutoResetWaitableEvent platiso_latch, ui_latch, gpu_latch,
609 platform_latch, io_latch;
610
612 task_runners_.GetPlatformTaskRunner(),
613 fml::MakeCopyable([this, &platiso_latch]() mutable {
614 engine_->ShutdownPlatformIsolates();
615 platiso_latch.Signal();
616 }));
617 platiso_latch.Wait();
618
620 task_runners_.GetUITaskRunner(),
621 fml::MakeCopyable([this, &ui_latch]() mutable {
622 engine_.reset();
623 ui_latch.Signal();
624 }));
625 ui_latch.Wait();
626
628 task_runners_.GetRasterTaskRunner(),
630 [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable {
631 rasterizer.reset();
632 this->weak_factory_gpu_.reset();
633 gpu_latch.Signal();
634 }));
635 gpu_latch.Wait();
636
638 task_runners_.GetIOTaskRunner(),
639 fml::MakeCopyable([io_manager = std::move(io_manager_),
640 platform_view = platform_view_.get(),
641 &io_latch]() mutable {
642 std::weak_ptr<ShellIOManager> weak_io_manager(io_manager);
643 io_manager.reset();
644
645 // If the IO manager is not being used by any other spawned shells,
646 // then detach the resource context from the IO thread.
647 if (platform_view && weak_io_manager.expired()) {
648 platform_view->ReleaseResourceContext();
649 }
650 io_latch.Signal();
651 }));
652
653 io_latch.Wait();
654
655 // The platform view must go last because it may be holding onto platform side
656 // counterparts to resources owned by subsystems running on other threads. For
657 // example, the NSOpenGLContext on the Mac.
659 task_runners_.GetPlatformTaskRunner(),
660 fml::MakeCopyable([platform_view = std::move(platform_view_),
661 &platform_latch]() mutable {
662 platform_view.reset();
663 platform_latch.Signal();
664 }));
665 platform_latch.Wait();
666
667 if (settings_.merged_platform_ui_thread ==
669 // Move the UI task runner back to its original thread to enable shutdown of
670 // 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:591
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 221 of file shell.cc.

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

813 :
815 case tonic::kNoError:
817 }
819}
820
821bool 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:812
@ 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 823 of file shell.cc.

825 {
826 return false;
827 }
828
829 return weak_engine_->UIIsolateHasLivePorts();
830}
831
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:823

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

◆ GetConcurrentWorkerTaskRunner()

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

Definition at line 2418 of file shell.cc.

2419 {
2420 if (!engine_) {
2421 return {};
2422 }
2423 return engine_->GetVsyncWaiter();
2424}

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

925 {
926 return parent_raster_thread_merger_;
927}
928

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

2031 {
2033 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 915 of file shell.cc.

916 {
917 return settings_;
918}

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

920 {
921 return task_runners_;
922}
923

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

793 {
794 FML_LOG(ERROR) << "Could not launch engine with configuration.";
795 }
796
797 result(run_result);
798 }));
799}
800
801std::optional<DartErrorCode> Shell::GetUIIsolateLastError() const {
802 FML_DCHECK(is_set_up_);
804
805 if (!weak_engine_) {
806 return std::nullopt;
807 }
808 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:792
#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 2410 of file shell.cc.

2410 {
2411 return fml::TimePoint::Now();
2412}
2413
2414const 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:2406
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 205 of file shell.cc.

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

836 {

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

735 {
736 auto trace_id = fml::tracing::TraceNonce();
737 TRACE_EVENT_ASYNC_BEGIN0("flutter", "Shell::NotifyLowMemoryWarning",
738 trace_id);
739 // This does not require a current isolate but does require a running VM.
740 // Since a valid shell will not be returned to the embedder without a valid
741 // DartVMRef, we can be certain that this is a safe spot to assume a VM is
742 // running.
743 ::Dart_NotifyLowMemory();
744
745 task_runners_.GetRasterTaskRunner()->PostTask(
746 [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 2381 of file shell.cc.

2382 :
2383 is_gpu_disabled_sync_switch_->SetSwitch(true);
2384 return;
2385 default:
2386 FML_DCHECK(false);
2387 }
2388}
2389
2390void Shell::OnDisplayUpdates(std::vector<std::unique_ptr<Display>> displays) {
2391 FML_DCHECK(is_set_up_);
2393
2394 std::vector<DisplayData> display_data;
2395 display_data.reserve(displays.size());
2396 for (const auto& display : displays) {
2397 display_data.push_back(display->GetDisplayData());
2398 }
void OnDisplayUpdates(std::vector< std::unique_ptr< Display > > displays)
Notifies the display manager of the updates.
Definition shell.cc:2381
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 2035 of file shell.cc.

2040 {
2041 return display_manager_->GetMainDisplayRefreshRate();
2042}
2043
2045 int32_t priority) {
2047 FML_DCHECK(is_set_up_);
2048
void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority)
Install a new factory that can match against and decode image data.
Definition shell.cc:2035
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 2336 of file shell.cc.

2338 {
2339 return fml::Status();
2340 } else {
2342 }
2343}
2344
2346 FML_DCHECK(is_set_up_);
2348
2349 if (!engine_) {
bool ReloadSystemFonts()
Used by embedders to reload the system fonts in FontCollection. It also clears the cached font famili...
Definition shell.cc:2336

◆ RunEngine() [1/2]

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

Starts an isolate for the given RunConfiguration.

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

758 {
759 engine_->FlushMicrotaskQueue();
760 }
761}
762
763void Shell::RunEngine(RunConfiguration run_configuration) {
764 RunEngine(std::move(run_configuration), nullptr);
765}
766
768 RunConfiguration run_configuration,
769 const std::function<void(Engine::RunStatus)>& result_callback) {
770 auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(),
771 result_callback](Engine::RunStatus run_result) {
772 if (!result_callback) {
773 return;
774 }
775 platform_runner->PostTask(
776 [result_callback, run_result]() { result_callback(run_result); });
777 };
778 FML_DCHECK(is_set_up_);
780
782 task_runners_.GetUITaskRunner(),
784 [run_configuration = std::move(run_configuration),
785 weak_engine = weak_engine_, result]() mutable {
786 if (!weak_engine) {
787 FML_LOG(ERROR)
788 << "Could not launch engine with configuration - no engine.";
789 result(Engine::RunStatus::Failure);
790 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:754

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

2275 {
2276 if (engine) {
2277 engine->SendViewFocusEvent(event);
2278 }
2279 });
2280}
2281
2282Rasterizer::Screenshot Shell::Screenshot(
2283 Rasterizer::ScreenshotType screenshot_type,
2284 bool base64_encode) {
2285 if (settings_.enable_impeller) {
2286 switch (screenshot_type) {
2288 FML_LOG(ERROR)
2289 << "Impeller backend cannot produce ScreenshotType::SkiaPicture.";
2290 return {};
2294 break;
2295 }
2296 }
2297 TRACE_EVENT0("flutter", "Shell::Screenshot");
2299 Rasterizer::Screenshot screenshot;
2301 task_runners_.GetRasterTaskRunner(), [&latch, //
2302 rasterizer = GetRasterizer(), //
2303 &screenshot, //
2304 screenshot_type, //
2305 base64_encode //
2306 ]() {
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:2273
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the raster task runner.
Definition shell.cc:920
FlutterEngine engine
Definition main.cc:84

◆ SetGpuAvailability()

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

Marks the GPU as available or unavailable.

Definition at line 2356 of file shell.cc.

2361 {
2362 return is_gpu_disabled_sync_switch_;
2363}
2364
2365void Shell::SetGpuAvailability(GpuAvailability availability) {
2367 switch (availability) {
2369 is_gpu_disabled_sync_switch_->SetSwitch(false);
2370 return;
2374 task_runners_.GetIOTaskRunner(),
2375 [io_manager = io_manager_.get(), &latch]() {
2376 io_manager->GetSkiaUnrefQueue()->Drain();
2377 latch.Signal();
2378 });
2379 latch.Wait();
void SetGpuAvailability(GpuAvailability availability)
Marks the GPU as available or unavailable.
Definition shell.cc:2356
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 672 of file shell.cc.

675 {
676 task_queues->Unmerge(platform_queue_id, ui_queue_id);
677 }
678 }
679}
680
681std::unique_ptr<Shell> Shell::Spawn(
682 RunConfiguration run_configuration,
683 const std::string& initial_route,
684 const CreateCallback<PlatformView>& on_create_platform_view,
685 const CreateCallback<Rasterizer>& on_create_rasterizer) const {
686 FML_DCHECK(task_runners_.IsValid());
687
688 if (settings_.merged_platform_ui_thread ==
690 // Spawning engines that share the same task runners can result in
691 // deadlocks when the UI task runner is moved to the platform thread.
692 FML_LOG(ERROR) << "MergedPlatformUIThread::kMergeAfterLaunch does not "
693 "support spawning";
694 return nullptr;
695 }
696
697 // It's safe to store this value since it is set on the platform thread.
698 bool is_gpu_disabled = false;
701 .SetIfFalse([&is_gpu_disabled] { is_gpu_disabled = false; })
702 .SetIfTrue([&is_gpu_disabled] { is_gpu_disabled = true; }));
703 std::unique_ptr<Shell> result = CreateWithSnapshot(
704 PlatformData{}, task_runners_, rasterizer_->GetRasterThreadMerger(),
705 io_manager_, resource_cache_limit_calculator_, GetSettings(), vm_,
706 vm_->GetVMData()->GetIsolateSnapshot(), on_create_platform_view,
707 on_create_rasterizer,
708 [engine = this->engine_.get(), initial_route](
709 Engine::Delegate& delegate,
710 const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm,
711 const fml::RefPtr<const DartSnapshot>& isolate_snapshot,
712 const TaskRunners& task_runners, const PlatformData& platform_data,
713 const Settings& settings, std::unique_ptr<Animator> animator,
714 const fml::WeakPtr<IOManager>& io_manager,
715 const fml::RefPtr<SkiaUnrefQueue>& unref_queue,
717 const std::shared_ptr<fml::SyncSwitch>& is_gpu_disabled_sync_switch,
718 const std::shared_future<impeller::RuntimeStageBackend>&
719 runtime_stage_backend) {
720 return engine->Spawn(
721 /*delegate=*/delegate,
722 /*dispatcher_maker=*/dispatcher_maker,
723 /*settings=*/settings,
724 /*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:672
const Settings & GetSettings() const override
Definition shell.cc:907
std::shared_ptr< const fml::SyncSwitch > GetIsGpuDisabledSyncSwitch() const override
Accessor for the disable GPU SyncSwitch.
Definition shell.cc:2351
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 2308 of file shell.cc.

2317 {
2318 FML_DCHECK(is_set_up_);
2319 if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() ||
2320 task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) {
2322 "WaitForFirstFrame called from thread that can't wait "
2323 "because it is responsible for generating the frame.");
2324 }
2325
2326 // Check for overflow.
2327 auto now = std::chrono::steady_clock::now();
2328 auto max_duration = std::chrono::steady_clock::time_point::max() - now;
2329 auto desired_duration = std::chrono::milliseconds(timeout.ToMilliseconds());
2330 auto duration =
2331 now + (desired_duration > max_duration ? max_duration : desired_duration);
2332
2333 std::unique_lock<std::mutex> lock(waiting_for_first_frame_mutex_);
2334 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 818 of file shell.h.


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