Flutter Engine
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

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::WeakPtr< SnapshotDelegate > snapshot_delegate, std::shared_ptr< VolatilePathTracker > volatile_path_tracker)> EngineCreateCallback
 
- Public Types inherited from flutter::PlatformView::Delegate
using KeyDataResponse = std::function< void(bool)>
 
- Public Types inherited from flutter::ServiceProtocol::Handler
using ServiceProtocolMap = std::map< std::string_view, std::string_view >
 

Public Member Functions

 ~Shell ()
 Destroys the shell. This is a synchronous operation and synchronous barrier blocks are introduced on the various threads to ensure shutdown of all shell sub-components before this method returns. More...
 
std::unique_ptr< ShellSpawn (RunConfiguration run_configuration, const std::string &initial_route, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer) const
 Creates one Shell from another Shell where the created Shell takes the opportunity to share any internal components it can. This results is a Shell that has a smaller startup time cost and a smaller memory footprint than an Shell created with the Create function. More...
 
void RunEngine (RunConfiguration run_configuration)
 Starts an isolate for the given RunConfiguration. More...
 
void RunEngine (RunConfiguration run_configuration, const std::function< void(Engine::RunStatus)> &result_callback)
 Starts an isolate for the given RunConfiguration. The result_callback will be called with the status of the operation. More...
 
const SettingsGetSettings () const
 
const TaskRunnersGetTaskRunners () const override
 If callers wish to interact directly with any shell subcomponents, they must (on the platform thread) obtain a task runner that the component is designed to run on and a weak pointer to that component. They may then post a task to that task runner, do the validity check on that task runner before performing any operation on that component. This accessor allows callers to access the task runners for this shell. More...
 
const fml::RefPtr< fml::RasterThreadMergerGetParentRasterThreadMerger () const override
 Getting the raster thread merger from parent shell, it can be a null RefPtr when it's a root Shell or the embedder_->SupportsDynamicThreadMerging() returns false. More...
 
fml::TaskRunnerAffineWeakPtr< RasterizerGetRasterizer () const
 Rasterizers may only be accessed on the raster task runner. More...
 
fml::WeakPtr< EngineGetEngine ()
 Engines may only be accessed on the UI thread. This method is deprecated, and implementers should instead use other API available on the Shell or the PlatformView. More...
 
fml::WeakPtr< PlatformViewGetPlatformView ()
 Platform views may only be accessed on the platform task runner. More...
 
fml::WeakPtr< ShellIOManagerGetIOManager ()
 The IO Manager may only be accessed on the IO task runner. More...
 
void NotifyLowMemoryWarning () const
 Used by embedders to notify that there is a low memory warning. The shell will attempt to purge caches. Current, only the rasterizer cache is purged. More...
 
bool IsSetup () const
 Used by embedders to check if all shell subcomponents are initialized. It is the embedder's responsibility to make this call before accessing any other shell method. A shell that is not set up must be discarded and another one created with updated settings. More...
 
Rasterizer::Screenshot Screenshot (Rasterizer::ScreenshotType type, bool base64_encode)
 Captures a screenshot and optionally Base64 encodes the data of the last layer tree rendered by the rasterizer in this shell. More...
 
fml::Status WaitForFirstFrame (fml::TimeDelta timeout)
 Pauses the calling thread until the first frame is presented. More...
 
bool ReloadSystemFonts ()
 Used by embedders to reload the system fonts in FontCollection. It also clears the cached font families and send system channel message to framework to rebuild affected widgets. More...
 
std::optional< DartErrorCodeGetUIIsolateLastError () const
 Used by embedders to get the last error from the Dart UI Isolate, if one exists. More...
 
bool EngineHasLivePorts () const
 Used by embedders to check if the Engine is running and has any live ports remaining. For example, the Flutter tester uses this method to check whether it should continue to wait for a running test or not. More...
 
