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 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...
 
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< Display > displays)
 Notifies the display manager of the updates. More...
 
double GetMainDisplayRefreshRate ()
 Queries the DisplayManager for the main display refresh rate. 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 106 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 113 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 127 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 432 of file shell.cc.

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

432  {
434  task_runners_.GetIOTaskRunner());
435 
436  vm_->GetServiceProtocol()->RemoveHandler(this);
437 
438  fml::AutoResetWaitableEvent ui_latch, gpu_latch, platform_latch, io_latch;
439 
441  task_runners_.GetUITaskRunner(),
442  fml::MakeCopyable([engine = std::move(engine_), &ui_latch]() mutable {
443  engine.reset();
444  ui_latch.Signal();
445  }));
446  ui_latch.Wait();
447 
449  task_runners_.GetRasterTaskRunner(),
451  [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable {
452  rasterizer.reset();
453  this->weak_factory_gpu_.reset();
454  gpu_latch.Signal();
455  }));
456  gpu_latch.Wait();
457 
459  task_runners_.GetIOTaskRunner(),
460  fml::MakeCopyable([io_manager = std::move(io_manager_),
461  platform_view = platform_view_.get(),
462  &io_latch]() mutable {
463  io_manager.reset();
464  if (platform_view) {
465  platform_view->ReleaseResourceContext();
466  }
467  io_latch.Signal();
468  }));
469 
470  io_latch.Wait();
471 
472  // The platform view must go last because it may be holding onto platform side
473  // counterparts to resources owned by subsystems running on other threads. For
474  // example, the NSOpenGLContext on the Mac.
476  task_runners_.GetPlatformTaskRunner(),
477  fml::MakeCopyable([platform_view = std::move(platform_view_),
478  &platform_latch]() mutable {
479  platform_view.reset();
480  platform_latch.Signal();
481  }));
482  platform_latch.Wait();
483 }
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:499
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 137 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(), 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().

143  {
144  // This must come first as it initializes tracing.
145  PerformInitializationTasks(settings);
146 
147  TRACE_EVENT0("flutter", "Shell::Create");
148 
149  // Always use the `vm_snapshot` and `isolate_snapshot` provided by the
150  // settings to launch the VM. If the VM is already running, the snapshot
151  // arguments are ignored.
152  auto vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings);
153  auto isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings);
154  auto vm = DartVMRef::Create(settings, vm_snapshot, isolate_snapshot);
155  FML_CHECK(vm) << "Must be able to initialize the VM.";
156 
157  // If the settings did not specify an `isolate_snapshot`, fall back to the
158  // one the VM was launched with.
159  if (!isolate_snapshot) {
160  isolate_snapshot = vm->GetVMData()->GetIsolateSnapshot();
161  }
162  return CreateWithSnapshot(std::move(platform_data), //
163  std::move(task_runners), //
164  std::move(settings), //
165  std::move(vm), //
166  std::move(isolate_snapshot), //
167  std::move(on_create_platform_view), //
168  std::move(on_create_rasterizer), //
169  CreateEngine, is_gpu_disabled);
170 }
#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 614 of file shell.cc.

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

614  {
615  FML_DCHECK(is_setup_);
616  FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread());
617 
618  if (!weak_engine_) {
619  return false;
620  }
621 
622  return weak_engine_->UIIsolateHasLivePorts();
623 }
#define FML_DCHECK(condition)
Definition: logging.h:86
TaskRunners task_runners_

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

References FML_DCHECK.

692  {
693  FML_DCHECK(is_setup_);
694  return weak_engine_;
695 }
#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 702 of file shell.cc.

References FML_DCHECK.

702  {
703  FML_DCHECK(is_setup_);
704  return io_manager_->GetWeakPtr();
705 }
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 1809 of file shell.cc.

Referenced by Spawn().

1810  {
1811  return is_gpu_disabled_sync_switch_;
1812 }

◆ GetMainDisplayRefreshRate()

◆ 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 697 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().

697  {
698  FML_DCHECK(is_setup_);
699  return weak_platform_view_;
700 }
#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 687 of file shell.cc.

References FML_DCHECK.

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

687  {
688  FML_DCHECK(is_setup_);
689  return weak_rasterizer_;
690 }
#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 679 of file shell.cc.

Referenced by Spawn().

679  {
680  return settings_;
681 }
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 683 of file shell.cc.

Referenced by flutter::testing::ShellTest::DispatchPointerData(), flutter::testing::GetRasterizerResourceCacheBytesSync(), InferMetalPlatformViewCreationCallback(), InferOpenGLPlatformViewCreationCallback(), InferSoftwarePlatformViewCreationCallback(), 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().

