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 &)>
 
- 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...
 
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 GPU 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 setup 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< fml::SyncSwitchGetIsGpuDisabledSyncSwitch () const override
 Accessor for the disable GPU SyncSwitch. 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 (TaskRunners task_runners, Settings settings, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer)
 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...
 
static std::unique_ptr< ShellCreate (TaskRunners task_runners, const PlatformData platform_data, Settings settings, CreateCallback< PlatformView > on_create_platform_view, CreateCallback< Rasterizer > on_create_rasterizer)
 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. Unlike the simpler variant of this factory method, this method allows for specification of window data. If this is the first instance of a shell in the process, this call also bootstraps the Dart VM. More...
 
static std::unique_ptr< ShellCreate (TaskRunners task_runners, const PlatformData platform_data, Settings settings, fml::RefPtr< const DartSnapshot > isolate_snapshot, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer, DartVMRef vm)
 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. Unlike the simpler variant of this factory method, this method allows for the specification of an isolate snapshot that cannot be adequately described in the settings. This call also requires the specification of a running VM instance. 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 92 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 99 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 386 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().

386  {
388  task_runners_.GetIOTaskRunner());
389 
390  vm_->GetServiceProtocol()->RemoveHandler(this);
391 
392  fml::AutoResetWaitableEvent ui_latch, gpu_latch, platform_latch, io_latch;
393 
395  task_runners_.GetUITaskRunner(),
396  fml::MakeCopyable([engine = std::move(engine_), &ui_latch]() mutable {
397  engine.reset();
398  ui_latch.Signal();
399  }));
400  ui_latch.Wait();
401 
403  task_runners_.GetRasterTaskRunner(),
405  [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable {
406  rasterizer.reset();
407  this->weak_factory_gpu_.reset();
408  gpu_latch.Signal();
409  }));
410  gpu_latch.Wait();
411 
413  task_runners_.GetIOTaskRunner(),
414  fml::MakeCopyable([io_manager = std::move(io_manager_),
415  platform_view = platform_view_.get(),
416  &io_latch]() mutable {
417  io_manager.reset();
418  if (platform_view) {
419  platform_view->ReleaseResourceContext();
420  }
421  io_latch.Signal();
422  }));
423 
424  io_latch.Wait();
425 
426  // The platform view must go last because it may be holding onto platform side
427  // counterparts to resources owned by subsystems running on other threads. For
428  // example, the NSOpenGLContext on the Mac.
430  task_runners_.GetPlatformTaskRunner(),
431  fml::MakeCopyable([platform_view = std::move(platform_view_),
432  &platform_latch]() mutable {
433  platform_view.reset();
434  platform_latch.Signal();
435  }));
436  platform_latch.Wait();
437 }
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:493
static void RunNowOrPostTask(fml::RefPtr< fml::TaskRunner > runner, const fml::closure &task)
Definition: task_runner.cc:55
fml::RefPtr< fml::TaskRunner > GetPlatformTaskRunner() const
Definition: task_runners.cc:30
fml::RefPtr< fml::TaskRunner > GetRasterTaskRunner() const
Definition: task_runners.cc:42
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition: make_copyable.h:57
void RemoveWorkerTaskRunner(fml::RefPtr< fml::TaskRunner > task_runner)
fml::RefPtr< fml::TaskRunner > GetIOTaskRunner() const
Definition: task_runners.cc:38
fml::RefPtr< fml::TaskRunner > GetUITaskRunner() const
Definition: task_runners.cc:34
static PersistentCache * GetCacheForProcess()

Member Function Documentation

◆ Create() [1/3]

std::unique_ptr< Shell > flutter::Shell::Create ( TaskRunners  task_runners,
Settings  settings,
const CreateCallback< PlatformView > &  on_create_platform_view,
const CreateCallback< Rasterizer > &  on_create_rasterizer 
)
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.

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

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

