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