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
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 // Embedders should call this under low memory conditions to free up
284 // internal caches used.
285 //
286 // This method posts a task to the raster threads to signal the Rasterizer to
287 // free resources.
288
289 //----------------------------------------------------------------------------
290 /// @brief Used by embedders to notify that there is a low memory
291 /// warning. The shell will attempt to purge caches. Current, only
292 /// the rasterizer cache is purged.
293 void NotifyLowMemoryWarning() const;
294
295 //----------------------------------------------------------------------------
296 /// @brief Used by embedders to flush the microtask queue. Required
297 /// when running with merged platform and UI threads, in which
298 /// case the embedder is responsible for flushing the microtask
299 /// queue.
300 void FlushMicrotaskQueue() const;
301
302 //----------------------------------------------------------------------------
303 /// @brief Used by embedders to check if all shell subcomponents are
304 /// initialized. It is the embedder's responsibility to make this
305 /// call before accessing any other shell method. A shell that is
306 /// not set up must be discarded and another one created with
307 /// updated settings.
308 ///
309 /// @return Returns if the shell has been set up. Once set up, this does
310 /// not change for the life-cycle of the shell.
311 ///
312 bool IsSetup() const;
313
314 //----------------------------------------------------------------------------
315 /// @brief Captures a screenshot and optionally Base64 encodes the data
316 /// of the last layer tree rendered by the rasterizer in this
317 /// shell.
318 ///
319 /// @param[in] type The type of screenshot to capture.
320 /// @param[in] base64_encode If the screenshot data should be base64
321 /// encoded.
322 ///
323 /// @return The screenshot result.
324 ///
326 bool base64_encode);
327
328 //----------------------------------------------------------------------------
329 /// @brief Pauses the calling thread until the first frame is presented.
330 ///
331 /// @param[in] timeout The duration to wait before timing out. If this
332 /// duration would cause an overflow when added to
333 /// std::chrono::steady_clock::now(), this method will
334 /// wait indefinitely for the first frame.
335 ///
336 /// @return 'kOk' when the first frame has been presented before the
337 /// timeout successfully, 'kFailedPrecondition' if called from the
338 /// GPU or UI thread, 'kDeadlineExceeded' if there is a timeout.
339 ///
341
342 //----------------------------------------------------------------------------
343 /// @brief Used by embedders to reload the system fonts in
344 /// FontCollection.
345 /// It also clears the cached font families and send system
346 /// channel message to framework to rebuild affected widgets.
347 ///
348 /// @return Returns if shell reloads system fonts successfully.
349 ///
350 bool ReloadSystemFonts();
351
352 //----------------------------------------------------------------------------
353 /// @brief Used by embedders to get the last error from the Dart UI
354 /// Isolate, if one exists.
355 ///
356 /// @return Returns the last error code from the UI Isolate.
357 ///
358 std::optional<DartErrorCode> GetUIIsolateLastError() const;
359
360 //----------------------------------------------------------------------------
361 /// @brief Used by embedders to check if the Engine is running and has
362 /// any live ports remaining. For example, the Flutter tester uses
363 /// this method to check whether it should continue to wait for
364 /// a running test or not.
365 ///
366 /// @return Returns if the shell has an engine and the engine has any live
367 /// Dart ports.
368 ///
369 bool EngineHasLivePorts() const;
370
371 //----------------------------------------------------------------------------
372 /// @brief Used by embedders to check if the Engine is running and has
373 /// any microtasks that have been queued but have not yet run.
374 /// The Flutter tester uses this as a signal that a test is still
375 /// running.
376 ///
377 /// @return Returns if the shell has an engine and the engine has pending
378 /// microtasks.
379 ///
380 bool EngineHasPendingMicrotasks() const;
381
382 //----------------------------------------------------------------------------
383 /// @brief Accessor for the disable GPU SyncSwitch.
384 // |Rasterizer::Delegate|
385 std::shared_ptr<const fml::SyncSwitch> GetIsGpuDisabledSyncSwitch()
386 const override;
387
388 //----------------------------------------------------------------------------
389 /// @brief Marks the GPU as available or unavailable.
390 void SetGpuAvailability(GpuAvailability availability);
391
392 //----------------------------------------------------------------------------
393 /// @brief Get a pointer to the Dart VM used by this running shell
394 /// instance.
395 ///
396 /// @return The Dart VM pointer.
397 ///
398 DartVM* GetDartVM();
399
400 //----------------------------------------------------------------------------
401 /// @brief Notifies the display manager of the updates.
402 ///
403 void OnDisplayUpdates(std::vector<std::unique_ptr<Display>> displays);
404
405 //----------------------------------------------------------------------------
406 /// @brief Queries the `DisplayManager` for the main display refresh rate.
407 ///
409
410 //----------------------------------------------------------------------------
411 /// @brief Install a new factory that can match against and decode image
412 /// data.
413 /// @param[in] factory Callback that produces `ImageGenerator`s for
414 /// compatible input data.
415 /// @param[in] priority The priority used to determine the order in which
416 /// factories are tried. Higher values mean higher
417 /// priority. The built-in Skia decoders are installed
418 /// at priority 0, and so a priority > 0 takes precedent
419 /// over the builtin decoders. When multiple decoders
420 /// are added with the same priority, those which are
421 /// added earlier take precedent.
422 /// @see `CreateCompatibleGenerator`
423 void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority);
424
425 // |Engine::Delegate|
426 const std::shared_ptr<PlatformMessageHandler>& GetPlatformMessageHandler()
427 const override;
428
429 const std::weak_ptr<VsyncWaiter> GetVsyncWaiter() const;
430
431 const std::shared_ptr<fml::ConcurrentTaskRunner>
433
434 // Infer the VM ref and the isolate snapshot based on the settings.
435 //
436 // If the VM is already running, the settings are ignored, but the returned
437 // isolate snapshot always prioritize what is specified by the settings, and
438 // falls back to the one VM was launched with.
439 //
440 // This function is what Shell::Create uses to infer snapshot settings.
441 //
442 // TODO(dkwingsmt): Extracting this method is part of a bigger change. If the
443 // entire change is not eventually landed, we should merge this method back
444 // to Create. https://github.com/flutter/flutter/issues/136826
445 static std::pair<DartVMRef, fml::RefPtr<const DartSnapshot>>
447
448 private:
449 using ServiceProtocolHandler =
450 std::function<bool(const ServiceProtocol::Handler::ServiceProtocolMap&,
451 rapidjson::Document*)>;
452
453 /// A collection of message channels (by name) that have sent at least one
454 /// message from a non-platform thread. Used to prevent printing the error
455 /// log more than once per channel, as a badly behaving plugin may send
456 /// multiple messages per second indefinitely.
457 std::mutex misbehaving_message_channels_mutex_;
458 std::set<std::string> misbehaving_message_channels_;
459 const TaskRunners task_runners_;
460 const fml::RefPtr<fml::RasterThreadMerger> parent_raster_thread_merger_;
461 std::shared_ptr<ResourceCacheLimitCalculator>
462 resource_cache_limit_calculator_;
463 size_t resource_cache_limit_;
464 const Settings settings_;
465 DartVMRef vm_;
466 mutable std::mutex time_recorder_mutex_;
467 std::optional<fml::TimePoint> latest_frame_target_time_;
468 std::unique_ptr<PlatformView> platform_view_; // on platform task runner
469 std::unique_ptr<Engine> engine_; // on UI task runner
470 std::unique_ptr<Rasterizer> rasterizer_; // on raster task runner
471 std::shared_ptr<ShellIOManager> io_manager_; // on IO task runner
472 std::shared_ptr<fml::SyncSwitch> is_gpu_disabled_sync_switch_;
473 std::shared_ptr<PlatformMessageHandler> platform_message_handler_;
474 std::atomic<bool> route_messages_through_platform_thread_ = false;
475
477 weak_engine_; // to be shared across threads
479 weak_rasterizer_; // to be shared across threads
481 weak_platform_view_; // to be shared across threads
482
483 std::unordered_map<std::string_view, // method
484 std::pair<fml::RefPtr<fml::TaskRunner>,
485 ServiceProtocolHandler> // task-runner/function
486 // pair
487 >
488 service_protocol_handlers_;
489 bool is_set_up_ = false;
490 bool is_added_to_service_protocol_ = false;
491 uint64_t next_pointer_flow_id_ = 0;
492
493 bool first_frame_rasterized_ = false;
494 std::atomic<bool> waiting_for_first_frame_ = true;
495 std::mutex waiting_for_first_frame_mutex_;
496 std::condition_variable waiting_for_first_frame_condition_;
497
498 // Written in the UI thread and read from the raster thread. Hence make it
499 // atomic.
500 std::atomic<bool> needs_report_timings_{false};
501
502 // Whether there's a task scheduled to report the timings to Dart through
503 // ui.PlatformDispatcher.onReportTimings.
504 bool frame_timings_report_scheduled_ = false;
505
506 // Vector of FrameTiming::kCount * n timestamps for n frames whose timings
507 // have not been reported yet. Vector of ints instead of FrameTiming is
508 // stored here for easier conversions to Dart objects.
509 std::vector<int64_t> unreported_timings_;
510
511 /// Manages the displays. This class is thread safe, can be accessed from
512 /// any of the threads.
513 std::unique_ptr<DisplayManager> display_manager_;
514
515 // Protects expected_frame_constraints_ which is set on platform thread and
516 // read on raster thread.
517 std::mutex resize_mutex_;
518
519 // Used to discard wrong size layer tree produced during interactive
520 // resizing.
521 std::unordered_map<int64_t, BoxConstraints> expected_frame_constraints_;
522
523 // Used to communicate the right frame bounds via service protocol.
524 double device_pixel_ratio_ = 0.0;
525
526 // Cached refresh rate used by the performance overlay.
527 std::optional<fml::Milliseconds> cached_display_refresh_rate_;
528
529 // How many frames have been timed since last report.
530 size_t UnreportedFramesCount() const;
531
532 Shell(DartVMRef vm,
533 const TaskRunners& task_runners,
535 const std::shared_ptr<ResourceCacheLimitCalculator>&
536 resource_cache_limit_calculator,
537 const Settings& settings,
538 bool is_gpu_disabled);
539
540 static std::unique_ptr<Shell> CreateShellOnPlatformThread(
541 DartVMRef vm,
543 std::shared_ptr<ShellIOManager> parent_io_manager,
544 const std::shared_ptr<ResourceCacheLimitCalculator>&
545 resource_cache_limit_calculator,
546 const TaskRunners& task_runners,
547 const PlatformData& platform_data,
548 const Settings& settings,
549 fml::RefPtr<const DartSnapshot> isolate_snapshot,
550 const Shell::CreateCallback<PlatformView>& on_create_platform_view,
551 const Shell::CreateCallback<Rasterizer>& on_create_rasterizer,
552 const EngineCreateCallback& on_create_engine,
553 bool is_gpu_disabled);
554
555 static std::unique_ptr<Shell> CreateWithSnapshot(
556 const PlatformData& platform_data,
557 const TaskRunners& task_runners,
558 const fml::RefPtr<fml::RasterThreadMerger>& parent_thread_merger,
559 const std::shared_ptr<ShellIOManager>& parent_io_manager,
560 const std::shared_ptr<ResourceCacheLimitCalculator>&
561 resource_cache_limit_calculator,
562 Settings settings,
563 DartVMRef vm,
564 fml::RefPtr<const DartSnapshot> isolate_snapshot,
565 const CreateCallback<PlatformView>& on_create_platform_view,
566 const CreateCallback<Rasterizer>& on_create_rasterizer,
567 const EngineCreateCallback& on_create_engine,
568 bool is_gpu_disabled);
569
570 bool Setup(std::unique_ptr<PlatformView> platform_view,
571 std::unique_ptr<Engine> engine,
572 std::unique_ptr<Rasterizer> rasterizer,
573 const std::shared_ptr<ShellIOManager>& io_manager);
574
575 void ReportTimings();
576
577 // |PlatformView::Delegate|
578 void OnPlatformViewCreated(std::unique_ptr<Surface> surface) override;
579
580 // |PlatformView::Delegate|
581 void OnPlatformViewDestroyed() override;
582
583 // |PlatformView::Delegate|
584 void OnPlatformViewScheduleFrame() override;
585
586 // |PlatformView::Delegate|
587 void OnPlatformViewAddView(int64_t view_id,
588 const ViewportMetrics& viewport_metrics,
589 AddViewCallback callback) override;
590
591 // |PlatformView::Delegate|
592 void OnPlatformViewRemoveView(int64_t view_id,
594
595 // |PlatformView::Delegate|
596 void OnPlatformViewSendViewFocusEvent(const ViewFocusEvent& event) override;
597
598 // |PlatformView::Delegate|
599 void OnPlatformViewSetViewportMetrics(
600 int64_t view_id,
601 const ViewportMetrics& metrics) override;
602
603 // |PlatformView::Delegate|
604 void OnPlatformViewDispatchPlatformMessage(
605 std::unique_ptr<PlatformMessage> message) override;
606
607 // |PlatformView::Delegate|
608 void OnPlatformViewDispatchPointerDataPacket(
609 std::unique_ptr<PointerDataPacket> packet) override;
610
611 // |PlatformView::Delegate|
612 void OnPlatformViewDispatchSemanticsAction(int64_t view_id,
613 int32_t node_id,
615 fml::MallocMapping args) override;
616
617 // |PlatformView::Delegate|
618 void OnPlatformViewSetSemanticsEnabled(bool enabled) override;
619
620 // |shell:PlatformView::Delegate|
621 void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override;
622
623 // |PlatformView::Delegate|
624 void OnPlatformViewRegisterTexture(
625 std::shared_ptr<flutter::Texture> texture) override;
626
627 // |PlatformView::Delegate|
628 void OnPlatformViewUnregisterTexture(int64_t texture_id) override;
629
630 // |PlatformView::Delegate|
631 void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override;
632
633 // |PlatformView::Delegate|
634 void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override;
635
636 // |PlatformView::Delegate|
637 const Settings& OnPlatformViewGetSettings() const override;
638
639 // |PlatformView::Delegate|
640 void LoadDartDeferredLibrary(
641 intptr_t loading_unit_id,
642 std::unique_ptr<const fml::Mapping> snapshot_data,
643 std::unique_ptr<const fml::Mapping> snapshot_instructions) override;
644
645 void LoadDartDeferredLibraryError(intptr_t loading_unit_id,
646 const std::string error_message,
647 bool transient) override;
648
649 // |PlatformView::Delegate|
650 void UpdateAssetResolverByType(
651 std::unique_ptr<AssetResolver> updated_asset_resolver,
653
654 // |Animator::Delegate|
655 void OnAnimatorBeginFrame(fml::TimePoint frame_target_time,
656 uint64_t frame_number) override;
657
658 // |Animator::Delegate|
659 void OnAnimatorNotifyIdle(fml::TimeDelta deadline) override;
660
661 // |Animator::Delegate|
662 void OnAnimatorUpdateLatestFrameTargetTime(
663 fml::TimePoint frame_target_time) override;
664
665 // |Animator::Delegate|
666 void OnAnimatorDraw(std::shared_ptr<FramePipeline> pipeline) override;
667
668 // |Animator::Delegate|
669 void OnAnimatorDrawLastLayerTrees(
670 std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) override;
671
672 // |Engine::Delegate|
673 void OnEngineUpdateSemantics(
674 int64_t view_id,
676 CustomAccessibilityActionUpdates actions) override;
677
678 // |Engine::Delegate|
679 void OnEngineSetApplicationLocale(std::string locale) override;
680
681 // |Engine::Delegate|
682 void OnEngineSetSemanticsTreeEnabled(bool enabled) override;
683
684 // |Engine::Delegate|
685 void OnEngineHandlePlatformMessage(
686 std::unique_ptr<PlatformMessage> message) override;
687
688 void HandleEngineSkiaMessage(std::unique_ptr<PlatformMessage> message);
689
690 // |Engine::Delegate|
691 void OnPreEngineRestart() override;
692
693 // |Engine::Delegate|
694 void OnRootIsolateCreated() override;
695
696 // |Engine::Delegate|
697 void UpdateIsolateDescription(const std::string isolate_name,
698 int64_t isolate_port) override;
699
700 // |Engine::Delegate|
701 void SetNeedsReportTimings(bool value) override;
702
703 // |Engine::Delegate|
704 std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocale(
705 const std::vector<std::string>& supported_locale_data) override;
706
707 // |Engine::Delegate|
708 void RequestDartDeferredLibrary(intptr_t loading_unit_id) override;
709
710 // |Engine::Delegate|
711 fml::TimePoint GetCurrentTimePoint() override;
712
713 // |Engine::Delegate|
714 void OnEngineChannelUpdate(std::string name, bool listening) override;
715
716 // |Engine::Delegate|
717 double GetScaledFontSize(double unscaled_font_size,
718 int configuration_id) const override;
719
720 // |Engine::Delegate|
721 void RequestViewFocusChange(const ViewFocusChangeRequest& request) override;
722
723 // |Rasterizer::Delegate|
724 void OnFrameRasterized(const FrameTiming&) override;
725
726 // |Rasterizer::Delegate|
727 fml::Milliseconds GetFrameBudget() override;
728
729 // |Rasterizer::Delegate|
730 fml::TimePoint GetLatestFrameTargetTime() const override;
731
732 // |Rasterizer::Delegate|
733 bool ShouldDiscardLayerTree(int64_t view_id,
734 const flutter::LayerTree& tree) override;
735
736 // |ServiceProtocol::Handler|
737 fml::RefPtr<fml::TaskRunner> GetServiceProtocolHandlerTaskRunner(
738 std::string_view method) const override;
739
740 // |ServiceProtocol::Handler|
741 bool HandleServiceProtocolMessage(
742 std::string_view method, // one if the extension names specified above.
744 rapidjson::Document* response) override;
745
746 // |ServiceProtocol::Handler|
747 ServiceProtocol::Handler::Description GetServiceProtocolDescription()
748 const override;
749
750 // Service protocol handler
751 bool OnServiceProtocolScreenshot(
753 rapidjson::Document* response);
754
755 // Service protocol handler
756 bool OnServiceProtocolScreenshotSKP(
758 rapidjson::Document* response);
759
760 // Service protocol handler
761 bool OnServiceProtocolRunInView(
763 rapidjson::Document* response);
764
765 // Service protocol handler
766 bool OnServiceProtocolFlushUIThreadTasks(
768 rapidjson::Document* response);
769
770 // Service protocol handler
771 bool OnServiceProtocolSetAssetBundlePath(
773 rapidjson::Document* response);
774
775 // Service protocol handler
776 bool OnServiceProtocolGetDisplayRefreshRate(
778 rapidjson::Document* response);
779
780 // Service protocol handler
781 //
782 // The returned SkSLs are base64 encoded. Decode before storing them to
783 // files.
784 bool OnServiceProtocolGetSkSLs(
786 rapidjson::Document* response);
787
788 // Service protocol handler
789 bool OnServiceProtocolEstimateRasterCacheMemory(
791 rapidjson::Document* response);
792
793 // Service protocol handler
794 //
795 // Forces the FontCollection to reload the font manifest. Used to support
796 // hot reload for fonts.
797 bool OnServiceProtocolReloadAssetFonts(
799 rapidjson::Document* response);
800
801 // Send a system font change notification.
802 void SendFontChangeNotification();
803
804 // |ResourceCacheLimitItem|
805 size_t GetResourceCacheLimit() override { return resource_cache_limit_; };
806
807 // Creates an asset bundle from the original settings asset path or
808 // directory.
809 std::unique_ptr<DirectoryAssetBundle> RestoreOriginalAssetResolver();
810
811 BoxConstraints ExpectedFrameConstraints(int64_t view_id);
812
813 // For accessing the Shell via the raster thread, necessary for various
814 // rasterizer callbacks.
815 std::unique_ptr<fml::TaskRunnerAffineWeakPtrFactory<Shell>> weak_factory_gpu_;
816
817 fml::WeakPtrFactory<Shell> weak_factory_;
818 friend class testing::ShellTest;
819
821};
822
823} // namespace flutter
824
825#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: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:940
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:792
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:221
void FlushMicrotaskQueue() const
Used by embedders to flush the microtask queue. Required when running with merged platform and UI thr...
Definition shell.cc:748
fml::TaskRunnerAffineWeakPtr< Engine > GetEngine()
Engines may only be accessed on the UI thread. This method is deprecated, and implementers should ins...
Definition shell.cc:925
bool EngineHasLivePorts() const
Used by embedders to check if the Engine is running and has any live ports remaining....
Definition shell.cc:812
~Shell()
Destroys the shell. This is a synchronous operation and synchronous barrier blocks are introduced on ...
Definition shell.cc:591
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:2273
static std::pair< DartVMRef, fml::RefPtr< const DartSnapshot > > InferVmInitDataFromSettings(Settings &settings)
Definition shell.cc:205
fml::WeakPtr< ShellIOManager > GetIOManager()
The IO Manager may only be accessed on the IO task runner.
Definition shell.cc:935
fml::TaskRunnerAffineWeakPtr< Rasterizer > GetRasterizer() const
Rasterizers may only be accessed on the raster task runner.
Definition shell.cc:920
void RunEngine(RunConfiguration run_configuration)
Starts an isolate for the given RunConfiguration.
Definition shell.cc:754
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:672
const std::weak_ptr< VsyncWaiter > GetVsyncWaiter() const
Definition shell.cc:2410
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:2406
const std::shared_ptr< fml::ConcurrentTaskRunner > GetConcurrentWorkerTaskRunner() const
Definition shell.cc:2418
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:726
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:823
const Settings & GetSettings() const override
Definition shell.cc:907
fml::Status WaitForFirstFrame(fml::TimeDelta timeout)
Pauses the calling thread until the first frame is presented.
Definition shell.cc:2308
void OnDisplayUpdates(std::vector< std::unique_ptr< Display > > displays)
Notifies the display manager of the updates.
Definition shell.cc:2381
const TaskRunners & GetTaskRunners() const override
If callers wish to interact directly with any shell subcomponents, they must (on the platform thread)...
Definition shell.cc:911
std::shared_ptr< const fml::SyncSwitch > GetIsGpuDisabledSyncSwitch() const override
Accessor for the disable GPU SyncSwitch.
Definition shell.cc:2351
void SetGpuAvailability(GpuAvailability availability)
Marks the GPU as available or unavailable.
Definition shell.cc:2356
void RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority)
Install a new factory that can match against and decode image data.
Definition shell.cc:2035
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:915
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:834
double GetMainDisplayRefreshRate()
Queries the DisplayManager for the main display refresh rate.
Definition shell.cc:2031
bool ReloadSystemFonts()
Used by embedders to reload the system fonts in FontCollection. It also clears the cached font famili...
Definition shell.cc:2336
fml::WeakPtr< PlatformView > GetPlatformView()
Platform views may only be accessed on the platform task runner.
Definition shell.cc:930
A Mapping like NonOwnedMapping, but uses Free as its release proc.
Definition mapping.h:144
const EmbeddedViewParams * params
FlutterEngine engine
Definition main.cc:84
G_BEGIN_DECLS G_MODULE_EXPORT FlValue * args
G_BEGIN_DECLS GBytes * message
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
A POD type used to return the screenshot data along with the size of the frame.
Definition rasterizer.h:399
int64_t texture_id