std::shared_ptr< const fml::SyncSwitchGetIsGpuDisabledSyncSwitch () const override
 Accessor for the disable GPU SyncSwitch. More...
 
void SetGpuAvailability (GpuAvailability availability)
 Marks the GPU as available or unavailable. More...
 
DartVMGetDartVM ()
 Get a pointer to the Dart VM used by this running shell instance. More...
 
void OnDisplayUpdates (DisplayUpdateType update_type, std::vector< std::unique_ptr< Display >> displays)
 Notifies the display manager of the updates. More...
 
double GetMainDisplayRefreshRate ()
 Queries the DisplayManager for the main display refresh rate. More...
 
void RegisterImageDecoder (ImageGeneratorFactory factory, int32_t priority)
 Install a new factory that can match against and decode image data. More...
 
const std::shared_ptr< PlatformMessageHandler > & GetPlatformMessageHandler () const
 Returns the delegate object that handles PlatformMessage's from Flutter to the host platform (and its responses). More...
 
- 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. More...
 

Static Public Member Functions

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

Friends

class testing::ShellTest
 

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 107 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 114 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::WeakPtr<SnapshotDelegate> snapshot_delegate, std::shared_ptr<VolatilePathTracker> volatile_path_tracker)> flutter::Shell::EngineCreateCallback

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

References flutter::PersistentCache::GetCacheForProcess(), flutter::TaskRunners::GetIOTaskRunner(), flutter::TaskRunners::GetPlatformTaskRunner(), flutter::TaskRunners::GetRasterTaskRunner(), flutter::DartVM::GetServiceProtocol(), flutter::TaskRunners::GetUITaskRunner(), fml::MakeCopyable(), platform_view, flutter::PersistentCache::RemoveWorkerTaskRunner(), fml::TaskRunner::RunNowOrPostTask(), fml::AutoResetWaitableEvent::Signal(), and fml::AutoResetWaitableEvent::Wait().

428  {
430  task_runners_.GetIOTaskRunner());
431 
432  vm_->GetServiceProtocol()->RemoveHandler(this);
433 
434  fml::AutoResetWaitableEvent ui_latch, gpu_latch, platform_latch, io_latch;
435 
437  task_runners_.GetUITaskRunner(),
438  fml::MakeCopyable([this, &ui_latch]() mutable {
439  engine_.reset();
440  ui_latch.Signal();
441  }));
442  ui_latch.Wait();
443 
445  task_runners_.GetRasterTaskRunner(),
447  [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable {
448  rasterizer.reset();
449  this->weak_factory_gpu_.reset();
450  gpu_latch.Signal();
451  }));
452  gpu_latch.Wait();
453 
455  task_runners_.GetIOTaskRunner(),
456  fml::MakeCopyable([io_manager = std::move(io_manager_),
457  platform_view = platform_view_.get(),
458  &io_latch]() mutable {
459  io_manager.reset();
460  if (platform_view) {
461  platform_view->ReleaseResourceContext();
462  }
463  io_latch.Signal();
464  }));
465 
466  io_latch.Wait();
467 
468  // The platform view must go last because it may be holding onto platform side
469  // counterparts to resources owned by subsystems running on other threads. For
470  // example, the NSOpenGLContext on the Mac.
472  task_runners_.GetPlatformTaskRunner(),
473  fml::MakeCopyable([platform_view = std::move(platform_view_),
474  &platform_latch]() mutable {
475  platform_view.reset();
476  platform_latch.Signal();
477  }));
478  platform_latch.Wait();
479 }
fml::WeakPtr< IOManager > io_manager_
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:510
std::unique_ptr< flutter::PlatformViewIOS > platform_view
static void RunNowOrPostTask(fml::RefPtr< fml::TaskRunner > runner, const fml::closure &task)
Definition: task_runner.cc:55
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition: make_copyable.h:57
void RemoveWorkerTaskRunner(fml::RefPtr< fml::TaskRunner > task_runner)
static PersistentCache * GetCacheForProcess()
TaskRunners task_runners_