243  {
244  return Shell::Create(std::move(task_runners), //
245  PlatformData{/* default platform data */}, //
246  std::move(settings), //
247  std::move(on_create_platform_view), //
248  std::move(on_create_rasterizer) //
249  );
250 }
static std::unique_ptr< Shell > Create(TaskRunners task_runners, Settings settings, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer)
Creates a shell instance using the provided settings. The callbacks to create the various shell subco...
Definition: shell.cc:239

◆ Create() [2/3]

std::unique_ptr< Shell > flutter::Shell::Create ( TaskRunners  task_runners,
const PlatformData  platform_data,
Settings  settings,
Shell::CreateCallback< PlatformView on_create_platform_view,
Shell::CreateCallback< Rasterizer on_create_rasterizer 
)
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. Unlike the simpler variant of this factory method, this method allows for specification of window data. If this is the first instance of a shell in the process, this call also bootstraps the Dart VM.

Parameters
[in]task_runnersThe task runners
[in]platform_dataThe default data for setting up ui.Window that attached to this intance.
[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.
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 252 of file shell.cc.

References flutter::Settings::cache_sksl, flutter::DartVMRef::Create(), Create(), FML_CHECK, flutter::PerformInitializationTasks(), flutter::PersistentCache::SetCacheSkSL(), and TRACE_EVENT0.

257  {
258  PerformInitializationTasks(settings);
259  PersistentCache::SetCacheSkSL(settings.cache_sksl);
260 
261  TRACE_EVENT0("flutter", "Shell::Create");
262 
263  auto vm = DartVMRef::Create(settings);
264  FML_CHECK(vm) << "Must be able to initialize the VM.";
265 
266  auto vm_data = vm->GetVMData();
267 
268  return Shell::Create(std::move(task_runners), //
269  std::move(platform_data), //
270  std::move(settings), //
271  vm_data->GetIsolateSnapshot(), // isolate snapshot
272  on_create_platform_view, //
273  on_create_rasterizer, //
274  std::move(vm) //
275  );
276 }
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:75
static void SetCacheSkSL(bool value)
static void PerformInitializationTasks(Settings &settings)
Definition: shell.cc:193
static DartVMRef Create(Settings settings, fml::RefPtr< DartSnapshot > vm_snapshot=nullptr, fml::RefPtr< DartSnapshot > isolate_snapshot=nullptr)
#define FML_CHECK(condition)
Definition: logging.h:68
static std::unique_ptr< Shell > Create(TaskRunners task_runners, Settings settings, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer)
Creates a shell instance using the provided settings. The callbacks to create the various shell subco...
Definition: shell.cc:239

◆ Create() [3/3]

std::unique_ptr< Shell > flutter::Shell::Create ( TaskRunners  task_runners,
const PlatformData  platform_data,
Settings  settings,
fml::RefPtr< const DartSnapshot isolate_snapshot,
const CreateCallback< PlatformView > &  on_create_platform_view,
const CreateCallback< Rasterizer > &  on_create_rasterizer,
DartVMRef  vm 
)
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. Unlike the simpler variant of this factory method, this method allows for the specification of an isolate snapshot that cannot be adequately described in the settings. This call also requires the specification of a running VM instance.

Parameters
[in]task_runnersThe task runners
[in]platform_dataThe default data for setting up ui.Window that attached to this intance.
[in]settingsThe settings
[in]isolate_snapshotA custom isolate snapshot. Takes precedence over any snapshots specified in the 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]vmA running VM instance.
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 278 of file shell.cc.

References flutter::Settings::cache_sksl, FML_CHECK, FML_DCHECK, flutter::TaskRunners::GetIOTaskRunner(), flutter::TaskRunners::GetPlatformTaskRunner(), flutter::TaskRunners::GetRasterTaskRunner(), flutter::TaskRunners::GetUITaskRunner(), 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(), flutter::PerformInitializationTasks(), fml::TaskRunner::RunNowOrPostTask(), fml::TaskRunner::RunsTasksOnCurrentThread(), flutter::PersistentCache::SetCacheSkSL(), fml::AutoResetWaitableEvent::Signal(), TRACE_EVENT0, and fml::AutoResetWaitableEvent::Wait().

