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