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.
 
std::shared_ptr< fml::BasicTaskRunnerGetShutdownSafeIOTaskRunner ()
 The IO thread can be used for background tasks, including tasks that perform graphics operations using the resource context. But the IO thread will lose the resource context during shutdown of the Shell. Tasks that require the IO manager or the resource context must not run after that phase of shutdown.
 
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 606 of file shell.cc.

610 {task_runners_.GetIOTaskRunner(),
611 std::bind(&Shell::OnServiceProtocolGetPipelineUsage, this,
612 std::placeholders::_1, std::placeholders::_2)};
613}
614
616#if !SLIMPELLER
618 task_runners_.GetIOTaskRunner());
619#endif // !SLIMPELLER
620
621 vm_->GetServiceProtocol()->RemoveHandler(this);
622
623 fml::AutoResetWaitableEvent platiso_latch, ui_latch, gpu_latch,
624 platform_latch, io_latch;
625
627 task_runners_.GetPlatformTaskRunner(),
628 fml::MakeCopyable([this, &platiso_latch]() mutable {
629 engine_->ShutdownPlatformIsolates();
630 platiso_latch.Signal();
631 }));
632 platiso_latch.Wait();
633
635 task_runners_.GetUITaskRunner(),
636 fml::MakeCopyable([this, &ui_latch]() mutable {
637 engine_.reset();
638 ui_latch.Signal();
639 }));
640 ui_latch.Wait();
641
643 task_runners_.GetRasterTaskRunner(),
645 [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable {
646 rasterizer.reset();
647 this->weak_factory_gpu_.reset();
648 gpu_latch.Signal();
649 }));
650 gpu_latch.Wait();
651
653 task_runners_.GetIOTaskRunner(),
654 fml::MakeCopyable([io_manager = std::move(io_manager_),
655 platform_view = platform_view_.get(),
656 &io_latch]() mutable {
657 std::weak_ptr<ShellIOManager> weak_io_manager(io_manager);
658 io_manager.reset();
659
660 // If the IO manager is not being used by any other spawned shells,
661 // then detach the resource context from the IO thread.
662 if (platform_view && weak_io_manager.expired()) {
663 platform_view->ReleaseResourceContext();
664 }
665 io_latch.Signal();
666 }));
667
668 io_latch.Wait();
669
670 // The platform view must go last because it may be holding onto platform side
671 // counterparts to resources owned by subsystems running on other threads. For
672 // example, the NSOpenGLContext on the Mac.
674 task_runners_.GetPlatformTaskRunner(),
675 fml::MakeCopyable([platform_view = std::move(platform_view_),
676 &platform_latch]() mutable {
677 platform_view.reset();
678 platform_latch.Signal();
679 }));
680 platform_latch.Wait();
681
682 if (settings_.merged_platform_ui_thread ==
684 // Move the UI task runner back to its original thread to enable shutdown of
685 // 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:532
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:606
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:382

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

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

828 :
830 case tonic::kNoError:
832 }
834}
835
836bool 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:827
@ 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 838 of file shell.cc.

840 {
841 return false;
842 }
843
844 return weak_engine_->UIIsolateHasLivePorts();
845}
846
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:838

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

◆ GetConcurrentWorkerTaskRunner()

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

Definition at line 2488 of file shell.cc.

2489 {
2490 if (!engine_) {
2491 return {};
2492 }
2493 return engine_->GetVsyncWaiter();
2494}

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