683  {
684  return task_runners_;
685 }
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 594 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.

594  {
595  FML_DCHECK(is_setup_);
596  FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread());
597 
598  if (!weak_engine_) {
599  return std::nullopt;
600  }
601  switch (weak_engine_->GetUIIsolateLastError()) {
608  case tonic::kNoError:
609  return DartErrorCode::NoError;
610  }
612 }
#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 625 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(), flutter::PersistentCache::Purge(), flutter::Settings::purge_persistent_cache, fml::TaskRunner::RunNowOrPostTask(), and flutter::PersistentCache::SetIsDumpingSkp().

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

625  {
626  return is_setup_;
627 }

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

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

535  {
536  auto trace_id = fml::tracing::TraceNonce();
537  TRACE_EVENT_ASYNC_BEGIN0("flutter", "Shell::NotifyLowMemoryWarning",
538  trace_id);
539  // This does not require a current isolate but does require a running VM.
540  // Since a valid shell will not be returned to the embedder without a valid
541  // DartVMRef, we can be certain that this is a safe spot to assume a VM is
542  // running.
543  ::Dart_NotifyLowMemory();
544 
545  task_runners_.GetRasterTaskRunner()->PostTask(
546  [rasterizer = rasterizer_->GetWeakPtr(), trace_id = trace_id]() {
547  if (rasterizer) {
548  rasterizer->NotifyLowMemoryWarning();
549  }
550  TRACE_EVENT_ASYNC_END0("flutter", "Shell::NotifyLowMemoryWarning",
551  trace_id);
552  });
553  // The IO Manager uses resource cache limits of 0, so it is not necessary
554  // to purge them.
555 }
#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< Display displays 
)

Notifies the display manager of the updates.

Definition at line 1838 of file shell.cc.

1839  {
1840  display_manager_->HandleDisplayUpdates(update_type, displays);
1841 }

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

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

1778  {
1779  FML_DCHECK(is_setup_);
1780  FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());
1781 
1782  if (!engine_) {
1783  return false;
1784  }
1785  engine_->GetFontCollection().GetFontCollection()->SetupDefaultFontManager();
1786  engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache();
1787  // After system fonts are reloaded, we send a system channel message
1788  // to notify flutter framework.
1789  rapidjson::Document document;
1790  document.SetObject();
1791  auto& allocator = document.GetAllocator();
1792  rapidjson::Value message_value;
1793  message_value.SetString(kFontChange, allocator);
1794  document.AddMember(kTypeKey, message_value, allocator);
1795 
1796  rapidjson::StringBuffer buffer;
1797  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
1798  document.Accept(writer);
1799  std::string message = buffer.GetString();
1800  fml::RefPtr<PlatformMessage> fontsChangeMessage =
1801  fml::MakeRefCounted<flutter::PlatformMessage>(
1802  kSystemChannel, std::vector<uint8_t>(message.begin(), message.end()),
1803  nullptr);
1804 
1805  OnPlatformViewDispatchPlatformMessage(fontsChangeMessage);
1806  return true;
1807 }
#define FML_DCHECK(condition)
Definition: logging.h:86
constexpr char kSystemChannel[]
Definition: shell.cc:38
constexpr char kFontChange[]
Definition: shell.cc:40
TaskRunners task_runners_
constexpr char kTypeKey[]
Definition: shell.cc:39

◆ RunEngine() [1/2]

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

Starts an isolate for the given RunConfiguration.

Definition at line 557 of file shell.cc.

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

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

◆ 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 561 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().

563  {
564  auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(),
565  result_callback](Engine::RunStatus run_result) {
566  if (!result_callback) {
567  return;
568  }
569  platform_runner->PostTask(
570  [result_callback, run_result]() { result_callback(run_result); });
571  };
572  FML_DCHECK(is_setup_);
573  FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());
574 
576  task_runners_.GetUITaskRunner(),
578  [run_configuration = std::move(run_configuration),
579  weak_engine = weak_engine_, result]() mutable {
580  if (!weak_engine) {
581  FML_LOG(ERROR)
582  << "Could not launch engine with configuration - no engine.";
584  return;
585  }
586  auto run_result = weak_engine->Run(std::move(run_configuration));
587  if (run_result == flutter::Engine::RunStatus::Failure) {
588  FML_LOG(ERROR) << "Could not launch engine with configuration.";
589  }
590  result(run_result);
591  }));
592 }
#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:82

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

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