285  {
286  PerformInitializationTasks(settings);
287  PersistentCache::SetCacheSkSL(settings.cache_sksl);
288 
289  TRACE_EVENT0("flutter", "Shell::CreateWithSnapshots");
290 
291  if (!task_runners.IsValid() || !on_create_platform_view ||
292  !on_create_rasterizer) {
293  return nullptr;
294  }
295 
297  std::unique_ptr<Shell> shell;
299  task_runners.GetPlatformTaskRunner(),
300  fml::MakeCopyable([&latch, //
301  vm = std::move(vm), //
302  &shell, //
303  task_runners = std::move(task_runners), //
304  platform_data, //
305  settings, //
306  isolate_snapshot = std::move(isolate_snapshot), //
307  on_create_platform_view, //
308  on_create_rasterizer //
309  ]() mutable {
310  shell = CreateShellOnPlatformThread(std::move(vm),
311  std::move(task_runners), //
312  platform_data, //
313  settings, //
314  std::move(isolate_snapshot), //
315  on_create_platform_view, //
316  on_create_rasterizer //
317  );
318  latch.Signal();
319  }));
320  latch.Wait();
321  return shell;
322 }
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:75
static void RunNowOrPostTask(fml::RefPtr< fml::TaskRunner > runner, const fml::closure &task)
Definition: task_runner.cc:55
static void SetCacheSkSL(bool value)
static void PerformInitializationTasks(Settings &settings)
Definition: shell.cc:193
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition: make_copyable.h:57

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

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

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

518  {
519  FML_DCHECK(is_setup_);
521 
522  if (!weak_engine_) {
523  return false;
524  }
525 
526  return weak_engine_->UIIsolateHasLivePorts();
527 }
#define FML_DCHECK(condition)
Definition: logging.h:86
fml::RefPtr< fml::TaskRunner > GetUITaskRunner() const
Definition: task_runners.cc:34
virtual bool RunsTasksOnCurrentThread()
Definition: task_runner.cc:43

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

References FML_DCHECK.

592  {
593  FML_DCHECK(is_setup_);
594  return weak_engine_;
595 }
#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 602 of file shell.cc.

References FML_DCHECK.

602  {
603  FML_DCHECK(is_setup_);
604  return io_manager_->GetWeakPtr();
605 }
#define FML_DCHECK(condition)
Definition: logging.h:86

◆ GetIsGpuDisabledSyncSwitch()

std::shared_ptr< fml::SyncSwitch > flutter::Shell::GetIsGpuDisabledSyncSwitch ( ) const
overridevirtual

Accessor for the disable GPU SyncSwitch.

Implements flutter::Rasterizer::Delegate.

Definition at line 1660 of file shell.cc.

1660  {
1661  return is_gpu_disabled_sync_switch_;
1662 }

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

597  {
598  FML_DCHECK(is_setup_);
599  return weak_platform_view_;
600 }
#define FML_DCHECK(condition)
Definition: logging.h:86

◆ GetRasterizer()

fml::TaskRunnerAffineWeakPtr< Rasterizer > flutter::Shell::GetRasterizer ( ) const

Rasterizers may only be accessed on the GPU task runner.

Returns
A weak pointer to the rasterizer.

Definition at line 587 of file shell.cc.

References FML_DCHECK.

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

587  {
588  FML_DCHECK(is_setup_);
589  return weak_rasterizer_;
590 }
#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 579 of file shell.cc.

579  {
580  return settings_;
581 }

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

Referenced by flutter::testing::ShellTest::CreateShell(), flutter::testing::ShellTest::DispatchPointerData(), flutter::testing::GetRasterizerResourceCacheBytesSync(), 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(), and flutter::testing::WaitForIO().

583  {
584  return task_runners_;
585 }

