Flutter Engine
The Flutter Engine
shell.h
Go to the documentation of this file.
1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef FLUTTER_SHELL_COMMON_SHELL_H_
6#define FLUTTER_SHELL_COMMON_SHELL_H_
7
8#include <functional>
9#include <mutex>
10#include <string_view>
11#include <unordered_map>
12
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"
45
46namespace flutter {
47
48/// Error exit codes for the Dart isolate.
49enum class DartErrorCode {
50 // NOLINTBEGIN(readability-identifier-naming)
51 /// No error has occurred.
52 NoError = 0,
53 /// The Dart error code for an API error.
54 ApiError = 253,
55 /// The Dart error code for a compilation error.
56 CompilationError = 254,
57 /// The Dart error code for an unknown error.
58 UnknownError = 255
59 // NOLINTEND(readability-identifier-naming)
60};
61
62/// Values for |Shell::SetGpuAvailability|.
63enum class GpuAvailability {
64 /// Indicates that GPU operations should be permitted.
65 kAvailable = 0,
66 /// Indicates that the GPU is about to become unavailable, and to attempt to
67 /// flush any GPU related resources now.
69 /// Indicates that the GPU is unavailable, and that no attempt should be made
70 /// to even flush GPU objects until it is available again.
71 kUnavailable = 2
72};
73
74//------------------------------------------------------------------------------
75/// Perhaps the single most important class in the Flutter engine repository.
76/// When embedders create a Flutter application, they are referring to the
77/// creation of an instance of a shell. Creation and destruction of the shell is
78/// synchronous and the embedder only holds a unique pointer to the shell. The
79/// shell does not create the threads its primary components run on. Instead, it
80/// is the embedder's responsibility to create threads and give the shell task
81/// runners for those threads. Due to deterministic destruction of the shell,
82/// the embedder can terminate all threads immediately after collecting the
83/// shell. The shell must be created and destroyed on the same thread, but,
84/// different shells (i.e. a separate instances of a Flutter application) may be
85/// run on different threads simultaneously. The task runners themselves do not
86/// have to be unique. If all task runner references given to the shell during
87/// shell creation point to the same task runner, the Flutter application is
88/// effectively single threaded.
89///
90/// The shell is the central nervous system of the Flutter application. None of
91/// the shell components are thread safe and must be created, accessed and
92/// destroyed on the same thread. To interact with one another, the various
93/// components delegate to the shell for communication. Instead of using back
94/// pointers to the shell, a delegation pattern is used by all components that
95/// want to communicate with one another. Because of this, the shell implements
96/// the delegate interface for all these components.
97///
98/// All shell methods accessed by the embedder may only be called on the
99/// platform task runner. In case the embedder wants to directly access a shell
100/// subcomponent, it is the embedder's responsibility to acquire a weak pointer
101/// to that component and post a task to the task runner used by the component
102/// to access its methods. The shell must also be destroyed on the platform
103/// task runner.
104///
105/// There is no explicit API to bootstrap and shutdown the Dart VM. The first
106/// instance of the shell in the process bootstraps the Dart VM and the
107/// destruction of the last shell instance destroys the same. Since different
108/// shells may be created and destroyed on different threads. VM bootstrap may
109/// happen on one thread but its collection on another. This behavior is thread
110/// safe.
111///
112class Shell final : public PlatformView::Delegate,
113 public Animator::Delegate,
114 public Engine::Delegate,
118 public:
119 template <class T>
120 using CreateCallback = std::function<std::unique_ptr<T>(Shell&)>;
121 typedef std::function<std::unique_ptr<Engine>(
122 Engine::Delegate& delegate,
123 const PointerDataDispatcherMaker& dispatcher_maker,
124 DartVM& vm,
125 fml::RefPtr<const DartSnapshot> isolate_snapshot,
126 TaskRunners task_runners,
127 const PlatformData& platform_data,
129 std::unique_ptr<Animator> animator,
130 fml::WeakPtr<IOManager> io_manager,
131 fml::RefPtr<SkiaUnrefQueue> unref_queue,
133 std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
134 const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch,
135 impeller::RuntimeStageBackend runtime_stage_type)>
137
138 //----------------------------------------------------------------------------
139 /// @brief Creates a shell instance using the provided settings. The
140 /// callbacks to create the various shell subcomponents will be
141 /// called on the appropriate threads before this method returns.
142 /// If this is the first instance of a shell in the process, this
143 /// call also bootstraps the Dart VM.
144 /// @note The root isolate which will run this Shell's Dart code takes
145 /// its instructions from the passed in settings. This allows
146 /// embedders to host multiple Shells with different Dart code.
147 ///
148 /// @param[in] task_runners The task runners
149 /// @param[in] settings The settings
150 /// @param[in] on_create_platform_view The callback that must return a
151 /// platform view. This will be called on
152 /// the platform task runner before this
153 /// method returns.
154 /// @param[in] on_create_rasterizer That callback that must provide a
155 /// valid rasterizer. This will be called
156 /// on the render task runner before this
157 /// method returns.
158 /// @param[in] is_gpu_disabled The default value for the switch that
159 /// turns off the GPU.
160 ///
161 /// @return A full initialized shell if the settings and callbacks are
162 /// valid. The root isolate has been created but not yet launched.
163 /// It may be launched by obtaining the engine weak pointer and
164 /// posting a task onto the UI task runner with a valid run
165 /// configuration to run the isolate. The embedder must always
166 /// check the validity of the shell (using the IsSetup call)
167 /// immediately after getting a pointer to it.
168 ///
169 static std::unique_ptr<Shell> Create(
170 const PlatformData& platform_data,
171 const TaskRunners& task_runners,
173 const CreateCallback<PlatformView>& on_create_platform_view,
174 const CreateCallback<Rasterizer>& on_create_rasterizer,
175 bool is_gpu_disabled = false);
176
177 //----------------------------------------------------------------------------
178 /// @brief Destroys the shell. This is a synchronous operation and
179 /// synchronous barrier blocks are introduced on the various
180 /// threads to ensure shutdown of all shell sub-components before
181 /// this method returns.
182 ///
183 ~Shell();
184
185 //----------------------------------------------------------------------------
186 /// @brief Creates one Shell from another Shell where the created Shell
187 /// takes the opportunity to share any internal components it can.
188 /// This results is a Shell that has a smaller startup time cost
189 /// and a smaller memory footprint than an Shell created with the
190 /// Create function.
191 ///
192 /// The new Shell is returned in a running state so RunEngine
193 /// shouldn't be called again on the Shell. Once running, the
194 /// second Shell is mostly independent from the original Shell
195 /// and the original Shell doesn't need to keep running for the
196 /// spawned Shell to keep functioning.
197 /// @param[in] run_configuration A RunConfiguration used to run the Isolate
198 /// associated with this new Shell. It doesn't have to be the same
199 /// configuration as the current Shell but it needs to be in the
200 /// same snapshot or AOT.
201 ///
202 /// @see http://flutter.dev/go/multiple-engines
203 std::unique_ptr<Shell> Spawn(
204 RunConfiguration run_configuration,
205 const std::string& initial_route,
206 const CreateCallback<PlatformView>& on_create_platform_view,
207 const CreateCallback<Rasterizer>& on_create_rasterizer) const;
208
209 //----------------------------------------------------------------------------
210 /// @brief Starts an isolate for the given RunConfiguration.
211 ///
212 void RunEngine(RunConfiguration run_configuration);
213
214 //----------------------------------------------------------------------------
215 /// @brief Starts an isolate for the given RunConfiguration. The
216 /// result_callback will be called with the status of the
217 /// operation.
218 ///
219 void RunEngine(RunConfiguration run_configuration,
220 const std::function<void(Engine::RunStatus)>& result_callback);
221
222 //------------------------------------------------------------------------------
223 /// @return The settings used to launch this shell.
224 ///
225 const Settings& GetSettings() const override;
226
227 //------------------------------------------------------------------------------
228 /// @brief If callers wish to interact directly with any shell
229 /// subcomponents, they must (on the platform thread) obtain a
230 /// task runner that the component is designed to run on and a
231 /// weak pointer to that component. They may then post a task to
232 /// that task runner, do the validity check on that task runner
233 /// before performing any operation on that component. This
234 /// accessor allows callers to access the task runners for this
235 /// shell.
236 ///
237 /// @return The task runners current in use by the shell.
238 ///
239 const TaskRunners& GetTaskRunners() const override;
240
241 //------------------------------------------------------------------------------
242 /// @brief Getting the raster thread merger from parent shell, it can be
243 /// a null RefPtr when it's a root Shell or the
244 /// embedder_->SupportsDynamicThreadMerging() returns false.
245 ///
246 /// @return The raster thread merger used by the parent shell.
247 ///
249 const override;
250
251 //----------------------------------------------------------------------------
252 /// @brief Rasterizers may only be accessed on the raster task runner.
253 ///
254 /// @return A weak pointer to the rasterizer.
255 ///
257
258 //------------------------------------------------------------------------------
259 /// @brief Engines may only be accessed on the UI thread. This method is
260 /// deprecated, and implementers should instead use other API
261 /// available on the Shell or the PlatformView.
262 ///
263 /// @return A weak pointer to the engine.
264 ///
266
267 //----------------------------------------------------------------------------
268 /// @brief Platform views may only be accessed on the platform task
269 /// runner.
270 ///
271 /// @return A weak pointer to the platform view.
272 ///
274
275 //----------------------------------------------------------------------------
276 /// @brief The IO Manager may only be accessed on the IO task runner.
277 ///
278 /// @return A weak pointer to the IO manager.
279 ///
281
282 // Embedders should call this under low memory conditions to free up
283 // internal caches used.
284 //
285 // This method posts a task to the raster threads to signal the Rasterizer to
286 // free resources.
287
288 //----------------------------------------------------------------------------
289 /// @brief Used by embedders to notify that there is a low memory
290 /// warning. The shell will attempt to purge caches. Current, only
291 /// the rasterizer cache is purged.
292 void NotifyLowMemoryWarning() const;
293
294 //----------------------------------------------------------------------------
295 /// @brief Used by embedders to check if all shell subcomponents are
296 /// initialized. It is the embedder's responsibility to make this
297 /// call before accessing any other shell method. A shell that is
298 /// not set up must be discarded and another one created with
299 /// updated settings.
300 ///
301 /// @return Returns if the shell has been set up. Once set up, this does
302 /// not change for the life-cycle of the shell.
303 ///
304 bool IsSetup() const;
305
306 //----------------------------------------------------------------------------
307 /// @brief Captures a screenshot and optionally Base64 encodes the data
308 /// of the last layer tree rendered by the rasterizer in this
309 /// shell.
310 ///
311 /// @param[in] type The type of screenshot to capture.
312 /// @param[in] base64_encode If the screenshot data should be base64
313 /// encoded.
314 ///
315 /// @return The screenshot result.
316 ///
318 bool base64_encode);
319
320 //----------------------------------------------------------------------------
321 /// @brief Pauses the calling thread until the first frame is presented.
322 ///
323 /// @param[in] timeout The duration to wait before timing out. If this
324 /// duration would cause an overflow when added to
325 /// std::chrono::steady_clock::now(), this method will
326 /// wait indefinitely for the first frame.
327 ///
328 /// @return 'kOk' when the first frame has been presented before the
329 /// timeout successfully, 'kFailedPrecondition' if called from the
330 /// GPU or UI thread, 'kDeadlineExceeded' if there is a timeout.
331 ///
333
334 //----------------------------------------------------------------------------
335 /// @brief Used by embedders to reload the system fonts in
336 /// FontCollection.
337 /// It also clears the cached font families and send system
338 /// channel message to framework to rebuild affected widgets.
339 ///
340 /// @return Returns if shell reloads system fonts successfully.
341 ///
342 bool ReloadSystemFonts();
343
344 //----------------------------------------------------------------------------
345 /// @brief Used by embedders to get the last error from the Dart UI
346 /// Isolate, if one exists.
347 ///
348 /// @return Returns the last error code from the UI Isolate.
349 ///
350 std::optional<DartErrorCode> GetUIIsolateLastError() const;
351
352 //----------------------------------------------------------------------------
353 /// @brief Used by embedders to check if the Engine is running and has
354 /// any live ports remaining. For example, the Flutter tester uses
355 /// this method to check whether it should continue to wait for
356 /// a running test or not.
357 ///
358 /// @return Returns if the shell has an engine and the engine has any live
359 /// Dart ports.
360 ///
361 bool EngineHasLivePorts() const;
362
363 //----------------------------------------------------------------------------
364 /// @brief Accessor for the disable GPU SyncSwitch.
365 // |Rasterizer::Delegate|
366 std::shared_ptr<const fml::SyncSwitch> GetIsGpuDisabledSyncSwitch()
367 const override;
368
369 //----------------------------------------------------------------------------
370 /// @brief Marks the GPU as available or unavailable.
371 void SetGpuAvailability(GpuAvailability availability);
372
373 //----------------------------------------------------------------------------
374 /// @brief Get a pointer to the Dart VM used by this running shell
375 /// instance.
376 ///
377 /// @return The Dart VM pointer.
378 ///
379 DartVM* GetDartVM();
380
381 //----------------------------------------------------------------------------
382 /// @brief Notifies the display manager of the updates.
383 ///
384 void OnDisplayUpdates(std::vector<std::unique_ptr<Display>> displays);
385
386 //----------------------------------------------------------------------------
387 /// @brief Queries the `DisplayManager` for the main display refresh rate.
388 ///
390
391 //----------------------------------------------------------------------------
392 /// @brief Install a new factory that can match against and decode image
393 /// data.
394 /// @param[in] factory Callback that produces `ImageGenerator`s for
395 /// compatible input data.
396 /// @param[in] priority The priority used to determine the order in which
397 /// factories are tried. Higher values mean higher
398 /// priority. The built-in Skia decoders are installed
399 /// at priority 0, and so a priority > 0 takes precedent
400 /// over the builtin decoders. When multiple decoders
401 /// are added with the same priority, those which are
402 /// added earlier take precedent.
403 /// @see `CreateCompatibleGenerator`
404 void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority);
405
406 // |Engine::Delegate|
407 const std::shared_ptr<PlatformMessageHandler>& GetPlatformMessageHandler()
408 const override;
409
410 const std::weak_ptr<VsyncWaiter> GetVsyncWaiter() const;
411
412 const std::shared_ptr<fml::ConcurrentTaskRunner>
414
415 // Infer the VM ref and the isolate snapshot based on the settings.
416 //
417 // If the VM is already running, the settings are ignored, but the returned
418 // isolate snapshot always prioritize what is specified by the settings, and
419 // falls back to the one VM was launched with.
420 //
421 // This function is what Shell::Create uses to infer snapshot settings.
422 //
423 // TODO(dkwingsmt): Extracting this method is part of a bigger change. If the
424 // entire change is not eventually landed, we should merge this method back
425 // to Create. https://github.com/flutter/flutter/issues/136826
426 static std::pair<DartVMRef, fml::RefPtr<const DartSnapshot>>
428
429 private:
430 using ServiceProtocolHandler =
432 rapidjson::Document*)>;
433
434 /// A collection of message channels (by name) that have sent at least one
435 /// message from a non-platform thread. Used to prevent printing the error
436 /// log more than once per channel, as a badly behaving plugin may send
437 /// multiple messages per second indefinitely.
438 std::mutex misbehaving_message_channels_mutex_;
439 std::set<std::string> misbehaving_message_channels_;
440 const TaskRunners task_runners_;
441 const fml::RefPtr<fml::RasterThreadMerger> parent_raster_thread_merger_;
442 std::shared_ptr<ResourceCacheLimitCalculator>
443 resource_cache_limit_calculator_;
444 size_t resource_cache_limit_;
445 const Settings settings_;
446 DartVMRef vm_;
447 mutable std::mutex time_recorder_mutex_;
448 std::optional<fml::TimePoint> latest_frame_target_time_;
449 std::unique_ptr<PlatformView> platform_view_; // on platform task runner
450 std::unique_ptr<Engine> engine_; // on UI task runner
451 std::unique_ptr<Rasterizer> rasterizer_; // on raster task runner
452 std::shared_ptr<ShellIOManager> io_manager_; // on IO task runner
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;
457
458 fml::WeakPtr<Engine> weak_engine_; // to be shared across threads
460 weak_rasterizer_; // to be shared across threads
462 weak_platform_view_; // to be shared across threads
463
464 std::unordered_map<std::string_view, // method
465 std::pair<fml::RefPtr<fml::TaskRunner>,
466 ServiceProtocolHandler> // task-runner/function
467 // pair
468 >
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;
473
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_;
478
479 // Written in the UI thread and read from the raster thread. Hence make it
480 // atomic.
481 std::atomic<bool> needs_report_timings_{false};
482
483 // Whether there's a task scheduled to report the timings to Dart through
484 // ui.PlatformDispatcher.onReportTimings.
485 bool frame_timings_report_scheduled_ = false;
486
487 // Vector of FrameTiming::kCount * n timestamps for n frames whose timings
488 // have not been reported yet. Vector of ints instead of FrameTiming is
489 // stored here for easier conversions to Dart objects.
490 std::vector<int64_t> unreported_timings_;
491
492 /// Manages the displays. This class is thread safe, can be accessed from
493 /// any of the threads.
494 std::unique_ptr<DisplayManager> display_manager_;
495
496 // protects expected_frame_size_ which is set on platform thread and read on
497 // raster thread
498 std::mutex resize_mutex_;
499
500 // used to discard wrong size layer tree produced during interactive
501 // resizing
502 std::unordered_map<int64_t, SkISize> expected_frame_sizes_;
503
504 // Used to communicate the right frame bounds via service protocol.
505 double device_pixel_ratio_ = 0.0;
506
507 // How many frames have been timed since last report.
508 size_t UnreportedFramesCount() const;
509
510 Shell(DartVMRef vm,
511 const TaskRunners& task_runners,
513 const std::shared_ptr<ResourceCacheLimitCalculator>&
514 resource_cache_limit_calculator,
515 const Settings& settings,
516 std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
517 bool is_gpu_disabled);
518
519 static std::unique_ptr<Shell> CreateShellOnPlatformThread(
520 DartVMRef vm,
522 std::shared_ptr<ShellIOManager> parent_io_manager,
523 const std::shared_ptr<ResourceCacheLimitCalculator>&
524 resource_cache_limit_calculator,
525 const TaskRunners& task_runners,
526 const PlatformData& platform_data,
527 const Settings& settings,
528 fml::RefPtr<const DartSnapshot> isolate_snapshot,
529 const Shell::CreateCallback<PlatformView>& on_create_platform_view,
530 const Shell::CreateCallback<Rasterizer>& on_create_rasterizer,
531 const EngineCreateCallback& on_create_engine,
532 bool is_gpu_disabled);
533
534 static std::unique_ptr<Shell> CreateWithSnapshot(
535 const PlatformData& platform_data,
536 const TaskRunners& task_runners,
537 const fml::RefPtr<fml::RasterThreadMerger>& parent_thread_merger,
538 const std::shared_ptr<ShellIOManager>& parent_io_manager,
539 const std::shared_ptr<ResourceCacheLimitCalculator>&
540 resource_cache_limit_calculator,
542 DartVMRef vm,
543 fml::RefPtr<const DartSnapshot> isolate_snapshot,
544 const CreateCallback<PlatformView>& on_create_platform_view,
545 const CreateCallback<Rasterizer>& on_create_rasterizer,
546 const EngineCreateCallback& on_create_engine,
547 bool is_gpu_disabled);
548
549 bool Setup(std::unique_ptr<PlatformView> platform_view,
550 std::unique_ptr<Engine> engine,
551 std::unique_ptr<Rasterizer> rasterizer,
552 const std::shared_ptr<ShellIOManager>& io_manager);
553
554 void ReportTimings();
555
556 // |PlatformView::Delegate|
557 void OnPlatformViewCreated(std::unique_ptr<Surface> surface) override;
558
559 // |PlatformView::Delegate|
560 void OnPlatformViewDestroyed() override;
561
562 // |PlatformView::Delegate|
563 void OnPlatformViewScheduleFrame() override;
564
565 // |PlatformView::Delegate|
566 void OnPlatformViewAddView(int64_t view_id,
567 const ViewportMetrics& viewport_metrics,
568 AddViewCallback callback) override;
569
570 // |PlatformView::Delegate|
571 void OnPlatformViewRemoveView(int64_t view_id,
573
574 // |PlatformView::Delegate|
575 void OnPlatformViewSetViewportMetrics(
576 int64_t view_id,
577 const ViewportMetrics& metrics) override;
578
579 // |PlatformView::Delegate|
580 void OnPlatformViewDispatchPlatformMessage(
581 std::unique_ptr<PlatformMessage> message) override;
582
583 // |PlatformView::Delegate|
584 void OnPlatformViewDispatchPointerDataPacket(
585 std::unique_ptr<PointerDataPacket> packet) override;
586
587 // |PlatformView::Delegate|
588 void OnPlatformViewDispatchSemanticsAction(int32_t node_id,
590 fml::MallocMapping args) override;
591
592 // |PlatformView::Delegate|
593 void OnPlatformViewSetSemanticsEnabled(bool enabled) override;
594
595 // |shell:PlatformView::Delegate|
596 void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override;
597
598 // |PlatformView::Delegate|
599 void OnPlatformViewRegisterTexture(
600 std::shared_ptr<flutter::Texture> texture) override;
601
602 // |PlatformView::Delegate|
603 void OnPlatformViewUnregisterTexture(int64_t texture_id) override;
604
605 // |PlatformView::Delegate|
606 void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override;
607
608 // |PlatformView::Delegate|
609 void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override;
610
611 // |PlatformView::Delegate|
612 const Settings& OnPlatformViewGetSettings() const override;
613
614 // |PlatformView::Delegate|
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;
619
620 void LoadDartDeferredLibraryError(intptr_t loading_unit_id,
621 const std::string error_message,
622 bool transient) override;
623
624 // |PlatformView::Delegate|
625 void UpdateAssetResolverByType(
626 std::unique_ptr<AssetResolver> updated_asset_resolver,
628
629 // |Animator::Delegate|
630 void OnAnimatorBeginFrame(fml::TimePoint frame_target_time,
631 uint64_t frame_number) override;
632
633 // |Animator::Delegate|
634 void OnAnimatorNotifyIdle(fml::TimeDelta deadline) override;
635
636 // |Animator::Delegate|
637 void OnAnimatorUpdateLatestFrameTargetTime(
638 fml::TimePoint frame_target_time) override;
639
640 // |Animator::Delegate|
641 void OnAnimatorDraw(std::shared_ptr<FramePipeline> pipeline) override;
642
643 // |Animator::Delegate|
644 void OnAnimatorDrawLastLayerTrees(
645 std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) override;
646
647 // |Engine::Delegate|
648 void OnEngineUpdateSemantics(
650 CustomAccessibilityActionUpdates actions) override;
651
652 // |Engine::Delegate|
653 void OnEngineHandlePlatformMessage(
654 std::unique_ptr<PlatformMessage> message) override;
655
656 void HandleEngineSkiaMessage(std::unique_ptr<PlatformMessage> message);
657
658 // |Engine::Delegate|
659 void OnPreEngineRestart() override;
660
661 // |Engine::Delegate|
662 void OnRootIsolateCreated() override;
663
664 // |Engine::Delegate|
665 void UpdateIsolateDescription(const std::string isolate_name,
666 int64_t isolate_port) override;
667
668 // |Engine::Delegate|
669 void SetNeedsReportTimings(bool value) override;
670
671 // |Engine::Delegate|
672 std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocale(
673 const std::vector<std::string>& supported_locale_data) override;
674
675 // |Engine::Delegate|
676 void RequestDartDeferredLibrary(intptr_t loading_unit_id) override;
677
678 // |Engine::Delegate|
679 fml::TimePoint GetCurrentTimePoint() override;
680
681 // |Engine::Delegate|
682 void OnEngineChannelUpdate(std::string name, bool listening) override;
683
684 // |Engine::Delegate|
685 double GetScaledFontSize(double unscaled_font_size,
686 int configuration_id) const override;
687
688 // |Rasterizer::Delegate|
689 void OnFrameRasterized(const FrameTiming&) override;
690
691 // |Rasterizer::Delegate|
692 fml::Milliseconds GetFrameBudget() override;
693
694 // |Rasterizer::Delegate|
695 fml::TimePoint GetLatestFrameTargetTime() const override;
696
697 // |Rasterizer::Delegate|
698 bool ShouldDiscardLayerTree(int64_t view_id,
699 const flutter::LayerTree& tree) override;
700
701 // |ServiceProtocol::Handler|
702 fml::RefPtr<fml::TaskRunner> GetServiceProtocolHandlerTaskRunner(
703 std::string_view method) const override;
704
705 // |ServiceProtocol::Handler|
706 bool HandleServiceProtocolMessage(
707 std::string_view method, // one if the extension names specified above.
709 rapidjson::Document* response) override;
710
711 // |ServiceProtocol::Handler|
712 ServiceProtocol::Handler::Description GetServiceProtocolDescription()
713 const override;
714
715 // Service protocol handler
716 bool OnServiceProtocolScreenshot(
718 rapidjson::Document* response);
719
720 // Service protocol handler
721 bool OnServiceProtocolScreenshotSKP(
723 rapidjson::Document* response);
724
725 // Service protocol handler
726 bool OnServiceProtocolRunInView(
728 rapidjson::Document* response);
729
730 // Service protocol handler
731 bool OnServiceProtocolFlushUIThreadTasks(
733 rapidjson::Document* response);
734
735 // Service protocol handler
736 bool OnServiceProtocolSetAssetBundlePath(
738 rapidjson::Document* response);
739
740 // Service protocol handler
741 bool OnServiceProtocolGetDisplayRefreshRate(
743 rapidjson::Document* response);
744
745 // Service protocol handler
746 //
747 // The returned SkSLs are base64 encoded. Decode before storing them to
748 // files.
749 bool OnServiceProtocolGetSkSLs(
751 rapidjson::Document* response);
752
753 // Service protocol handler
754 bool OnServiceProtocolEstimateRasterCacheMemory(
756 rapidjson::Document* response);
757
758 // Service protocol handler
759 //
760 // Renders a frame and responds with various statistics pertaining to the
761 // raster call. These include time taken to raster every leaf layer and also
762 // leaf layer snapshots.
763 bool OnServiceProtocolRenderFrameWithRasterStats(
765 rapidjson::Document* response);
766
767 // Service protocol handler
768 //
769 // Forces the FontCollection to reload the font manifest. Used to support
770 // hot reload for fonts.
771 bool OnServiceProtocolReloadAssetFonts(
773 rapidjson::Document* response);
774
775 // Send a system font change notification.
776 void SendFontChangeNotification();
777
778 // |ResourceCacheLimitItem|
779 size_t GetResourceCacheLimit() override { return resource_cache_limit_; };
780
781 // Creates an asset bundle from the original settings asset path or
782 // directory.
783 std::unique_ptr<DirectoryAssetBundle> RestoreOriginalAssetResolver();
784
785 SkISize ExpectedFrameSize(int64_t view_id);
786
787 // For accessing the Shell via the raster thread, necessary for various
788 // rasterizer callbacks.
789 std::unique_ptr<fml::TaskRunnerAffineWeakPtrFactory<Shell>> weak_factory_gpu_;
790
791 fml::WeakPtrFactory<Shell> weak_factory_;
792 friend class testing::ShellTest;
793
795};
796
797} // namespace flutter
798
799#endif // FLUTTER_SHELL_COMMON_SHELL_H_
std::unique_ptr< flutter::PlatformViewIOS > platform_view
GLenum type
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...
Definition: dart_vm.h:61
While the engine operates entirely on the UI task runner, it needs the capabilities of the other comp...
Definition: engine.h:140
RunStatus
Indicates the result of the call to Engine::Run.
Definition: engine.h:78
Used to forward events from the platform view to interested subsystems. This forwarding is done by th...
Definition: platform_view.h:60
PlatformView::AddViewCallback AddViewCallback
Definition: platform_view.h:62
PlatformView::RemoveViewCallback RemoveViewCallback
Definition: platform_view.h:63
Used to forward events from the rasterizer to interested subsystems. Currently, the shell sets itself...
Definition: rasterizer.h:128
ScreenshotType
The type of the screenshot to obtain of the previously rendered layer tree.
Definition: rasterizer.h:347
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.
Definition: shell.cc:834
std::optional< DartErrorCode > GetUIIsolateLastError() const
Used by embedders to get the last error from the Dart UI Isolate, if one exists.
Definition: shell.cc:697
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...
Definition: shell.cc:169
bool EngineHasLivePorts() const
Used by embedders to check if the Engine is running and has any live ports remaining....
Definition: shell.cc:717
~Shell()
Destroys the shell. This is a synchronous operation and synchronous barrier blocks are introduced on ...
Definition: shell.cc:529
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...
Definition: shell.cc:2189
static std::pair< DartVMRef, fml::RefPtr< const DartSnapshot > > InferVmInitDataFromSettings(Settings &settings)
Definition: shell.cc:153
fml::WeakPtr< ShellIOManager > GetIOManager()
The IO Manager may only be accessed on the IO task runner.
Definition: shell.cc:829
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the raster task runner.
Definition: shell.cc:814
void RunEngine(RunConfiguration run_configuration)
Starts an isolate for the given RunConfiguration.
Definition: shell.cc:659
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...
Definition: shell.cc:593
const std::weak_ptr< VsyncWaiter > GetVsyncWaiter() const
Definition: shell.cc:2326
const std::shared_ptr< PlatformMessageHandler > & GetPlatformMessageHandler() const override
Returns the delegate object that handles PlatformMessage's from Flutter to the host platform (and its...
Definition: shell.cc:2322
const std::shared_ptr< fml::ConcurrentTaskRunner > GetConcurrentWorkerTaskRunner() const
Definition: shell.cc:2334
void NotifyLowMemoryWarning() const
Used by embedders to notify that there is a low memory warning. The shell will attempt to purge cache...
Definition: shell.cc:637
fml::WeakPtr< Engine > GetEngine()
Engines may only be accessed on the UI thread. This method is deprecated, and implementers should ins...
Definition: shell.cc:819
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
Definition: shell.h:136
const Settings & GetSettings() const override
Definition: shell.cc:801
fml::Status WaitForFirstFrame(fml::TimeDelta timeout)
Pauses the calling thread until the first frame is presented.
Definition: shell.cc:2224
void OnDisplayUpdates(std::vector< std::unique_ptr< Display > > displays)
Notifies the display manager of the updates.
Definition: shell.cc:2297
const TaskRunners & GetTaskRunners() const override
If callers wish to interact directly with any shell subcomponents, they must (on the platform thread)...
Definition: shell.cc:805
std::shared_ptr< const fml::SyncSwitch > GetIsGpuDisabledSyncSwitch() const override
Accessor for the disable GPU SyncSwitch.
Definition: shell.cc:2267
void SetGpuAvailability(GpuAvailability availability)
Marks the GPU as available or unavailable.
Definition: shell.cc:2272
void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority)
Install a new factory that can match against and decode image data.
Definition: shell.cc:1875
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...
Definition: shell.cc:809
std::function< std::unique_ptr< T >(Shell &)> CreateCallback
Definition: shell.h:120
bool IsSetup() const
Used by embedders to check if all shell subcomponents are initialized. It is the embedder's responsib...
Definition: shell.cc:728
double GetMainDisplayRefreshRate()
Queries the DisplayManager for the main display refresh rate.
Definition: shell.cc:1871
bool ReloadSystemFonts()
Used by embedders to reload the system fonts in FontCollection. It also clears the cached font famili...
Definition: shell.cc:2252
fml::WeakPtr< PlatformView > GetPlatformView()
Platform views may only be accessed on the platform task runner.
Definition: shell.cc:824
A Mapping like NonOwnedMapping, but uses Free as its release proc.
Definition: mapping.h:144
const EmbeddedViewParams * params
FlutterEngine engine
Definition: main.cc:68
VkSurfaceKHR surface
Definition: main.cc:49
FlutterSemanticsFlag flags
G_BEGIN_DECLS G_MODULE_EXPORT FlValue * args
FlKeyEvent uint64_t FlKeyResponderAsyncCallback callback
uint8_t value
#define FML_DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition: macros.h:27
Dart_NativeFunction function
Definition: fuchsia.cc:51
Win32Message message
FlTexture * texture
DartErrorCode
Error exit codes for the Dart isolate.
Definition: shell.h:49
@ 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
Definition: switches.h:32
GpuAvailability
Values for |Shell::SetGpuAvailability|.
Definition: shell.h:63
@ kAvailable
Indicates that GPU operations should be permitted.
std::chrono::duration< double, std::milli > Milliseconds
Definition: time_delta.h:18
std::function< void()> closure
Definition: closure.h:14
def timeout(deadline, cmd)
Definition: update.py:1
Definition: SkSize.h:16
A POD type used to return the screenshot data along with the size of the frame.
Definition: rasterizer.h:398
int64_t texture_id