Member Function Documentation

◆ Create()

std::unique_ptr< Shell > flutter::Shell::Create ( const PlatformData platform_data,
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 126 of file shell.cc.

References flutter::DartVMRef::Create(), FML_CHECK, FML_DCHECK, FML_LOG, flutter::TaskRunners::GetIOTaskRunner(), flutter::TaskRunners::GetPlatformTaskRunner(), flutter::TaskRunners::GetRasterTaskRunner(), flutter::TaskRunners::GetUITaskRunner(), flutter::DartSnapshot::IsolateSnapshotFromSettings(), flutter::TaskRunners::IsValid(), flutter::ServiceProtocol::kEstimateRasterCacheMemoryExtensionName, flutter::ServiceProtocol::kFlushUIThreadTasksExtensionName, flutter::ServiceProtocol::kGetDisplayRefreshRateExtensionName, flutter::ServiceProtocol::kGetSkSLsExtensionName, flutter::ServiceProtocol::kRunInViewExtensionName, flutter::ServiceProtocol::kScreenshotExtensionName, flutter::ServiceProtocol::kScreenshotSkpExtensionName, flutter::ServiceProtocol::kSetAssetBundlePathExtensionName, fml::MakeCopyable(), platform_view, fml::TaskRunner::RunNowOrPostTask(), fml::TaskRunner::RunsTasksOnCurrentThread(), fml::AutoResetWaitableEvent::Signal(), flutter::Settings::skia_deterministic_rendering_on_cpu, TRACE_EVENT0, flutter::DartSnapshot::VMSnapshotFromSettings(), and fml::AutoResetWaitableEvent::Wait().

Referenced by flutter::AndroidShellHolder::AndroidShellHolder(), flutter::testing::ShellTest::CreateShell(), FlutterEngine::destroyContext, flutter_runner::Engine::Engine(), flutter::EmbedderEngine::LaunchShell(), flutter::RunTester(), flutter::StartupAndShutdownShell(), and flutter::testing::TEST_F().

132  {
133  // This must come first as it initializes tracing.
134  PerformInitializationTasks(settings);
135 
136  TRACE_EVENT0("flutter", "Shell::Create");
137 
138  // Always use the `vm_snapshot` and `isolate_snapshot` provided by the
139  // settings to launch the VM. If the VM is already running, the snapshot
140  // arguments are ignored.
141  auto vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings);
142  auto isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings);
143  auto vm = DartVMRef::Create(settings, vm_snapshot, isolate_snapshot);
144  FML_CHECK(vm) << "Must be able to initialize the VM.";
145 
146  // If the settings did not specify an `isolate_snapshot`, fall back to the
147  // one the VM was launched with.
148  if (!isolate_snapshot) {
149  isolate_snapshot = vm->GetVMData()->GetIsolateSnapshot();
150  }
151  return CreateWithSnapshot(std::move(platform_data), //
152  std::move(task_runners), //
153  /*parent_merger=*/nullptr, //
154  std::move(settings), //
155  std::move(vm), //
156  std::move(isolate_snapshot), //
157  std::move(on_create_platform_view), //
158  std::move(on_create_rasterizer), //
159  CreateEngine, is_gpu_disabled);
160 }
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:90
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(Settings settings, fml::RefPtr< const DartSnapshot > vm_snapshot=nullptr, fml::RefPtr< const DartSnapshot > isolate_snapshot=nullptr)
#define FML_CHECK(condition)
Definition: logging.h:68
static fml::RefPtr< const DartSnapshot > VMSnapshotFromSettings(const Settings &settings)
From the fields present in the given settings object, infer the core snapshot.

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

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

598  {
599  FML_DCHECK(is_setup_);
600  FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread());
601 
602  if (!weak_engine_) {
603  return false;
604  }
605 
606  return weak_engine_->UIIsolateHasLivePorts();
607 }
#define FML_DCHECK(condition)
Definition: logging.h:86
TaskRunners task_runners_