◆ 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 498 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.

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

498  {
499  FML_DCHECK(is_setup_);
501 
502  if (!weak_engine_) {
503  return std::nullopt;
504  }
505  switch (weak_engine_->GetUIIsolateLastError()) {
512  case tonic::kNoError:
513  return DartErrorCode::NoError;
514  }
516 }
#define FML_DCHECK(condition)
Definition: logging.h:86
The Dart error code for an API error.
The Dart error code for an unkonwn error.
fml::RefPtr< fml::TaskRunner > GetUITaskRunner() const
Definition: task_runners.cc:34
virtual bool RunsTasksOnCurrentThread()
Definition: task_runner.cc:43
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 setup must be discarded and another one created with updated settings.

Returns
Returns if the shell has been setup. Once set up, this does not change for the life-cycle of the shell.

Definition at line 529 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().

529  {
530  return is_setup_;
531 }

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

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

439  {
440  auto trace_id = fml::tracing::TraceNonce();
441  TRACE_EVENT_ASYNC_BEGIN0("flutter", "Shell::NotifyLowMemoryWarning",
442  trace_id);
443  // This does not require a current isolate but does require a running VM.
444  // Since a valid shell will not be returned to the embedder without a valid
445  // DartVMRef, we can be certain that this is a safe spot to assume a VM is
446  // running.
447  ::Dart_NotifyLowMemory();
448 
449  task_runners_.GetRasterTaskRunner()->PostTask(
450  [rasterizer = rasterizer_->GetWeakPtr(), trace_id = trace_id]() {
451  if (rasterizer) {
452  rasterizer->NotifyLowMemoryWarning();
453  }
454  TRACE_EVENT_ASYNC_END0("flutter", "Shell::NotifyLowMemoryWarning",
455  trace_id);
456  });
457  // The IO Manager uses resource cache limits of 0, so it is not necessary
458  // to purge them.
459 }
virtual void PostTask(const fml::closure &task)
Definition: task_runner.cc:24
#define TRACE_EVENT_ASYNC_BEGIN0(category_group, name, id)
Definition: trace_event.h:89
fml::RefPtr< fml::TaskRunner > GetRasterTaskRunner() const
Definition: task_runners.cc:42
#define TRACE_EVENT_ASYNC_END0(category_group, name, id)
Definition: trace_event.h:92
size_t TraceNonce()
Definition: trace_event.cc:291

◆ OnDisplayUpdates()

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

Notifies the display manager of the updates.

Definition at line 1664 of file shell.cc.

1665  {
1666  display_manager_->HandleDisplayUpdates(update_type, displays);
1667 }

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

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

1629  {
1630  FML_DCHECK(is_setup_);
1632 
1633  if (!engine_) {
1634  return false;
1635  }
1636  engine_->GetFontCollection().GetFontCollection()->SetupDefaultFontManager();
1637  engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache();
1638  // After system fonts are reloaded, we send a system channel message
1639  // to notify flutter framework.
1640  rapidjson::Document document;
1641  document.SetObject();
1642  auto& allocator = document.GetAllocator();
1643  rapidjson::Value message_value;
1644  message_value.SetString(kFontChange, allocator);
1645  document.AddMember(kTypeKey, message_value, allocator);
1646 
1647  rapidjson::StringBuffer buffer;
1648  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
1649  document.Accept(writer);
1650  std::string message = buffer.GetString();
1651  fml::RefPtr<PlatformMessage> fontsChangeMessage =
1652  fml::MakeRefCounted<flutter::PlatformMessage>(
1653  kSystemChannel, std::vector<uint8_t>(message.begin(), message.end()),
1654  nullptr);
1655 
1656  OnPlatformViewDispatchPlatformMessage(fontsChangeMessage);
1657  return true;
1658 }
#define FML_DCHECK(condition)
Definition: logging.h:86
fml::RefPtr< fml::TaskRunner > GetPlatformTaskRunner() const
Definition: task_runners.cc:30
constexpr char kSystemChannel[]
Definition: shell.cc:38
constexpr char kFontChange[]
Definition: shell.cc:40
virtual bool RunsTasksOnCurrentThread()
Definition: task_runner.cc:43
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 461 of file shell.cc.

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

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

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

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