1735  {
1736  TRACE_EVENT0("flutter", "Shell::Screenshot");
1738  Rasterizer::Screenshot screenshot;
1740  task_runners_.GetRasterTaskRunner(), [&latch, //
1741  rasterizer = GetRasterizer(), //
1742  &screenshot, //
1743  screenshot_type, //
1744  base64_encode //
1745  ]() {
1746  if (rasterizer) {
1747  screenshot = rasterizer->ScreenshotLastLayerTree(screenshot_type,
1748  base64_encode);
1749  }
1750  latch.Signal();
1751  });
1752  latch.Wait();
1753  return screenshot;
1754 }
#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:687
TaskRunners task_runners_

◆ SetGpuAvailability()

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

Marks the GPU as available or unavailable.

Definition at line 1814 of file shell.cc.

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

1814  {
1815  switch (availability) {
1817  is_gpu_disabled_sync_switch_->SetSwitch(false);
1818  return;
1822  task_runners_.GetIOTaskRunner(),
1823  [io_manager = io_manager_.get(), &latch]() {
1824  io_manager->GetSkiaUnrefQueue()->Drain();
1825  latch.Signal();
1826  });
1827  latch.Wait();
1828  }
1829  // FALLTHROUGH
1831  is_gpu_disabled_sync_switch_->SetSwitch(true);
1832  return;
1833  default:
1834  FML_DCHECK(false);
1835  }
1836 }
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 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 485 of file shell.cc.

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

488  {
489  FML_DCHECK(task_runners_.IsValid());
490  auto shell_maker = [&](bool is_gpu_disabled) {
491  std::unique_ptr<Shell> result(CreateWithSnapshot(
492  PlatformData{}, task_runners_, GetSettings(), vm_,
493  vm_->GetVMData()->GetIsolateSnapshot(), on_create_platform_view,
494  on_create_rasterizer,
495  [engine = this->engine_.get()](
496  Engine::Delegate& delegate,
497  const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm,
498  fml::RefPtr<const DartSnapshot> isolate_snapshot,
499  TaskRunners task_runners, const PlatformData& platform_data,
500  Settings settings, std::unique_ptr<Animator> animator,
501  fml::WeakPtr<IOManager> io_manager,
502  fml::RefPtr<SkiaUnrefQueue> unref_queue,
503  fml::WeakPtr<SnapshotDelegate> snapshot_delegate,
504  std::shared_ptr<VolatilePathTracker> volatile_path_tracker) {
505  return engine->Spawn(/*delegate=*/delegate,
506  /*dispatcher_maker=*/dispatcher_maker,
507  /*settings=*/settings,
508  /*animator=*/std::move(animator));
509  },
510  is_gpu_disabled));
511  return result;
512  };
513  std::unique_ptr<Shell> result;
514  GetIsGpuDisabledSyncSwitch()->Execute(
516  .SetIfFalse([&] { result = shell_maker(false); })
517  .SetIfTrue([&] { result = shell_maker(true); }));
518  result->shared_resource_context_ = io_manager_->GetSharedResourceContext();
519  result->RunEngine(std::move(run_configuration));
520 
521  task_runners_.GetRasterTaskRunner()->PostTask(
522  [rasterizer = rasterizer_->GetWeakPtr(),
523  spawn_rasterizer = result->rasterizer_->GetWeakPtr()]() {
524  if (rasterizer) {
525  rasterizer->BlockThreadMerging();
526  }
527  if (spawn_rasterizer) {
528  spawn_rasterizer->BlockThreadMerging();
529  }
530  });
531 
532  return result;
533 }
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:679
std::shared_ptr< const DartVMData > GetVMData() const
The VM and isolate snapshots used by this running Dart VM instance.
Definition: dart_vm.cc:491
std::shared_ptr< const fml::SyncSwitch > GetIsGpuDisabledSyncSwitch() const override
Accessor for the disable GPU SyncSwitch.
Definition: shell.cc:1809
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.

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 1756 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:.

1756  {
1757  FML_DCHECK(is_setup_);
1758  if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() ||
1759  task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) {
1761  "WaitForFirstFrame called from thread that can't wait "
1762  "because it is responsible for generating the frame.");
1763  }
1764 
1765  std::unique_lock<std::mutex> lock(waiting_for_first_frame_mutex_);
1766  bool success = waiting_for_first_frame_condition_.wait_for(
1767  lock, std::chrono::milliseconds(timeout.ToMilliseconds()),
1768  [&waiting_for_first_frame = waiting_for_first_frame_] {
1769  return !waiting_for_first_frame.load();
1770  });
1771  if (success) {
1772  return fml::Status();
1773  } else {
1775  }
1776 }
#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 648 of file shell.h.


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