◆ GetDartVM()

DartVM * flutter::Shell::GetDartVM ( )

◆ GetEngine()

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

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

Returns
A weak pointer to the engine.

Definition at line 686 of file shell.cc.

References FML_DCHECK.

686  {
687  FML_DCHECK(is_setup_);
688  return weak_engine_;
689 }
#define FML_DCHECK(condition)
Definition: logging.h:86

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

References FML_DCHECK.

696  {
697  FML_DCHECK(is_setup_);
698  return io_manager_->GetWeakPtr();
699 }
fml::WeakPtr< IOManager > io_manager_
#define FML_DCHECK(condition)
Definition: logging.h:86

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

Referenced by Spawn().

1824  {
1825  return is_gpu_disabled_sync_switch_;
1826 }

◆ GetMainDisplayRefreshRate()

double flutter::Shell::GetMainDisplayRefreshRate ( )

Queries the DisplayManager for the main display refresh rate.

Definition at line 1624 of file shell.cc.

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

1624  {
1625  return display_manager_->GetMainDisplayRefreshRate();
1626 }

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

677  {
678  return parent_raster_thread_merger_;
679 }

◆ GetPlatformMessageHandler()

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

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

Definition at line 1863 of file shell.cc.

1863  {
1864  return platform_message_handler_;
1865 }

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

References FML_DCHECK.

Referenced by flutter::testing::ShellTest::DispatchPointerData(), flutter::testing::ShellTest::PlatformViewNotifyCreated(), flutter::testing::ShellTest::PlatformViewNotifyDestroyed(), flutter::testing::TEST_F(), flutter::testing::ValidateShell(), and flutter::testing::ShellTest::VSyncFlush().

691  {
692  FML_DCHECK(is_setup_);
693  return weak_platform_view_;
694 }
#define FML_DCHECK(condition)
Definition: logging.h:86

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

References FML_DCHECK.

Referenced by flutter::testing::GetRasterizerResourceCacheBytesSync(), flutter::testing::RasterizerHasLayerTree(), Screenshot(), and flutter::testing::TEST_F().

681  {
682  FML_DCHECK(is_setup_);
683  return weak_rasterizer_;
684 }
#define FML_DCHECK(condition)
Definition: logging.h:86

◆ GetSettings()

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

Definition at line 668 of file shell.cc.

Referenced by Spawn().

668  {
669  return settings_;
670 }
Settings settings_

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

Referenced by flutter::testing::ShellTest::DispatchPointerData(), flutter::testing::GetRasterizerResourceCacheBytesSync(), InferMetalPlatformViewCreationCallback(), InferOpenGLPlatformViewCreationCallback(), InferSoftwarePlatformViewCreationCallback(), flutter::testing::ShellTest::IsAnimatorRunning(), flutter::testing::ShellTest::NotifyIdle(), flutter::testing::ShellTest::PlatformViewNotifyCreated(), flutter::testing::ShellTest::PlatformViewNotifyDestroyed(), flutter::testing::ShellTest::PumpOneFrame(), flutter::testing::RasterizerHasLayerTree(), flutter::testing::ShellTest::RestartEngine(), flutter::testing::ShellTest::RunEngine(), flutter::testing::ShellTest::SendEnginePlatformMessage(), flutter::testing::ShellTest::SetViewportMetrics(), flutter::StartupAndShutdownShell(), flutter::testing::TEST_F(), flutter::testing::ValidateShell(), flutter::testing::ShellTest::VSyncFlush(), flutter::testing::WaitForIO(), and flutter::testing::WaitForRaster().

672  {
673  return task_runners_;
674 }
TaskRunners task_runners_

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

References flutter::ApiError, flutter::CompilationError, FML_DCHECK, flutter::TaskRunners::GetUITaskRunner(), tonic::kApiErrorType, tonic::kCompilationErrorType, tonic::kNoError, tonic::kUnknownErrorType, flutter::NoError, fml::TaskRunner::RunsTasksOnCurrentThread(), and flutter::UnknownError.