467  {
468  auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(),
469  result_callback](Engine::RunStatus run_result) {
470  if (!result_callback) {
471  return;
472  }
473  platform_runner->PostTask(
474  [result_callback, run_result]() { result_callback(run_result); });
475  };
476  FML_DCHECK(is_setup_);
478 
480  task_runners_.GetUITaskRunner(),
482  [run_configuration = std::move(run_configuration),
483  weak_engine = weak_engine_, result]() mutable {
484  if (!weak_engine) {
485  FML_LOG(ERROR)
486  << "Could not launch engine with configuration - no engine.";
488  return;
489  }
490  auto run_result = weak_engine->Run(std::move(run_configuration));
491  if (run_result == flutter::Engine::RunStatus::Failure) {
492  FML_LOG(ERROR) << "Could not launch engine with configuration.";
493  }
494  result(run_result);
495  }));
496 }
#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
fml::RefPtr< fml::TaskRunner > GetPlatformTaskRunner() const
Definition: task_runners.cc:30
#define FML_LOG(severity)
Definition: logging.h:65
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition: make_copyable.h:57
fml::RefPtr< fml::TaskRunner > GetUITaskRunner() const
Definition: task_runners.cc:34
virtual bool RunsTasksOnCurrentThread()
Definition: task_runner.cc:43
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 1584 of file shell.cc.

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

1586  {
1587  TRACE_EVENT0("flutter", "Shell::Screenshot");
1589  Rasterizer::Screenshot screenshot;
1591  task_runners_.GetRasterTaskRunner(), [&latch, //
1592  rasterizer = GetRasterizer(), //
1593  &screenshot, //
1594  screenshot_type, //
1595  base64_encode //
1596  ]() {
1597  if (rasterizer) {
1598  screenshot = rasterizer->ScreenshotLastLayerTree(screenshot_type,
1599  base64_encode);
1600  }
1601  latch.Signal();
1602  });
1603  latch.Wait();
1604  return screenshot;
1605 }
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:75
static void RunNowOrPostTask(fml::RefPtr< fml::TaskRunner > runner, const fml::closure &task)
Definition: task_runner.cc:55
fml::RefPtr< fml::TaskRunner > GetRasterTaskRunner() const
Definition: task_runners.cc:42
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the GPU task runner.
Definition: shell.cc:587

◆ 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 1607 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:.

1607  {
1608  FML_DCHECK(is_setup_);
1609  if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() ||
1610  task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) {
1612  "WaitForFirstFrame called from thread that can't wait "
1613  "because it is responsible for generating the frame.");
1614  }
1615 
1616  std::unique_lock<std::mutex> lock(waiting_for_first_frame_mutex_);
1617  bool success = waiting_for_first_frame_condition_.wait_for(
1618  lock, std::chrono::milliseconds(timeout.ToMilliseconds()),
1619  [&waiting_for_first_frame = waiting_for_first_frame_] {
1620  return !waiting_for_first_frame.load();
1621  });
1622  if (success) {
1623  return fml::Status();
1624  } else {
1626  }
1627 }
#define FML_DCHECK(condition)
Definition: logging.h:86
constexpr int64_t ToMilliseconds() const
Definition: time_delta.h:63
fml::RefPtr< fml::TaskRunner > GetRasterTaskRunner() const
Definition: task_runners.cc:42
fml::RefPtr< fml::TaskRunner > GetUITaskRunner() const
Definition: task_runners.cc:34
virtual bool RunsTasksOnCurrentThread()
Definition: task_runner.cc:43

Friends And Related Function Documentation

◆ testing::ShellTest

friend class testing::ShellTest
friend

Definition at line 629 of file shell.h.


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