960 {
961 FML_DCHECK(is_set_up_);
962 return io_manager_->GetWeakPtr();
#define FML_DCHECK(condition)
Definition logging.h:122

References FML_DCHECK.

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

941 {
942 return parent_raster_thread_merger_;
943}
944

◆ 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 951 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 2421 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 2068 of file shell.cc.

2068 {
2070 response->SetObject();
virtual bool RunsTasksOnCurrentThread()

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

932 {
933 return settings_;
934}

◆ 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 2476 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 946 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 936 of file shell.cc.

936 {
937 return task_runners_;
938}
939

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

◆ GetSettings()

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

◆ GetShutdownSafeIOTaskRunner()

std::shared_ptr< fml::BasicTaskRunner > flutter::Shell::GetShutdownSafeIOTaskRunner ( )

The IO thread can be used for background tasks, including tasks that perform graphics operations using the resource context. But the IO thread will lose the resource context during shutdown of the Shell. Tasks that require the IO manager or the resource context must not run after that phase of shutdown.

Returns
A BasicTaskRunner that posts tasks to the IO thread but stops running tasks after the Shell shuts down the IO manager.

Definition at line 956 of file shell.cc.

Referenced by InferOpenGLPlatformViewCreationCallback().

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

808 {
809 FML_LOG(ERROR) << "Could not launch engine with configuration.";
810 }
811
812 result(run_result);
813 }));
814}
815
816std::optional<DartErrorCode> Shell::GetUIIsolateLastError() const {
817 FML_DCHECK(is_set_up_);
819
820 if (!weak_engine_) {
821 return std::nullopt;
822 }
823 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:807
#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 2480 of file shell.cc.

2480 {
2481 return fml::TimePoint::Now();
2482}
2483
2484const 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:2476
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 207 of file shell.cc.

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

851 {

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

750 {
751 auto trace_id = fml::tracing::TraceNonce();
752 TRACE_EVENT_ASYNC_BEGIN0("flutter", "Shell::NotifyLowMemoryWarning",
753 trace_id);
754 // This does not require a current isolate but does require a running VM.
755 // Since a valid shell will not be returned to the embedder without a valid
756 // DartVMRef, we can be certain that this is a safe spot to assume a VM is
757 // running.
758 ::Dart_NotifyLowMemory();
759
760 task_runners_.GetRasterTaskRunner()->PostTask(
761 [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 2451 of file shell.cc.

2452 :
2453 is_gpu_disabled_sync_switch_->SetSwitch(true);
2454 return;
2455 default:
2456 FML_DCHECK(false);
2457 }
2458}
2459
2460void Shell::OnDisplayUpdates(std::vector<std::unique_ptr<Display>> displays) {
2461 FML_DCHECK(is_set_up_);
2463
2464 std::vector<DisplayData> display_data;
2465 display_data.reserve(displays.size());
2466 for (const auto& display : displays) {
2467 display_data.push_back(display->GetDisplayData());
2468 }
void OnDisplayUpdates(std::vector< std::unique_ptr< Display > > displays)
Notifies the display manager of the updates.
Definition shell.cc:2451
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 2072 of file shell.cc.

2077 {
2078 return display_manager_->GetMainDisplayRefreshRate();
2079}
2080
2082 int32_t priority) {
2084 FML_DCHECK(is_set_up_);
2085
void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority)
Install a new factory that can match against and decode image data.
Definition shell.cc:2072
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 2406 of file shell.cc.

2408 {
2409 return fml::Status();
2410 } else {
2412 }
2413}
2414
2416 FML_DCHECK(is_set_up_);
2418
2419 if (!engine_) {
bool ReloadSystemFonts()
Used by embedders to reload the system fonts in FontCollection. It also clears the cached font famili...
Definition shell.cc:2406

◆ RunEngine() [1/2]

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

Starts an isolate for the given RunConfiguration.

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

773 {
774 engine_->FlushMicrotaskQueue();
775 }
776}
777
778void Shell::RunEngine(RunConfiguration run_configuration) {
779 RunEngine(std::move(run_configuration), nullptr);
780}
781
783 RunConfiguration run_configuration,
784 const std::function<void(Engine::RunStatus)>& result_callback) {
785 auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(),
786 result_callback](Engine::RunStatus run_result) {
787 if (!result_callback) {
788 return;
789 }
790 platform_runner->PostTask(
791 [result_callback, run_result]() { result_callback(run_result); });
792 };
793 FML_DCHECK(is_set_up_);
795
797 task_runners_.GetUITaskRunner(),
799 [run_configuration = std::move(run_configuration),
800 weak_engine = weak_engine_, result]() mutable {
801 if (!weak_engine) {
802 FML_LOG(ERROR)
803 << "Could not launch engine with configuration - no engine.";
804 result(Engine::RunStatus::Failure);
805 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:769

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

2345 {
2346 if (engine) {
2347 engine->SendViewFocusEvent(event);
2348 }
2349 });
2350}
2351
2352Rasterizer::Screenshot Shell::Screenshot(
2353 Rasterizer::ScreenshotType screenshot_type,
2354 bool base64_encode) {
2355 if (settings_.enable_impeller) {
2356 switch (screenshot_type) {
2358 FML_LOG(ERROR)
2359 << "Impeller backend cannot produce ScreenshotType::SkiaPicture.";
2360 return {};
2364 break;
2365 }
2366 }
2367 TRACE_EVENT0("flutter", "Shell::Screenshot");
2369 Rasterizer::Screenshot screenshot;
2371 task_runners_.GetRasterTaskRunner(), [&latch, //
2372 rasterizer = GetRasterizer(), //
2373 &screenshot, //
2374 screenshot_type, //
2375 base64_encode //
2376 ]() {
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:2343
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the raster task runner.
Definition shell.cc:936
FlutterEngine engine
Definition main.cc:84

◆ SetGpuAvailability()

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

Marks the GPU as available or unavailable.

Definition at line 2426 of file shell.cc.

2431 {
2432 return is_gpu_disabled_sync_switch_;
2433}
2434
2435void Shell::SetGpuAvailability(GpuAvailability availability) {
2437 switch (availability) {
2439 is_gpu_disabled_sync_switch_->SetSwitch(false);
2440 return;
2444 task_runners_.GetIOTaskRunner(),
2445 [io_manager = io_manager_.get(), &latch]() {
2446 io_manager->GetSkiaUnrefQueue()->Drain();
2447 latch.Signal();
2448 });
2449 latch.Wait();
void SetGpuAvailability(GpuAvailability availability)
Marks the GPU as available or unavailable.
Definition shell.cc:2426
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 687 of file shell.cc.

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

2387 {
2388 FML_DCHECK(is_set_up_);
2389 if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() ||
2390 task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) {
2392 "WaitForFirstFrame called from thread that can't wait "
2393 "because it is responsible for generating the frame.");
2394 }
2395
2396 // Check for overflow.
2397 auto now = std::chrono::steady_clock::now();
2398 auto max_duration = std::chrono::steady_clock::time_point::max() - now;
2399 auto desired_duration = std::chrono::milliseconds(timeout.ToMilliseconds());
2400 auto duration =
2401 now + (desired_duration > max_duration ? max_duration : desired_duration);
2402
2403 std::unique_lock<std::mutex> lock(waiting_for_first_frame_mutex_);
2404 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 847 of file shell.h.


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