578  {
579  FML_DCHECK(is_setup_);
580  FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread());
581 
582  if (!weak_engine_) {
583  return std::nullopt;
584  }
585  switch (weak_engine_->GetUIIsolateLastError()) {
592  case tonic::kNoError:
593  return DartErrorCode::NoError;
594  }
596 }
#define FML_DCHECK(condition)
Definition: logging.h:86
The Dart error code for an API error.
The Dart error code for an unknown error.
TaskRunners task_runners_
The Dart error code for a compilation error.
No error has occurred.

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

References flutter::PersistentCache::AddWorkerTaskRunner(), flutter::Settings::dump_skp_on_shader_compilation, engine, flutter::PersistentCache::GetCacheForProcess(), flutter::TaskRunners::GetIOTaskRunner(), flutter::TaskRunners::GetUITaskRunner(), platform_view, flutter::Settings::prefetched_default_font_manager, flutter::PersistentCache::Purge(), flutter::Settings::purge_persistent_cache, fml::TaskRunner::RunNowOrPostTask(), and flutter::PersistentCache::SetIsDumpingSkp().

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

609  {
610  return is_setup_;
611 }

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

References flutter::TaskRunners::GetRasterTaskRunner(), fml::TaskRunner::PostTask(), TRACE_EVENT_ASYNC_BEGIN0, TRACE_EVENT_ASYNC_END0, and fml::tracing::TraceNonce().

519  {
520  auto trace_id = fml::tracing::TraceNonce();
521  TRACE_EVENT_ASYNC_BEGIN0("flutter", "Shell::NotifyLowMemoryWarning",
522  trace_id);
523  // This does not require a current isolate but does require a running VM.
524  // Since a valid shell will not be returned to the embedder without a valid
525  // DartVMRef, we can be certain that this is a safe spot to assume a VM is
526  // running.
527  ::Dart_NotifyLowMemory();
528 
529  task_runners_.GetRasterTaskRunner()->PostTask(
530  [rasterizer = rasterizer_->GetWeakPtr(), trace_id = trace_id]() {
531  if (rasterizer) {
532  rasterizer->NotifyLowMemoryWarning();
533  }
534  TRACE_EVENT_ASYNC_END0("flutter", "Shell::NotifyLowMemoryWarning",
535  trace_id);
536  });
537  // The IO Manager uses resource cache limits of 0, so it is not necessary
538  // to purge them.
539 }
#define TRACE_EVENT_ASYNC_BEGIN0(category_group, name, id)
Definition: trace_event.h:104
#define TRACE_EVENT_ASYNC_END0(category_group, name, id)
Definition: trace_event.h:107
TaskRunners task_runners_
size_t TraceNonce()
Definition: trace_event.cc:298

◆ OnDisplayUpdates()

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

Notifies the display manager of the updates.

Definition at line 1853 of file shell.cc.

References fml::TimePoint::Now().

1854  {
1855  display_manager_->HandleDisplayUpdates(update_type, std::move(displays));
1856 }

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

References fml::Base32Encode(), FML_DCHECK, FML_DLOG, flutter::PersistentCache::GetCacheForProcess(), flutter::TaskRunners::GetIOTaskRunner(), flutter::TaskRunners::GetPlatformTaskRunner(), flutter::TaskRunners::GetRasterTaskRunner(), flutter::TaskRunners::GetUITaskRunner(), fml::kRead, flutter::PersistentCache::LoadSkSLs(), fml::OpenDirectory(), fml::TaskRunner::RunNowOrPostTask(), fml::TaskRunner::RunsTasksOnCurrentThread(), flutter::ServiceProtocolFailureError(), flutter::ServiceProtocolParameterError(), flutter::sksl, and view.

