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"
121 typedef std::function<std::unique_ptr<Engine>(
129 std::unique_ptr<Animator> animator,
133 std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
134 const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch,
169 static std::unique_ptr<Shell>
Create(
175 bool is_gpu_disabled =
false);
203 std::unique_ptr<Shell>
Spawn(
205 const std::string& initial_route,
412 const std::shared_ptr<fml::ConcurrentTaskRunner>
426 static std::pair<DartVMRef, fml::RefPtr<const DartSnapshot>>
430 using ServiceProtocolHandler =
432 rapidjson::Document*)>;
438 std::mutex misbehaving_message_channels_mutex_;
439 std::set<std::string> misbehaving_message_channels_;
442 std::shared_ptr<ResourceCacheLimitCalculator>
443 resource_cache_limit_calculator_;
444 size_t resource_cache_limit_;
447 mutable std::mutex time_recorder_mutex_;
448 std::optional<fml::TimePoint> latest_frame_target_time_;
449 std::unique_ptr<PlatformView> platform_view_;
450 std::unique_ptr<Engine> engine_;
451 std::unique_ptr<Rasterizer> rasterizer_;
452 std::shared_ptr<ShellIOManager> io_manager_;
453 std::shared_ptr<fml::SyncSwitch> is_gpu_disabled_sync_switch_;
454 std::shared_ptr<VolatilePathTracker> volatile_path_tracker_;
455 std::shared_ptr<PlatformMessageHandler> platform_message_handler_;
456 std::atomic<bool> route_messages_through_platform_thread_ =
false;
464 std::unordered_map<std::string_view,
465 std::pair<fml::RefPtr<fml::TaskRunner>,
466 ServiceProtocolHandler>
469 service_protocol_handlers_;
470 bool is_set_up_ =
false;
471 bool is_added_to_service_protocol_ =
false;
472 uint64_t next_pointer_flow_id_ = 0;
474 bool first_frame_rasterized_ =
false;
475 std::atomic<bool> waiting_for_first_frame_ =
true;
476 std::mutex waiting_for_first_frame_mutex_;
477 std::condition_variable waiting_for_first_frame_condition_;
481 std::atomic<bool> needs_report_timings_{
false};
485 bool frame_timings_report_scheduled_ =
false;
490 std::vector<int64_t> unreported_timings_;
494 std::unique_ptr<DisplayManager> display_manager_;
498 std::mutex resize_mutex_;
502 std::unordered_map<int64_t, SkISize> expected_frame_sizes_;
505 double device_pixel_ratio_ = 0.0;
508 size_t UnreportedFramesCount()
const;
513 const std::shared_ptr<ResourceCacheLimitCalculator>&
514 resource_cache_limit_calculator,
516 std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
517 bool is_gpu_disabled);
519 static std::unique_ptr<Shell> CreateShellOnPlatformThread(
522 std::shared_ptr<ShellIOManager> parent_io_manager,
523 const std::shared_ptr<ResourceCacheLimitCalculator>&
524 resource_cache_limit_calculator,
532 bool is_gpu_disabled);
534 static std::unique_ptr<Shell> CreateWithSnapshot(
538 const std::shared_ptr<ShellIOManager>& parent_io_manager,
539 const std::shared_ptr<ResourceCacheLimitCalculator>&
540 resource_cache_limit_calculator,
544 const CreateCallback<PlatformView>& on_create_platform_view,
545 const CreateCallback<Rasterizer>& on_create_rasterizer,
547 bool is_gpu_disabled);
550 std::unique_ptr<Engine>
engine,
551 std::unique_ptr<Rasterizer> rasterizer,
552 const std::shared_ptr<ShellIOManager>& io_manager);
554 void ReportTimings();
557 void OnPlatformViewCreated(std::unique_ptr<Surface>
surface)
override;
560 void OnPlatformViewDestroyed()
override;
563 void OnPlatformViewScheduleFrame()
override;
566 void OnPlatformViewAddView(int64_t view_id,
571 void OnPlatformViewRemoveView(int64_t view_id,
575 void OnPlatformViewSetViewportMetrics(
580 void OnPlatformViewDispatchPlatformMessage(
581 std::unique_ptr<PlatformMessage>
message)
override;
584 void OnPlatformViewDispatchPointerDataPacket(
585 std::unique_ptr<PointerDataPacket> packet)
override;
588 void OnPlatformViewDispatchSemanticsAction(int32_t node_id,
593 void OnPlatformViewSetSemanticsEnabled(
bool enabled)
override;
596 void OnPlatformViewSetAccessibilityFeatures(int32_t
flags)
override;
599 void OnPlatformViewRegisterTexture(
600 std::shared_ptr<flutter::Texture>
texture)
override;
603 void OnPlatformViewUnregisterTexture(int64_t
texture_id)
override;
606 void OnPlatformViewMarkTextureFrameAvailable(int64_t
texture_id)
override;
612 const Settings& OnPlatformViewGetSettings()
const override;
615 void LoadDartDeferredLibrary(
616 intptr_t loading_unit_id,
617 std::unique_ptr<const fml::Mapping> snapshot_data,
618 std::unique_ptr<const fml::Mapping> snapshot_instructions)
override;
620 void LoadDartDeferredLibraryError(intptr_t loading_unit_id,
621 const std::string error_message,
622 bool transient)
override;
625 void UpdateAssetResolverByType(
626 std::unique_ptr<AssetResolver> updated_asset_resolver,
631 uint64_t frame_number)
override;
637 void OnAnimatorUpdateLatestFrameTargetTime(
641 void OnAnimatorDraw(std::shared_ptr<FramePipeline> pipeline)
override;
644 void OnAnimatorDrawLastLayerTrees(
645 std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder)
override;
648 void OnEngineUpdateSemantics(
653 void OnEngineHandlePlatformMessage(
654 std::unique_ptr<PlatformMessage>
message)
override;
656 void HandleEngineSkiaMessage(std::unique_ptr<PlatformMessage>
message);
659 void OnPreEngineRestart()
override;
662 void OnRootIsolateCreated()
override;
665 void UpdateIsolateDescription(
const std::string isolate_name,
666 int64_t isolate_port)
override;
669 void SetNeedsReportTimings(
bool value)
override;
672 std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocale(
673 const std::vector<std::string>& supported_locale_data)
override;
676 void RequestDartDeferredLibrary(intptr_t loading_unit_id)
override;
682 void OnEngineChannelUpdate(std::string
name,
bool listening)
override;
685 double GetScaledFontSize(
double unscaled_font_size,
686 int configuration_id)
const override;
689 void OnFrameRasterized(
const FrameTiming&)
override;
698 bool ShouldDiscardLayerTree(int64_t view_id,
703 std::string_view method)
const override;
706 bool HandleServiceProtocolMessage(
707 std::string_view method,
709 rapidjson::Document* response)
override;
716 bool OnServiceProtocolScreenshot(
718 rapidjson::Document* response);
721 bool OnServiceProtocolScreenshotSKP(
723 rapidjson::Document* response);
726 bool OnServiceProtocolRunInView(
728 rapidjson::Document* response);
731 bool OnServiceProtocolFlushUIThreadTasks(
733 rapidjson::Document* response);
736 bool OnServiceProtocolSetAssetBundlePath(
738 rapidjson::Document* response);
741 bool OnServiceProtocolGetDisplayRefreshRate(
743 rapidjson::Document* response);
749 bool OnServiceProtocolGetSkSLs(
751 rapidjson::Document* response);
754 bool OnServiceProtocolEstimateRasterCacheMemory(
756 rapidjson::Document* response);
763 bool OnServiceProtocolRenderFrameWithRasterStats(
765 rapidjson::Document* response);
771 bool OnServiceProtocolReloadAssetFonts(
773 rapidjson::Document* response);
776 void SendFontChangeNotification();
779 size_t GetResourceCacheLimit()
override {
return resource_cache_limit_; };
783 std::unique_ptr<DirectoryAssetBundle> RestoreOriginalAssetResolver();
785 SkISize ExpectedFrameSize(int64_t view_id);
789 std::unique_ptr<fml::TaskRunnerAffineWeakPtrFactory<Shell>> weak_factory_gpu_;
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.
std::optional< DartErrorCode > GetUIIsolateLastError() const
Used by embedders to get the last error from the Dart UI Isolate, if one exists.
static std::unique_ptr< Shell > Create(const PlatformData &platform_data, const TaskRunners &task_runners, Settings settings, const CreateCallback< PlatformView > &on_create_platform_view, const CreateCallback< Rasterizer > &on_create_rasterizer, bool is_gpu_disabled=false)
Creates a shell instance using the provided settings. The callbacks to create the various shell subco...
bool EngineHasLivePorts() const
Used by embedders to check if the Engine is running and has any live ports remaining....
~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...
static std::pair< DartVMRef, fml::RefPtr< const DartSnapshot > > InferVmInitDataFromSettings(Settings &settings)
fml::WeakPtr< ShellIOManager > GetIOManager()
The IO Manager may only be accessed on the IO task runner.
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the raster task runner.
void RunEngine(RunConfiguration run_configuration)
Starts an isolate for the given RunConfiguration.
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
const std::shared_ptr< PlatformMessageHandler > & GetPlatformMessageHandler() const override
Returns the delegate object that handles PlatformMessage's from Flutter to the host platform (and its...
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...
fml::WeakPtr< Engine > GetEngine()
Engines may only be accessed on the UI thread. This method is deprecated, and implementers should ins...
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
const Settings & GetSettings() const override
fml::Status WaitForFirstFrame(fml::TimeDelta timeout)
Pauses the calling thread until the first frame is presented.
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)...
std::shared_ptr< const fml::SyncSwitch > GetIsGpuDisabledSyncSwitch() const override
Accessor for the disable GPU SyncSwitch.
void SetGpuAvailability(GpuAvailability availability)
Marks the GPU as available or unavailable.
void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority)
Install a new factory that can match against and decode image data.
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.
bool ReloadSystemFonts()
Used by embedders to reload the system fonts in FontCollection. It also clears the cached font famili...
fml::WeakPtr< PlatformView > GetPlatformView()
Platform views may only be accessed on the platform task runner.
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)
Dart_NativeFunction function
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
def timeout(deadline, cmd)
A POD type used to return the screenshot data along with the size of the frame.