5#ifndef FLUTTER_SHELL_COMMON_SHELL_H_
6#define FLUTTER_SHELL_COMMON_SHELL_H_
11#include <unordered_map>
13#include "flutter/assets/directory_asset_bundle.h"
14#include "flutter/common/graphics/texture.h"
15#include "flutter/common/settings.h"
16#include "flutter/common/task_runners.h"
17#include "flutter/flow/surface.h"
18#include "flutter/fml/closure.h"
19#include "flutter/fml/macros.h"
20#include "flutter/fml/memory/ref_ptr.h"
21#include "flutter/fml/memory/thread_checker.h"
22#include "flutter/fml/memory/weak_ptr.h"
23#include "flutter/fml/status.h"
24#include "flutter/fml/synchronization/sync_switch.h"
25#include "flutter/fml/synchronization/waitable_event.h"
26#include "flutter/fml/thread.h"
27#include "flutter/fml/time/time_point.h"
28#include "flutter/lib/ui/painting/image_generator_registry.h"
29#include "flutter/lib/ui/semantics/custom_accessibility_action.h"
30#include "flutter/lib/ui/semantics/semantics_node.h"
31#include "flutter/lib/ui/volatile_path_tracker.h"
32#include "flutter/lib/ui/window/platform_message.h"
33#include "flutter/runtime/dart_vm_lifecycle.h"
34#include "flutter/runtime/platform_data.h"
35#include "flutter/runtime/service_protocol.h"
36#include "flutter/shell/common/animator.h"
37#include "flutter/shell/common/display_manager.h"
38#include "flutter/shell/common/engine.h"
39#include "flutter/shell/common/platform_view.h"
40#include "flutter/shell/common/rasterizer.h"
41#include "flutter/shell/common/resource_cache_limit_calculator.h"
42#include "flutter/shell/common/shell_io_manager.h"
120 typedef std::function<std::unique_ptr<Engine>(
128 std::unique_ptr<Animator> animator,
132 std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
133 const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch,
168 static std::unique_ptr<Shell>
Create(
174 bool is_gpu_disabled =
false);
202 std::unique_ptr<Shell>
Spawn(
204 const std::string& initial_route,
411 const std::shared_ptr<fml::ConcurrentTaskRunner>
425 static std::pair<DartVMRef, fml::RefPtr<const DartSnapshot>>
429 using ServiceProtocolHandler =
431 rapidjson::Document*)>;
437 std::mutex misbehaving_message_channels_mutex_;
438 std::set<std::string> misbehaving_message_channels_;
441 std::shared_ptr<ResourceCacheLimitCalculator>
442 resource_cache_limit_calculator_;
443 size_t resource_cache_limit_;
446 mutable std::mutex time_recorder_mutex_;
447 std::optional<fml::TimePoint> latest_frame_target_time_;
448 std::unique_ptr<PlatformView> platform_view_;
449 std::unique_ptr<Engine> engine_;
450 std::unique_ptr<Rasterizer> rasterizer_;
451 std::shared_ptr<ShellIOManager> io_manager_;
452 std::shared_ptr<fml::SyncSwitch> is_gpu_disabled_sync_switch_;
453 std::shared_ptr<VolatilePathTracker> volatile_path_tracker_;
454 std::shared_ptr<PlatformMessageHandler> platform_message_handler_;
455 std::atomic<bool> route_messages_through_platform_thread_ =
false;
463 std::unordered_map<std::string_view,
464 std::pair<fml::RefPtr<fml::TaskRunner>,
465 ServiceProtocolHandler>
468 service_protocol_handlers_;
469 bool is_set_up_ =
false;
470 bool is_added_to_service_protocol_ =
false;
471 uint64_t next_pointer_flow_id_ = 0;
473 bool first_frame_rasterized_ =
false;
474 std::atomic<bool> waiting_for_first_frame_ =
true;
475 std::mutex waiting_for_first_frame_mutex_;
476 std::condition_variable waiting_for_first_frame_condition_;
480 std::atomic<bool> needs_report_timings_{
false};
484 bool frame_timings_report_scheduled_ =
false;
489 std::vector<int64_t> unreported_timings_;
493 std::unique_ptr<DisplayManager> display_manager_;
497 std::mutex resize_mutex_;
501 std::unordered_map<int64_t, SkISize> expected_frame_sizes_;
504 double device_pixel_ratio_ = 0.0;
507 size_t UnreportedFramesCount()
const;
512 const std::shared_ptr<ResourceCacheLimitCalculator>&
513 resource_cache_limit_calculator,
515 std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
516 bool is_gpu_disabled);
518 static std::unique_ptr<Shell> CreateShellOnPlatformThread(
521 std::shared_ptr<ShellIOManager> parent_io_manager,
522 const std::shared_ptr<ResourceCacheLimitCalculator>&
523 resource_cache_limit_calculator,
531 bool is_gpu_disabled);
533 static std::unique_ptr<Shell> CreateWithSnapshot(
537 const std::shared_ptr<ShellIOManager>& parent_io_manager,
538 const std::shared_ptr<ResourceCacheLimitCalculator>&
539 resource_cache_limit_calculator,
543 const CreateCallback<PlatformView>& on_create_platform_view,
544 const CreateCallback<Rasterizer>& on_create_rasterizer,
546 bool is_gpu_disabled);
549 std::unique_ptr<Engine>
engine,
550 std::unique_ptr<Rasterizer> rasterizer,
551 const std::shared_ptr<ShellIOManager>& io_manager);
553 void ReportTimings();
580 std::unique_ptr<PlatformMessage>
message)
override;
584 std::unique_ptr<PointerDataPacket> packet)
override;
599 std::shared_ptr<flutter::Texture>
texture)
override;
615 intptr_t loading_unit_id,
616 std::unique_ptr<const fml::Mapping> snapshot_data,
617 std::unique_ptr<const fml::Mapping> snapshot_instructions)
override;
620 const std::string error_message,
621 bool transient)
override;
625 std::unique_ptr<AssetResolver> updated_asset_resolver,
630 uint64_t frame_number)
override;
640 void OnAnimatorDraw(std::shared_ptr<FramePipeline> pipeline)
override;
644 std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder)
override;
653 std::unique_ptr<PlatformMessage>
message)
override;
655 void HandleEngineSkiaMessage(std::unique_ptr<PlatformMessage>
message);
665 int64_t isolate_port)
override;
672 const std::vector<std::string>& supported_locale_data)
override;
685 int configuration_id)
const override;
702 std::string_view method)
const override;
706 std::string_view method,
708 rapidjson::Document* response)
override;
715 bool OnServiceProtocolScreenshot(
717 rapidjson::Document* response);
720 bool OnServiceProtocolScreenshotSKP(
722 rapidjson::Document* response);
725 bool OnServiceProtocolRunInView(
727 rapidjson::Document* response);
730 bool OnServiceProtocolFlushUIThreadTasks(
732 rapidjson::Document* response);
735 bool OnServiceProtocolSetAssetBundlePath(
737 rapidjson::Document* response);
740 bool OnServiceProtocolGetDisplayRefreshRate(
742 rapidjson::Document* response);
748 bool OnServiceProtocolGetSkSLs(
750 rapidjson::Document* response);
753 bool OnServiceProtocolEstimateRasterCacheMemory(
755 rapidjson::Document* response);
762 bool OnServiceProtocolRenderFrameWithRasterStats(
764 rapidjson::Document* response);
770 bool OnServiceProtocolReloadAssetFonts(
772 rapidjson::Document* response);
775 void SendFontChangeNotification();
782 std::unique_ptr<DirectoryAssetBundle> RestoreOriginalAssetResolver();
784 SkISize ExpectedFrameSize(int64_t view_id);
788 std::unique_ptr<fml::TaskRunnerAffineWeakPtrFactory<Shell>> weak_factory_gpu_;
static sk_sp< Effect > Create()
AssetResolverType
Identifies the type of AssetResolver an instance is.
Describes a running instance of the Dart VM. There may only be one running instance of the Dart VM in...
While the engine operates entirely on the UI task runner, it needs the capabilities of the other comp...
RunStatus
Indicates the result of the call to Engine::Run.
Used to forward events from the rasterizer to interested subsystems. Currently, the shell sets itself...
ScreenshotType
The type of the screenshot to obtain of the previously rendered layer tree.
Specifies all the configuration required by the runtime library to launch the root isolate....
std::map< std::string_view, std::string_view > ServiceProtocolMap
DartVM * GetDartVM()
Get a pointer to the Dart VM used by this running shell instance.
void OnAnimatorBeginFrame(fml::TimePoint frame_target_time, uint64_t frame_number) override
void OnAnimatorDrawLastLayerTrees(std::unique_ptr< FrameTimingsRecorder > frame_timings_recorder) override
void OnAnimatorDraw(std::shared_ptr< FramePipeline > pipeline) override
void UpdateAssetResolverByType(std::unique_ptr< AssetResolver > updated_asset_resolver, AssetResolver::AssetResolverType type) override
Replaces the asset resolver handled by the engine's AssetManager of the specified type with updated_a...
void OnPlatformViewScheduleFrame() override
Notifies the delegate that the platform needs to schedule a frame to regenerate the layer tree and re...
void LoadDartDeferredLibraryError(intptr_t loading_unit_id, const std::string error_message, bool transient) override
Indicates to the dart VM that the request to load a deferred library with the specified loading unit ...
std::optional< DartErrorCode > GetUIIsolateLastError() const
Used by embedders to get the last error from the Dart UI Isolate, if one exists.
void OnPlatformViewSetNextFrameCallback(const fml::closure &closure) override
Notifies the delegate that the specified callback needs to be invoked after the rasterizer is done re...
void OnAnimatorUpdateLatestFrameTargetTime(fml::TimePoint frame_target_time) override
void OnEngineUpdateSemantics(SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions) override
When the accessibility tree has been updated by the Flutter application, this new information needs t...
void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override
Notifies the delegate that the embedder has expressed an opinion about the features to enable in the ...
bool EngineHasLivePorts() const
Used by embedders to check if the Engine is running and has any live ports remaining....
void OnPlatformViewDestroyed() override
Notifies the delegate that the platform view was destroyed. This is usually a sign to the rasterizer ...
double GetScaledFontSize(double unscaled_font_size, int configuration_id) const override
Synchronously invokes platform-specific APIs to apply the system text scaling on the given unscaled f...
~Shell()
Destroys the shell. This is a synchronous operation and synchronous barrier blocks are introduced on ...
Rasterizer::Screenshot Screenshot(Rasterizer::ScreenshotType type, bool base64_encode)
Captures a screenshot and optionally Base64 encodes the data of the last layer tree rendered by the r...
void OnPlatformViewDispatchSemanticsAction(int32_t node_id, SemanticsAction action, fml::MallocMapping args) override
Notifies the delegate that the platform view has encountered an accessibility related action on the s...
void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override
Notifies the delegate that the embedder has updated the contents of the texture with the specified id...
void OnFrameRasterized(const FrameTiming &) override
Notifies the delegate that a frame has been rendered. The rasterizer collects profiling information f...
void UpdateIsolateDescription(const std::string isolate_name, int64_t isolate_port) override
Notifies the shell of the name of the root isolate and its port when that isolate is launched,...
static std::pair< DartVMRef, fml::RefPtr< const DartSnapshot > > InferVmInitDataFromSettings(Settings &settings)
void OnPlatformViewSetViewportMetrics(int64_t view_id, const ViewportMetrics &metrics) override
Notifies the delegate the viewport metrics of a view have been updated. The rasterizer will need to b...
fml::WeakPtr< ShellIOManager > GetIOManager()
The IO Manager may only be accessed on the IO task runner.
void RequestDartDeferredLibrary(intptr_t loading_unit_id) override
Invoked when the Dart VM requests that a deferred library be loaded. Notifies the engine that the def...
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the raster task runner.
void OnPlatformViewCreated(std::unique_ptr< Surface > surface) override
Notifies the delegate that the platform view was created with the given render surface....
void OnPlatformViewUnregisterTexture(int64_t texture_id) override
Notifies the delegate that the embedder will no longer attempt to composite the specified texture wit...
void RunEngine(RunConfiguration run_configuration)
Starts an isolate for the given RunConfiguration.
void OnAnimatorNotifyIdle(fml::TimeDelta deadline) override
fml::TimePoint GetLatestFrameTargetTime() const override
void SetNeedsReportTimings(bool value) override
Notifies the shell that the application has an opinion about whether its frame timings need to be rep...
std::unique_ptr< Shell > Spawn(RunConfiguration run_configuration, const std::string &initial_route, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer) const
Creates one Shell from another Shell where the created Shell takes the opportunity to share any inter...
const std::weak_ptr< VsyncWaiter > GetVsyncWaiter() const
fml::Milliseconds GetFrameBudget() override
const std::shared_ptr< PlatformMessageHandler > & GetPlatformMessageHandler() const override
Returns the delegate object that handles PlatformMessage's from Flutter to the host platform (and its...
std::unique_ptr< std::vector< std::string > > ComputePlatformResolvedLocale(const std::vector< std::string > &supported_locale_data) override
Directly invokes platform-specific APIs to compute the locale the platform would have natively resolv...
const std::shared_ptr< fml::ConcurrentTaskRunner > GetConcurrentWorkerTaskRunner() const
void NotifyLowMemoryWarning() const
Used by embedders to notify that there is a low memory warning. The shell will attempt to purge cache...
void OnPlatformViewRegisterTexture(std::shared_ptr< flutter::Texture > texture) override
fml::WeakPtr< Engine > GetEngine()
Engines may only be accessed on the UI thread. This method is deprecated, and implementers should ins...
void OnPreEngineRestart() override
Notifies the delegate that the root isolate of the application is about to be discarded and a new iso...
std::function< std::unique_ptr< Engine >(Engine::Delegate &delegate, const PointerDataDispatcherMaker &dispatcher_maker, DartVM &vm, fml::RefPtr< const DartSnapshot > isolate_snapshot, TaskRunners task_runners, const PlatformData &platform_data, Settings settings, std::unique_ptr< Animator > animator, fml::WeakPtr< IOManager > io_manager, fml::RefPtr< SkiaUnrefQueue > unref_queue, fml::TaskRunnerAffineWeakPtr< SnapshotDelegate > snapshot_delegate, std::shared_ptr< VolatilePathTracker > volatile_path_tracker, const std::shared_ptr< fml::SyncSwitch > &gpu_disabled_switch, impeller::RuntimeStageBackend runtime_stage_type)> EngineCreateCallback
void OnPlatformViewSetSemanticsEnabled(bool enabled) override
Notifies the delegate that the embedder has expressed an opinion about whether the accessibility tree...
const Settings & GetSettings() const override
fml::Status WaitForFirstFrame(fml::TimeDelta timeout)
Pauses the calling thread until the first frame is presented.
void OnEngineHandlePlatformMessage(std::unique_ptr< PlatformMessage > message) override
When the Flutter application has a message to send to the underlying platform, the message needs to b...
fml::RefPtr< fml::TaskRunner > GetServiceProtocolHandlerTaskRunner(std::string_view method) const override
void OnPlatformViewDispatchPointerDataPacket(std::unique_ptr< PointerDataPacket > packet) override
Notifies the delegate that the platform view has encountered a pointer event. This pointer event need...
void OnDisplayUpdates(std::vector< std::unique_ptr< Display > > displays)
Notifies the display manager of the updates.
const TaskRunners & GetTaskRunners() const override
If callers wish to interact directly with any shell subcomponents, they must (on the platform thread)...
bool HandleServiceProtocolMessage(std::string_view method, const ServiceProtocolMap ¶ms, rapidjson::Document *response) override
std::shared_ptr< const fml::SyncSwitch > GetIsGpuDisabledSyncSwitch() const override
Accessor for the disable GPU SyncSwitch.
void OnRootIsolateCreated() override
Notifies the shell that the root isolate is created. Currently, this information is to add to the ser...
void OnPlatformViewDispatchPlatformMessage(std::unique_ptr< PlatformMessage > message) override
Notifies the delegate that the platform has dispatched a platform message from the embedder to the Fl...
const Settings & OnPlatformViewGetSettings() const override
Called by the platform view on the platform thread to get the settings object associated with the pla...
void SetGpuAvailability(GpuAvailability availability)
Marks the GPU as available or unavailable.
void OnPlatformViewAddView(int64_t view_id, const ViewportMetrics &viewport_metrics, AddViewCallback callback) override
Allocate resources for a new non-implicit view and inform Dart about the view, and on success,...
void OnPlatformViewRemoveView(int64_t view_id, RemoveViewCallback callback) override
Deallocate resources for a removed view and inform Dart about the removal.
void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority)
Install a new factory that can match against and decode image data.
fml::TimePoint GetCurrentTimePoint() override
Returns the current fml::TimePoint. This method is primarily provided to allow tests to control Any m...
const fml::RefPtr< fml::RasterThreadMerger > GetParentRasterThreadMerger() const override
Getting the raster thread merger from parent shell, it can be a null RefPtr when it's a root Shell or...
std::function< std::unique_ptr< T >(Shell &)> CreateCallback
bool IsSetup() const
Used by embedders to check if all shell subcomponents are initialized. It is the embedder's responsib...
double GetMainDisplayRefreshRate()
Queries the DisplayManager for the main display refresh rate.
void OnEngineChannelUpdate(std::string name, bool listening) override
Invoked when a listener is registered on a platform channel.
bool ReloadSystemFonts()
Used by embedders to reload the system fonts in FontCollection. It also clears the cached font famili...
bool ShouldDiscardLayerTree(int64_t view_id, const flutter::LayerTree &tree) override
void LoadDartDeferredLibrary(intptr_t loading_unit_id, std::unique_ptr< const fml::Mapping > snapshot_data, std::unique_ptr< const fml::Mapping > snapshot_instructions) override
Loads the dart shared library into the dart VM. When the dart library is loaded successfully,...
fml::WeakPtr< PlatformView > GetPlatformView()
Platform views may only be accessed on the platform task runner.
size_t GetResourceCacheLimit() override
ServiceProtocol::Handler::Description GetServiceProtocolDescription() const override
A Mapping like NonOwnedMapping, but uses Free as its release proc.
const EmbeddedViewParams * params
FlutterSemanticsFlag flags
G_BEGIN_DECLS G_MODULE_EXPORT FlValue * args
FlKeyEvent uint64_t FlKeyResponderAsyncCallback callback
#define FML_DISALLOW_COPY_AND_ASSIGN(TypeName)
DartErrorCode
Error exit codes for the Dart isolate.
@ CompilationError
The Dart error code for a compilation error.
@ ApiError
The Dart error code for an API error.
@ NoError
No error has occurred.
@ UnknownError
The Dart error code for an unknown error.
std::unordered_map< int32_t, SemanticsNode > SemanticsNodeUpdates
std::function< std::shared_ptr< ImageGenerator >(sk_sp< SkData > buffer)> ImageGeneratorFactory
ImageGeneratorFactory is the top level primitive for specifying an image decoder in Flutter....
std::unordered_map< int32_t, CustomAccessibilityAction > CustomAccessibilityActionUpdates
std::function< std::unique_ptr< PointerDataDispatcher >(PointerDataDispatcher::Delegate &)> PointerDataDispatcherMaker
Signature for constructing PointerDataDispatcher.
DEF_SWITCHES_START aot vmservice shared library name
GpuAvailability
Values for |Shell::SetGpuAvailability|.
@ kFlushAndMakeUnavailable
@ kAvailable
Indicates that GPU operations should be permitted.
std::chrono::duration< double, std::milli > Milliseconds
std::function< void()> closure
A POD type used to return the screenshot data along with the size of the frame.