1629  {
1630  FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());
1631  FML_DCHECK(is_setup_);
1632 
1634  task_runners_.GetUITaskRunner(),
1635  [engine = engine_->GetWeakPtr(), factory = std::move(factory),
1636  priority]() {
1637  if (engine) {
1638  engine->GetImageGeneratorRegistry()->AddFactory(factory, priority);
1639  }
1640  });
1641 }
#define FML_DCHECK(condition)
Definition: logging.h:86
static void RunNowOrPostTask(fml::RefPtr< fml::TaskRunner > runner, const fml::closure &task)
Definition: task_runner.cc:55
TaskRunners task_runners_

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

References flutter::buffer, fml::MallocMapping::Copy(), FML_DCHECK, flutter::TaskRunners::GetPlatformTaskRunner(), flutter::kSystemChannel, and fml::TaskRunner::RunsTasksOnCurrentThread().

1792  {
1793  FML_DCHECK(is_setup_);
1794  FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());
1795 
1796  if (!engine_) {
1797  return false;
1798  }
1799  engine_->SetupDefaultFontManager();
1800  engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache();
1801  // After system fonts are reloaded, we send a system channel message
1802  // to notify flutter framework.
1803  rapidjson::Document document;
1804  document.SetObject();
1805  auto& allocator = document.GetAllocator();
1806  rapidjson::Value message_value;
1807  message_value.SetString(kFontChange, allocator);
1808  document.AddMember(kTypeKey, message_value, allocator);
1809 
1810  rapidjson::StringBuffer buffer;
1811  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
1812  document.Accept(writer);
1813  std::string message = buffer.GetString();
1814  std::unique_ptr<PlatformMessage> fontsChangeMessage =
1815  std::make_unique<flutter::PlatformMessage>(
1817  fml::MallocMapping::Copy(message.c_str(), message.length()), nullptr);
1818 
1819  OnPlatformViewDispatchPlatformMessage(std::move(fontsChangeMessage));
1820  return true;
1821 }
#define FML_DCHECK(condition)
Definition: logging.h:86
constexpr char kSystemChannel[]
Definition: shell.cc:39
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data observatory The hostname IP address on which the Dart Observatory should be served If not defaults to or::depending on whether ipv6 is specified disable Disable the Dart Observatory The observatory is never available in release mode Bind to the IPv6 localhost address for the Dart Observatory Ignored if observatory host is set endless trace buffer
Definition: switches.h:98
constexpr char kFontChange[]
Definition: shell.cc:41
static MallocMapping Copy(const T *begin, const T *end)
Definition: mapping.h:162
TaskRunners task_runners_
constexpr char kTypeKey[]
Definition: shell.cc:40

◆ RunEngine() [1/2]

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

Starts an isolate for the given RunConfiguration.

Definition at line 541 of file shell.cc.

Referenced by flutter::testing::ShellTest::RunEngine().

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

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

References flutter::Engine::Failure, FML_DCHECK, FML_LOG, flutter::TaskRunners::GetPlatformTaskRunner(), flutter::TaskRunners::GetUITaskRunner(), fml::MakeCopyable(), result, fml::TaskRunner::RunNowOrPostTask(), and fml::TaskRunner::RunsTasksOnCurrentThread().

547  {
548  auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(),
549  result_callback](Engine::RunStatus run_result) {
550  if (!result_callback) {
551  return;
552  }
553  platform_runner->PostTask(
554  [result_callback, run_result]() { result_callback(run_result); });
555  };
556  FML_DCHECK(is_setup_);
557  FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());
558 
560  task_runners_.GetUITaskRunner(),
562  [run_configuration = std::move(run_configuration),
563  weak_engine = weak_engine_, result]() mutable {
564  if (!weak_engine) {
565  FML_LOG(ERROR)
566  << "Could not launch engine with configuration - no engine.";
568  return;
569  }
570  auto run_result = weak_engine->Run(std::move(run_configuration));
571  if (run_result == flutter::Engine::RunStatus::Failure) {
572  FML_LOG(ERROR) << "Could not launch engine with configuration.";
573  }
574  result(run_result);
575  }));
576 }
#define FML_DCHECK(condition)
Definition: logging.h:86
static void RunNowOrPostTask(fml::RefPtr< fml::TaskRunner > runner, const fml::closure &task)
Definition: task_runner.cc:55
GAsyncResult * result
#define FML_LOG(severity)
Definition: logging.h:65
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition: make_copyable.h:57
TaskRunners task_runners_
RunStatus
Indicates the result of the call to Engine::Run.
Definition: engine.h:80

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

References GetRasterizer(), flutter::TaskRunners::GetRasterTaskRunner(), fml::TaskRunner::RunNowOrPostTask(), fml::AutoResetWaitableEvent::Signal(), TRACE_EVENT0, and fml::AutoResetWaitableEvent::Wait().

1743  {
1744  TRACE_EVENT0("flutter", "Shell::Screenshot");
1746  Rasterizer::Screenshot screenshot;
1748  task_runners_.GetRasterTaskRunner(), [&latch, //
1749  rasterizer = GetRasterizer(), //
1750  &screenshot, //
1751  screenshot_type, //
1752  base64_encode //
1753  ]() {
1754  if (rasterizer) {
1755  screenshot = rasterizer->ScreenshotLastLayerTree(screenshot_type,
1756  base64_encode);
1757  }
1758  latch.Signal();
1759  });
1760  latch.Wait();
1761  return screenshot;
1762 }
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:90
static void RunNowOrPostTask(fml::RefPtr< fml::TaskRunner > runner, const fml::closure &task)
Definition: task_runner.cc:55
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the raster task runner.
Definition: shell.cc:681
TaskRunners task_runners_

◆ SetGpuAvailability()

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

Marks the GPU as available or unavailable.

Definition at line 1828 of file shell.cc.

References FML_DCHECK, flutter::TaskRunners::GetIOTaskRunner(), flutter::TaskRunners::GetPlatformTaskRunner(), flutter::kAvailable, flutter::kFlushAndMakeUnavailable, flutter::kUnavailable, fml::TaskRunner::RunNowOrPostTask(), fml::TaskRunner::RunsTasksOnCurrentThread(), fml::AutoResetWaitableEvent::Signal(), and fml::AutoResetWaitableEvent::Wait().

1828  {
1829  FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());
1830  switch (availability) {
1832  is_gpu_disabled_sync_switch_->SetSwitch(false);
1833  return;
1837  task_runners_.GetIOTaskRunner(),
1838  [io_manager = io_manager_.get(), &latch]() {
1839  io_manager->GetSkiaUnrefQueue()->Drain();
1840  latch.Signal();
1841  });
1842  latch.Wait();
1843  }
1844  // FALLTHROUGH
1846  is_gpu_disabled_sync_switch_->SetSwitch(true);
1847  return;
1848  default:
1849  FML_DCHECK(false);
1850  }
1851 }
fml::WeakPtr< IOManager > io_manager_
#define FML_DCHECK(condition)
Definition: logging.h:86
static void RunNowOrPostTask(fml::RefPtr< fml::TaskRunner > runner, const fml::closure &task)
Definition: task_runner.cc:55
Indicates that GPU operations should be permitted.
TaskRunners task_runners_

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

References engine, FML_DCHECK, GetIsGpuDisabledSyncSwitch(), GetSettings(), flutter::DartVM::GetVMData(), flutter::TaskRunners::IsValid(), and result.

485  {
486  FML_DCHECK(task_runners_.IsValid());
487  // It's safe to store this value since it is set on the platform thread.
488  bool is_gpu_disabled = false;
489  GetIsGpuDisabledSyncSwitch()->Execute(
491  .SetIfFalse([&is_gpu_disabled] { is_gpu_disabled = false; })
492  .SetIfTrue([&is_gpu_disabled] { is_gpu_disabled = true; }));
493  std::unique_ptr<Shell> result = (CreateWithSnapshot(
494  PlatformData{}, task_runners_, rasterizer_->GetRasterThreadMerger(),
495  GetSettings(), vm_, vm_->GetVMData()->GetIsolateSnapshot(),
496  on_create_platform_view, on_create_rasterizer,
497  [engine = this->engine_.get(), initial_route](
498  Engine::Delegate& delegate,
499  const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm,
500  fml::RefPtr<const DartSnapshot> isolate_snapshot,
501  TaskRunners task_runners, const PlatformData& platform_data,
502  Settings settings, std::unique_ptr<Animator> animator,
503  fml::WeakPtr<IOManager> io_manager,
504  fml::RefPtr<SkiaUnrefQueue> unref_queue,
505  fml::WeakPtr<SnapshotDelegate> snapshot_delegate,
506  std::shared_ptr<VolatilePathTracker> volatile_path_tracker) {
507  return engine->Spawn(/*delegate=*/delegate,
508  /*dispatcher_maker=*/dispatcher_maker,
509  /*settings=*/settings,
510  /*animator=*/std::move(animator),
511  /*initial_route=*/initial_route);
512  },
513  is_gpu_disabled));
514  result->shared_resource_context_ = io_manager_->GetSharedResourceContext();
515  result->RunEngine(std::move(run_configuration));
516  return result;
517 }
fml::WeakPtr< IOManager > io_manager_
#define FML_DCHECK(condition)
Definition: logging.h:86
GAsyncResult * result
std::function< std::unique_ptr< PointerDataDispatcher >(PointerDataDispatcher::Delegate &)> PointerDataDispatcherMaker
Signature for constructing PointerDataDispatcher.
TaskRunners task_runners_
const Settings & GetSettings() const
Definition: shell.cc:668
std::shared_ptr< const DartVMData > GetVMData() const
The VM and isolate snapshots used by this running Dart VM instance.
Definition: dart_vm.cc:502
std::shared_ptr< const fml::SyncSwitch > GetIsGpuDisabledSyncSwitch() const override
Accessor for the disable GPU SyncSwitch.
Definition: shell.cc:1823
Represents the 2 code paths available when calling |SyncSwitch::Execute|.
Definition: sync_switch.h:24

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

References FML_DCHECK, flutter::TaskRunners::GetRasterTaskRunner(), flutter::TaskRunners::GetUITaskRunner(), fml::kDeadlineExceeded, fml::kFailedPrecondition, fml::TaskRunner::RunsTasksOnCurrentThread(), and fml::TimeDelta::ToMilliseconds().

Referenced by FlutterViewController::setFlutterViewDidRenderCallback:.

1764  {
1765  FML_DCHECK(is_setup_);
1766  if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() ||
1767  task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) {
1769  "WaitForFirstFrame called from thread that can't wait "
1770  "because it is responsible for generating the frame.");
1771  }
1772 
1773  // Check for overflow.
1774  auto now = std::chrono::steady_clock::now();
1775  auto max_duration = std::chrono::steady_clock::time_point::max() - now;
1776  auto desired_duration = std::chrono::milliseconds(timeout.ToMilliseconds());
1777  auto duration =
1778  now + (desired_duration > max_duration ? max_duration : desired_duration);
1779 
1780  std::unique_lock<std::mutex> lock(waiting_for_first_frame_mutex_);
1781  bool success = waiting_for_first_frame_condition_.wait_until(
1782  lock, duration, [&waiting_for_first_frame = waiting_for_first_frame_] {
1783  return !waiting_for_first_frame.load();
1784  });
1785  if (success) {
1786  return fml::Status();
1787  } else {
1789  }
1790 }
#define FML_DCHECK(condition)
Definition: logging.h:86
constexpr int64_t ToMilliseconds() const
Definition: time_delta.h:63
TaskRunners task_runners_

Friends And Related Function Documentation

◆ testing::ShellTest

friend class testing::ShellTest
friend

Definition at line 691 of file shell.h.


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