waft_embedder/platform.rs
1//! Host capabilities the framework calls at runtime.
2//!
3//! Unlike Dart's isolate-global `PlatformDispatcher`, this object is supplied
4//! by the embedder and held by `App`. Incoming host events travel through
5//! `EmbedderClient`, so this interface contains requests and state only.
6
7use std::any::Any;
8use std::rc::Rc;
9use std::sync::Arc;
10use std::time::Duration;
11
12use web_time::Instant;
13
14use crate::clipboard::Clipboard;
15use crate::file_dialogs::FileDialogs;
16use crate::files::Files;
17use crate::fonts::FontSource;
18use crate::geometry::{Color, Offset, Rect};
19use crate::http::HttpClient;
20use crate::menus::{DockMenu, MenuBar, PopupMenus, TrayIcons};
21use crate::notifications::Notifications;
22use crate::opener::Opener;
23use crate::restoration::{RestorationMap, RestorationUpdate};
24use crate::system_context_menu::SystemContextMenuItem;
25use crate::{View, ViewId};
26
27pub type PlatformRef = Rc<dyn Platform>;
28
29pub type ViewRef = Rc<dyn View>;
30
31/// Specifies a description of the application that is pertinent to the
32/// embedder's application switcher (also known as "recent tasks") user
33/// interface.
34///
35/// Flutter counterpart: `ApplicationSwitcherDescription` (`services/system_chrome.dart`).
36/// It lives here because [`Platform`] names it.
37#[derive(Clone, Debug, Default, PartialEq, Eq)]
38pub struct ApplicationSwitcherDescription {
39 /// A label and description of the current state of the application.
40 pub label: Option<String>,
41 /// The application's primary color, as a 32-bit ARGB value.
42 ///
43 /// This may influence the color that the operating system uses to represent
44 /// the application.
45 pub primary_color: Option<u32>,
46}
47
48/// Specifies a system overlay style for a portion of the app.
49///
50/// Flutter counterpart: `SystemUiOverlayStyle` (`services/system_chrome.dart`).
51/// It lives here because [`Platform`] names it.
52#[derive(Clone, Copy, Debug, Default, PartialEq)]
53pub struct SystemUiOverlayStyle {
54 /// The color of the system bottom navigation bar.
55 ///
56 /// Only honored in Android versions O and greater.
57 pub system_navigation_bar_color: Option<Color>,
58
59 /// The color of the divider between the system's bottom navigation bar and the app's
60 /// content.
61 ///
62 /// Only honored in Android versions P and greater.
63 pub system_navigation_bar_divider_color: Option<Color>,
64
65 /// The brightness of the system navigation bar icons.
66 ///
67 /// Only honored in Android versions O and greater.
68 /// When set to [`Brightness::Light`], the system navigation bar icons are light.
69 /// When set to [`Brightness::Dark`], the system navigation bar icons are dark.
70 pub system_navigation_bar_icon_brightness: Option<Brightness>,
71
72 /// Overrides the contrast enforcement when setting a transparent navigation bar.
73 ///
74 /// When setting a transparent navigation bar in SDK 29+, or Android 10 and up, a
75 /// translucent body scrim may be applied behind the button navigation bar to ensure
76 /// contrast with buttons and the background of the application.
77 ///
78 /// SDK 28-, or Android P and lower, will not apply this body scrim.
79 ///
80 /// Setting this to false overrides the default body scrim.
81 pub system_navigation_bar_contrast_enforced: Option<bool>,
82
83 /// The color of top status bar.
84 ///
85 /// Only honored in Android version M and greater.
86 pub status_bar_color: Option<Color>,
87
88 /// The brightness of top status bar.
89 ///
90 /// Only honored in iOS.
91 pub status_bar_brightness: Option<Brightness>,
92
93 /// The brightness of the top status bar icons.
94 ///
95 /// Only honored in Android version M and greater.
96 pub status_bar_icon_brightness: Option<Brightness>,
97
98 /// Overrides the contrast enforcement when setting a transparent status bar.
99 ///
100 /// When setting a transparent status bar in SDK 29+, or Android 10 and up, a translucent
101 /// body scrim may be applied to ensure contrast with icons and the background of the
102 /// application.
103 ///
104 /// SDK 28-, or Android P and lower, will not apply this body scrim.
105 ///
106 /// Setting this to false overrides the default body scrim.
107 pub system_status_bar_contrast_enforced: Option<bool>,
108}
109
110impl SystemUiOverlayStyle {
111 /// System overlays should be drawn with a light color. Intended for applications with a
112 /// dark background.
113 pub const LIGHT: SystemUiOverlayStyle = SystemUiOverlayStyle {
114 system_navigation_bar_color: Some(Color::new(0xFF000000)),
115 system_navigation_bar_icon_brightness: Some(Brightness::Light),
116 status_bar_icon_brightness: Some(Brightness::Light),
117 status_bar_brightness: Some(Brightness::Dark),
118 system_navigation_bar_divider_color: None,
119 system_navigation_bar_contrast_enforced: None,
120 status_bar_color: None,
121 system_status_bar_contrast_enforced: None,
122 };
123
124 /// System overlays should be drawn with a dark color. Intended for applications with a
125 /// light background.
126 pub const DARK: SystemUiOverlayStyle = SystemUiOverlayStyle {
127 system_navigation_bar_color: Some(Color::new(0xFF000000)),
128 system_navigation_bar_icon_brightness: Some(Brightness::Light),
129 status_bar_icon_brightness: Some(Brightness::Dark),
130 status_bar_brightness: Some(Brightness::Light),
131 system_navigation_bar_divider_color: None,
132 system_navigation_bar_contrast_enforced: None,
133 status_bar_color: None,
134 system_status_bar_contrast_enforced: None,
135 };
136
137 /// Creates a new [`SystemUiOverlayStyle`]; Dart's named arguments are the setters.
138 pub const fn new() -> SystemUiOverlayStyle {
139 SystemUiOverlayStyle {
140 system_navigation_bar_color: None,
141 system_navigation_bar_divider_color: None,
142 system_navigation_bar_icon_brightness: None,
143 system_navigation_bar_contrast_enforced: None,
144 status_bar_color: None,
145 status_bar_brightness: None,
146 status_bar_icon_brightness: None,
147 system_status_bar_contrast_enforced: None,
148 }
149 }
150
151 /// Dart `SystemUiOverlayStyle(systemNavigationBarColor:)`.
152 pub fn system_navigation_bar_color(mut self, color: Color) -> SystemUiOverlayStyle {
153 self.system_navigation_bar_color = Some(color);
154 self
155 }
156
157 /// Dart `SystemUiOverlayStyle(systemNavigationBarDividerColor:)`.
158 pub fn system_navigation_bar_divider_color(mut self, color: Color) -> SystemUiOverlayStyle {
159 self.system_navigation_bar_divider_color = Some(color);
160 self
161 }
162
163 /// Dart `SystemUiOverlayStyle(systemNavigationBarIconBrightness:)`.
164 pub fn system_navigation_bar_icon_brightness(
165 mut self,
166 brightness: Brightness,
167 ) -> SystemUiOverlayStyle {
168 self.system_navigation_bar_icon_brightness = Some(brightness);
169 self
170 }
171
172 /// Dart `SystemUiOverlayStyle(systemNavigationBarContrastEnforced:)`.
173 pub fn system_navigation_bar_contrast_enforced(
174 mut self,
175 enforced: bool,
176 ) -> SystemUiOverlayStyle {
177 self.system_navigation_bar_contrast_enforced = Some(enforced);
178 self
179 }
180
181 /// Dart `SystemUiOverlayStyle(statusBarColor:)`.
182 pub fn status_bar_color(mut self, color: Color) -> SystemUiOverlayStyle {
183 self.status_bar_color = Some(color);
184 self
185 }
186
187 /// Dart `SystemUiOverlayStyle(statusBarBrightness:)`.
188 pub fn status_bar_brightness(mut self, brightness: Brightness) -> SystemUiOverlayStyle {
189 self.status_bar_brightness = Some(brightness);
190 self
191 }
192
193 /// Dart `SystemUiOverlayStyle(statusBarIconBrightness:)`.
194 pub fn status_bar_icon_brightness(mut self, brightness: Brightness) -> SystemUiOverlayStyle {
195 self.status_bar_icon_brightness = Some(brightness);
196 self
197 }
198
199 /// Dart `SystemUiOverlayStyle(systemStatusBarContrastEnforced:)`.
200 pub fn system_status_bar_contrast_enforced(mut self, enforced: bool) -> SystemUiOverlayStyle {
201 self.system_status_bar_contrast_enforced = Some(enforced);
202 self
203 }
204
205 /// Creates a copy of this theme with the given fields replaced with new values.
206 pub fn copy_with(&self) -> SystemUiOverlayStyle {
207 *self
208 }
209}
210
211/// The kind of haptic feedback to play.
212///
213/// Flutter counterpart: the `HapticFeedbackType.*` argument Dart sends with the
214/// `HapticFeedback.vibrate` message on `SystemChannels.platform`. It lives here
215/// because [`Platform`] names it.
216#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
217pub enum HapticFeedbackType {
218 /// Vibration for a short duration, the argument-less `HapticFeedback.vibrate`.
219 Vibrate,
220 /// A collision impact with a light mass.
221 LightImpact,
222 /// A collision impact with a medium mass.
223 MediumImpact,
224 /// A collision impact with a heavy mass.
225 HeavyImpact,
226 /// A selection changing through discrete values.
227 SelectionClick,
228 /// A task or action completed successfully.
229 SuccessNotification,
230 /// A task or action produced a warning.
231 WarningNotification,
232 /// A task or action failed.
233 ErrorNotification,
234}
235
236/// Describes the contrast of a theme or color palette.
237///
238/// Flutter counterpart: `Brightness` (`dart:ui` `window.dart`).
239#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
240pub enum Brightness {
241 /// The color is dark and will require a light text color to achieve readable
242 /// contrast.
243 ///
244 /// For example, the color might be dark grey, requiring white text.
245 Dark,
246
247 /// The color is light and will require a dark text color to achieve readable
248 /// contrast.
249 ///
250 /// For example, the color might be bright white, requiring black text.
251 Light,
252}
253
254/// States that an application can be in once it is running.
255///
256/// States not supported on a platform are synthesized so the state machine stays the same
257/// everywhere. For example, [`Hidden`](AppLifecycleState::Hidden) is synthesized on mobile
258/// before [`Paused`](AppLifecycleState::Paused) when coming from
259/// [`Inactive`](AppLifecycleState::Inactive), and before [`Inactive`](AppLifecycleState::Inactive)
260/// when coming from [`Paused`](AppLifecycleState::Paused).
261///
262/// The values below are listed in the expected state machine transition order. The initial
263/// state is [`Detached`](AppLifecycleState::Detached).
264///
265/// Flutter counterpart: `AppLifecycleState` (`dart:ui` `platform_dispatcher.dart`).
266#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
267pub enum AppLifecycleState {
268 /// The application is still hosted by a Flutter engine but is detached from any host
269 /// views.
270 ///
271 /// The application defaults to this state before it initializes, and can be in this
272 /// state (applicable on Android, iOS, and web) after all views have been detached.
273 ///
274 /// When the application is in this state, the engine is running without a view.
275 ///
276 /// This state is only entered on iOS, Android, and web, although on all platforms it is
277 /// the default state before the application begins running.
278 Detached,
279
280 /// On all platforms, this state indicates that the application is in the default
281 /// running mode for a running application that has input focus and is visible.
282 ///
283 /// On Android, this state corresponds to the Flutter host view having focus while in
284 /// Android's "resumed" state. It is possible for the Flutter app to be in the
285 /// [`Inactive`](AppLifecycleState::Inactive) state while still being in Android's
286 /// "onResume" state if the app has lost focus but hasn't had `Activity.onPause` called
287 /// on it.
288 ///
289 /// On iOS and macOS, this corresponds to the app running in the foreground active
290 /// state.
291 Resumed,
292
293 /// At least one view of the application is visible, but none have input focus. The
294 /// application is otherwise running normally.
295 ///
296 /// On non-web desktop platforms, this corresponds to an application that is not in the
297 /// foreground, but still has visible windows.
298 ///
299 /// On the web, this corresponds to an application that is running in a window or tab
300 /// that does not have input focus.
301 ///
302 /// On iOS and macOS, this state corresponds to the Flutter host view running in the
303 /// foreground inactive state. Apps transition to this state when in a phone call, when
304 /// responding to a TouchID request, when entering the app switcher or the control
305 /// center, or when the UIViewController hosting the Flutter app is transitioning.
306 ///
307 /// On Android, this corresponds to the Flutter host view running in Android's paused
308 /// state (i.e. `Activity.onPause` has been called), or in Android's "resumed" state
309 /// (i.e. `Activity.onResume` has been called) but does not have window focus.
310 ///
311 /// On Android and iOS, apps in this state should assume that they may be
312 /// [`Hidden`](AppLifecycleState::Hidden) and [`Paused`](AppLifecycleState::Paused) at any
313 /// time.
314 Inactive,
315
316 /// All views of an application are hidden, either because the application is about to
317 /// be paused (on iOS and Android), or because it has been minimized or placed on a
318 /// desktop that is no longer visible (on non-web desktop), or is running in a window or
319 /// tab that is no longer visible (on the web).
320 ///
321 /// On iOS and Android, in order to keep the state machine the same on all platforms, a
322 /// transition to this state is synthesized before the [`Paused`](AppLifecycleState::Paused)
323 /// state is entered when coming from [`Inactive`](AppLifecycleState::Inactive), and
324 /// before the [`Inactive`](AppLifecycleState::Inactive) state is entered when coming
325 /// from [`Paused`](AppLifecycleState::Paused). This allows cross-platform implementations
326 /// that want to know when an app is conceptually "hidden" to only write one handler.
327 Hidden,
328
329 /// The application is not currently visible to the user, and not responding to user
330 /// input.
331 ///
332 /// When the application is in this state, the engine will not call
333 /// `PlatformDispatcher.onBeginFrame` and `PlatformDispatcher.onDrawFrame`.
334 ///
335 /// This state is only entered on iOS and Android.
336 Paused,
337}
338
339/// The possible responses to a request to exit the application.
340///
341/// The request is typically responded to by creating an `AppLifecycleListener` and supplying
342/// an `on_exit_requested` callback, or by overriding
343/// `WidgetsBindingObserver::did_request_app_exit`.
344///
345/// Flutter counterpart: `AppExitResponse` (`dart:ui` `platform_dispatcher.dart`).
346#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
347pub enum AppExitResponse {
348 /// Exiting the application can proceed.
349 Exit,
350
351 /// Cancel the exit: do not exit the application.
352 Cancel,
353}
354
355/// The answer to one request to exit, which the host made through
356/// [`EmbedderClient::request_app_exit`](crate::EmbedderClient::request_app_exit): Flutter's reply
357/// to `System.requestAppExit`. It is answered once; dropped unanswered, it answers
358/// [`AppExitResponse::Exit`], since an application that lets go of the question has nothing to
359/// keep.
360pub struct AppExitReply(Option<Box<dyn FnOnce(AppExitResponse)>>);
361
362impl AppExitReply {
363 /// A reply that hands its answer to `send`. The answer is given inside a call into the
364 /// client, so `send` may only post it to the host's own loop, never call the client.
365 pub fn new(send: impl FnOnce(AppExitResponse) + 'static) -> AppExitReply {
366 AppExitReply(Some(Box::new(send)))
367 }
368
369 pub fn answer(mut self, response: AppExitResponse) {
370 self.send(response);
371 }
372
373 fn send(&mut self, response: AppExitResponse) {
374 if let Some(send) = self.0.take() {
375 send(response);
376 }
377 }
378}
379
380impl Drop for AppExitReply {
381 fn drop(&mut self) {
382 self.send(AppExitResponse::Exit);
383 }
384}
385
386impl std::fmt::Debug for AppExitReply {
387 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388 f.debug_struct("AppExitReply")
389 .field("answered", &self.0.is_none())
390 .finish()
391 }
392}
393
394/// The type of application exit to perform when calling `ServicesBinding::exit_application`.
395///
396/// Flutter counterpart: `AppExitType` (`dart:ui` `platform_dispatcher.dart`).
397#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
398pub enum AppExitType {
399 /// Requests that the application start an orderly exit, sending a request back to the
400 /// framework through the `WidgetsBinding`. If that responds with [`AppExitResponse::Exit`],
401 /// then proceed with the same steps as a [`Required`](AppExitType::Required) exit. If that
402 /// responds with [`AppExitResponse::Cancel`], then the exit request is canceled and the
403 /// application continues executing normally.
404 Cancelable,
405
406 /// A non-cancelable orderly exit request. The engine will shut down the engine and call
407 /// the native UI toolkit's exit API.
408 ///
409 /// If you need an even faster and more dangerous exit, then call
410 /// [`std::process::exit`] directly, and even the native toolkit's exit API won't be
411 /// called. This is quite dangerous, though, since it's possible that the engine will
412 /// crash because it hasn't been properly shut down, causing the app to crash on exit.
413 Required,
414}
415
416/// The platform that user interaction should adapt to target.
417///
418/// Flutter counterpart: `TargetPlatform` (`foundation/platform.dart`). Flutter
419/// reads the current one from a library global that consults `dart:io`. Here it
420/// is a plain value type, and the App-owned [`Platform`] reports which one it
421/// is, so two Apps in one process can differ.
422#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
423pub enum TargetPlatform {
424 /// Android: <https://www.android.com/>
425 Android,
426 /// Fuchsia: <https://fuchsia.dev/fuchsia-src/concepts>
427 Fuchsia,
428 /// iOS: <https://www.apple.com/ios/>
429 IOS,
430 /// Linux: <https://www.linux.org>
431 Linux,
432 /// macOS: <https://www.apple.com/macos>
433 MacOS,
434 /// Windows: <https://www.windows.com>
435 Windows,
436}
437
438/// The host's threads as any thread reaches them: the two things the framework asks of them.
439/// gpui's `PlatformDispatcher`. Flutter's embedder API has the first as `post_task_callback`,
440/// with its target time, and keeps the second — the engine's own worker threads — to itself.
441pub trait Dispatcher: Send + Sync {
442 /// Sets when the host should next wake the application for a timer.
443 ///
444 /// The host keeps one such time. When it arrives, the host calls
445 /// [`EmbedderClient::wake`](crate::EmbedderClient::wake) on the main thread.
446 ///
447 /// `None` means no timer is waiting, so the host should not wake for one.
448 ///
449 /// Each call replaces the previous one. The new time can be later than the old one, not
450 /// only earlier. Call this only from the thread the application runs on.
451 fn wake_at(&self, timer_wakeup: Option<Instant>);
452
453 /// Asks the host to wake the application as soon as it can, because a task became ready
454 /// to run.
455 ///
456 /// The next wake clears this request. It does not change the timer wakeup set by
457 /// [`wake_at`](Self::wake_at), which is still waiting for its own time. Call this from
458 /// any thread.
459 fn wake_now(&self);
460
461 /// Runs `work` off the main thread, on whatever the host has for that, such as a system
462 /// queue or a worker thread. The framework's `run_in_background` sends its work here.
463 fn dispatch(&self, work: Box<dyn FnOnce() + Send>);
464}
465
466/// A dispatcher for tests, which pump the application by hand: it never wakes the application,
467/// and work runs at once on the calling thread, so its result is there at the next checkpoint.
468pub struct InertDispatcher;
469
470impl Dispatcher for InertDispatcher {
471 fn wake_at(&self, _timer_wakeup: Option<Instant>) {}
472
473 fn wake_now(&self) {}
474
475 fn dispatch(&self, work: Box<dyn FnOnce() + Send>) {
476 work();
477 }
478}
479
480/// The long-lived host object held by the application.
481///
482/// Implementations must queue requests and return. They must not synchronously
483/// re-enter the [`EmbedderClient`](crate::EmbedderClient) while `App` is active.
484///
485/// A host may offer more than this interface — a picture from a buffer only its system
486/// has, a handle to its renderer. An app that knows its host reaches that through
487/// [`downcast_ref`](dyn Platform::downcast_ref); the interface itself names nothing of any
488/// one system.
489pub trait Platform: Any {
490 /// Which host this is, for behaviour that follows platform convention
491 /// (Flutter `defaultTargetPlatform`).
492 ///
493 /// Required rather than defaulted: an embedder must say what it is, and a
494 /// default would let one silently claim the wrong conventions.
495 fn target_platform(&self) -> TargetPlatform;
496
497 /// Asks for a frame of `view`: Flutter's `PlatformDispatcher.scheduleFrame`, for one view.
498 ///
499 /// `view` is in the next [`EmbedderClient::frame`](crate::EmbedderClient::frame) of the
500 /// screen it is on once its window is in sight; the host holds the request while the window
501 /// is minimized or occluded. Asked again before then, it is in that refresh once.
502 fn request_frame(&self, view: ViewId);
503
504 /// The host clock used for frame and timer timestamps.
505 fn now(&self) -> Instant;
506
507 /// The host's threads, for waking the application or running work off the main thread: see
508 /// [`Dispatcher`].
509 fn dispatcher(&self) -> Arc<dyn Dispatcher>;
510
511 /// Every view the app has now: those the platform gave it, such as a phone's screen or an
512 /// embedder's views, and those it asked for. An app may run with none, as one on a desktop
513 /// does until it asks.
514 fn views(&self) -> Vec<ViewRef>;
515
516 /// Looks up one of the app's views.
517 fn view(&self, id: ViewId) -> Option<ViewRef>;
518
519 /// Asks for a view in a window configured as `config`, carrying `initial_data`
520 /// ([`View::initial_data`](crate::View::initial_data)), such as which screen to show. A
521 /// desktop makes the window, Android a task of its own, an iPad that has more than one window
522 /// of the app's a window scene; a platform that gives the app its views and makes none, an
523 /// iPhone or an embedder, answers [`ViewError::Unsupported`](crate::ViewError::Unsupported).
524 /// The view
525 /// arrives later, through `EmbedderClient::view_added`, carrying the id answered here; a
526 /// request that fails on the way is reported through `EmbedderClient::view_request_failed`.
527 fn request_view(
528 &self,
529 config: crate::WindowConfig,
530 initial_data: Option<String>,
531 ) -> Result<crate::RequestId, crate::ViewError> {
532 let _ = (config, initial_data);
533 Err(crate::ViewError::Unsupported)
534 }
535
536 /// The full system-reported supported locales of the device (Flutter
537 /// `PlatformDispatcher.locales`), in order of preference; empty until the host
538 /// reports them.
539 fn locales(&self) -> Vec<crate::Locale> {
540 Vec::new()
541 }
542
543 /// Tells the host which locale the application resolved to (Flutter
544 /// `PlatformDispatcher.setApplicationLocale`); the default drops it.
545 fn set_application_locale(&self, locale: &crate::Locale) {
546 let _ = locale;
547 }
548
549 /// The local time zone's offset from UTC at `seconds_since_epoch`, positive east of UTC: the
550 /// Dart VM's `DateTime_timeZoneOffsetInSeconds`, which `DateTime` asks for each local value
551 /// it makes. The instant is already within the years a 32-bit `time_t` holds, as the VM maps
552 /// it (`DateTime`'s equivalent year). The host asks the system on every call, keeping
553 /// nothing, so a change of zone shows in the next value made. The default is UTC's zero, for
554 /// a host with no zone to ask.
555 fn time_zone_offset(&self, seconds_since_epoch: i64) -> crate::SignedDuration {
556 let _ = seconds_since_epoch;
557 crate::SignedDuration::ZERO
558 }
559
560 /// The local time zone's name at `seconds_since_epoch`, as the system gives it (an
561 /// abbreviation such as "CET" on a C library and in a browser, the full name on Windows):
562 /// the Dart VM's `DateTime_timeZoneName`, asked as [`time_zone_offset`](Self::time_zone_offset)
563 /// is. The default is "UTC".
564 fn time_zone_name(&self, seconds_since_epoch: i64) -> String {
565 let _ = seconds_since_epoch;
566 "UTC".to_string()
567 }
568
569 /// Whether briefly displaying the characters as you type in obscured text fields is enabled
570 /// in system settings (Flutter `PlatformDispatcher.brieflyShowPassword`).
571 ///
572 /// Defaults to `true`, dart:ui's value until a host reports the setting. dart:ui has no
573 /// callback for its change: a host answers the setting as it is now, and the framework reads
574 /// it as it needs it, as `EditableText` does at each tick of its cursor.
575 fn briefly_show_password(&self) -> bool {
576 true
577 }
578
579 /// The platform's light/dark preference (Flutter
580 /// `PlatformDispatcher.platformBrightness`).
581 ///
582 /// Defaults to [`Brightness::Light`], matching Flutter's view configuration
583 /// default. A live host that can see the OS theme overrides this.
584 fn platform_brightness(&self) -> Brightness {
585 Brightness::Light
586 }
587
588 /// The route the application was started with (Flutter
589 /// `PlatformDispatcher.defaultRouteName`).
590 ///
591 /// Defaults to `"/"`, Flutter's value for a host that was not asked to open a
592 /// particular route; a host that receives a deep link answers it here.
593 fn default_route_name(&self) -> String {
594 String::from("/")
595 }
596
597 /// The lifecycle state immediately after the application started (Flutter
598 /// `PlatformDispatcher.initialLifecycleState`).
599 ///
600 /// This property will not be updated as the lifecycle changes: a host reports each change
601 /// through `EmbedderClient::app_lifecycle_state_changed`.
602 ///
603 /// It is used to initialize `SchedulerBinding::lifecycle_state` at startup. Defaults to
604 /// `None`, Flutter's empty string: a host that has no state to report yet.
605 fn initial_lifecycle_state(&self) -> Option<AppLifecycleState> {
606 None
607 }
608
609 /// The platform's own font lookup: faces by family name and by codepoint, the way
610 /// Flutter's engine asks the OS. `None` for a host without one; text then shapes only
611 /// against fonts the application registers.
612 fn font_source(&self) -> Option<Box<dyn FontSource>> {
613 None
614 }
615
616 /// Flutter's `txt::GetDefaultFontFamilies()`: the families text uses when its style names
617 /// none, first match first.
618 ///
619 /// The engine decides this per OS, so the host answers it: one on an OS Flutter names gives
620 /// that OS's [`default_font_families`](crate::default_font_families), and one whose fonts are
621 /// not the OS's, as a web page's are not, answers its own. Defaults to `txt/platform.cc`, the
622 /// engine's answer on an OS it has no file of its own for.
623 fn default_font_families(&self) -> Vec<String> {
624 vec![String::from("Arial")]
625 }
626
627 /// Open an encoded image, answering with a codec for its frames.
628 ///
629 /// Flutter dart:ui `instantiateImageCodec`. The host decodes with whatever its platform
630 /// provides and uploads each frame, so the framework never sees pixels and the set of
631 /// readable formats is the platform's rather than the framework's.
632 ///
633 /// The default answers a failure at once, so a host with no decoder leaves nobody waiting.
634 fn open_image_codec(&self, bytes: std::sync::Arc<[u8]>) -> crate::ImageCodecFuture {
635 let _ = bytes;
636 Box::pin(std::future::ready(Err(crate::ImageDecodeError::NoDecoder)))
637 }
638
639 /// An image from pixels the app already holds, with no codec in between: Flutter's
640 /// `decodeImageFromPixels`. `None` when the host has no renderer to put it on yet.
641 fn import_pixels(&self, pixels: valo::PixelBuffer) -> Option<crate::Image> {
642 let _ = pixels;
643 None
644 }
645
646 /// Synchronously creates a handle to an image of `picture`: Flutter's `Picture.toImageSync`.
647 ///
648 /// The returned image will be `width` pixels wide and `height` pixels high. The picture is
649 /// rasterized within the 0 (left), 0 (top), `width` (right), `height` (bottom) bounds.
650 /// Content outside these bounds is clipped. The image lives on the renderer's device, and
651 /// anything drawn with it waits for it there.
652 ///
653 /// It is a call on the platform, where Dart's is on the picture, because only the host
654 /// holds a device to draw on. `None` when the host has no renderer to draw it with.
655 ///
656 /// # Panics
657 ///
658 /// Where `width` or `height` is zero: "Invalid image dimensions.".
659 fn picture_to_image_sync(
660 &self,
661 picture: &crate::Picture,
662 width: u32,
663 height: u32,
664 ) -> Option<crate::Image> {
665 let _ = (picture, width, height);
666 None
667 }
668
669 /// `image`'s pixels read back from the device it lives on, as straight-alpha RGBA: Dart's
670 /// `Image.toByteData(format: ImageByteFormat.rawStraightRgba)`, as a test reads what a widget
671 /// paints. It is a call on the platform, where Dart's is on the image, because only the host
672 /// holds the device; a host answers it through its [`SnapshotDelegate`](crate::SnapshotDelegate).
673 /// [`ImageErrorKind::Unsupported`](crate::image_codecs::ImageErrorKind::Unsupported) where the
674 /// host has no renderer.
675 fn read_image_pixels(
676 &self,
677 image: &crate::Image,
678 ) -> crate::image_codecs::ImageFuture<valo::PixelBuffer> {
679 let _ = image;
680 Box::pin(std::future::ready(Err(
681 crate::image_codecs::ImageError::new(
682 crate::image_codecs::ImageErrorKind::Unsupported,
683 "this host has no renderer to read an image back with",
684 ),
685 )))
686 }
687
688 /// An image of a video frame the app holds, its hardware buffer imported as a texture on the
689 /// renderer's device with no copy ([`import_texture`](Self::import_texture)), holding the frame
690 /// while the image lives: a still picture a media asset read, drawn as any image. Not
691 /// Flutter's: its `Texture` widget draws a source's frames as they come, as `VideoFrameView`
692 /// does. `None` when the host has no renderer to put it on yet, or the renderer's device cannot
693 /// take the frame's memory.
694 fn import_video_frame(&self, frame: &dyn crate::VideoFrame) -> Option<crate::Image> {
695 let _ = frame;
696 None
697 }
698
699 /// An image of a hardware buffer the app holds, imported as a texture on the renderer's device
700 /// with no copy ([`import_texture`](Self::import_texture)), holding the buffer while the image
701 /// lives: an image the hardware codecs decoded, or a buffer the app drew, drawn as any image.
702 /// `None` when the host has no renderer to put it on yet, or the renderer's device cannot take
703 /// the buffer's memory.
704 fn import_hardware_buffer(&self, buffer: &dyn crate::HardwareBuffer) -> Option<crate::Image> {
705 let _ = buffer;
706 None
707 }
708
709 /// `buffer`, one this host handed out and of one plane, imported as a texture on `device` over
710 /// its memory with no copy, as the system's GPU API imports such memory (Metal's texture over
711 /// an `IOSurface`, Vulkan's external memory over an `AHardwareBuffer`): of the buffer's size, for what its
712 /// usage names, sampled where the GPU samples it, drawn into and copied into where it draws
713 /// into it, and copied from whatever its usage. The texture holds the buffer, and a video
714 /// frame's buffer its frame, until the GPU is done with it. The host imports it, as the one
715 /// that knows both the buffer and the device; a buffer names no GPU API. `None` for a buffer
716 /// another host handed out, for a buffer of two planes, which
717 /// [`import_planes`](Self::import_planes) imports, and for a device that cannot take the
718 /// buffer's memory: on Apple platforms a wgpu device not on Metal. Not dart:ui's: Flutter's engine keeps its textures to
719 /// itself.
720 fn import_texture(
721 &self,
722 buffer: &dyn crate::HardwareBuffer,
723 device: &wgpu::Device,
724 ) -> Option<wgpu::Texture> {
725 let _ = (buffer, device);
726 None
727 }
728
729 /// `buffer`, one this host handed out, imported on `device` with no copy as one texture view
730 /// per plane, brightness first, each in the format
731 /// [`HardwareBufferFormat::plane_format`](crate::HardwareBufferFormat::plane_format) names and
732 /// of the size [`plane_size`](crate::HardwareBufferFormat::plane_size) names: what a shader
733 /// samples to convert a decoder's picture to colour with the frame's
734 /// [`VideoFrame::color`](crate::VideoFrame::color). The views are of one texture per plane on
735 /// Metal, which has no texture of two planes, and the plane aspects of one NV12 or P010
736 /// texture on D3D12. A buffer of one plane is one view of its texture, as
737 /// [`import_texture`](Self::import_texture) makes it. Each view holds its texture, and the
738 /// texture the buffer, and a frame's buffer its frame, until the GPU is done with it. `None`
739 /// for a buffer another host handed out, for a device that cannot take its memory or sample
740 /// its planes' formats, and on a host that imports no planes.
741 fn import_planes(
742 &self,
743 buffer: &dyn crate::HardwareBuffer,
744 device: &wgpu::Device,
745 ) -> Option<Vec<wgpu::TextureView>> {
746 let _ = (buffer, device);
747 None
748 }
749
750 /// The GPU `device` runs on, as its system names it: what an app that draws with `device`
751 /// asks for its decoders and allocator with, `platform.gpu(platform.gpu_id(&device))`, so
752 /// their memory opens on that device. `None` where the system names no GPU (Apple's systems,
753 /// Android), and for a device whose backend says nothing of its GPU (OpenGL, a Vulkan driver
754 /// without `VK_EXT_physical_device_drm`). Only the host reads it, as the one that knows which
755 /// backend the device is on.
756 fn gpu_id(&self, device: &wgpu::Device) -> Option<crate::GpuId> {
757 let _ = device;
758 None
759 }
760
761 /// The GPU `id` names, or the system's default where `None`, with what the system makes for
762 /// it: its video decoders and its hardware buffer allocator. `None` where the system has no
763 /// such GPU, and where it hands out nothing for any. Apple's systems and Android have one,
764 /// whatever `id` names, as their memory opens on any of the machine's GPUs.
765 fn gpu(&self, id: Option<crate::GpuId>) -> Option<Rc<dyn crate::SystemGpu>> {
766 let _ = id;
767 None
768 }
769
770 /// The host's compositor, where it has one: composition layers shown beside the
771 /// framework's picture. `None` on the web, on X11, on the inert host, and on an
772 /// embedder that chose not to have one.
773 fn compositor(&self) -> Option<Arc<dyn crate::Compositor>> {
774 None
775 }
776
777 /// Flutter's `VsyncWaiter`, for any screen: the refreshes the host draws the framework's
778 /// frames at, for a producer that paces by them, as a composition layer's does. `None` for a
779 /// host without screen ticks.
780 fn vsync_waiter(&self) -> Option<Arc<dyn crate::VsyncWaiter>> {
781 None
782 }
783
784 /// The screens the app's views are on, and where the pointer is on them (Flutter
785 /// `PlatformDispatcher.displays`), or `None` where the host has none to report. Every host
786 /// with screens answers, a phone with its one included; a view's metrics name the screen it
787 /// is on, and a host that hears the screens change says so through
788 /// `EmbedderClient::screens_changed`.
789 fn screens(&self) -> Option<&dyn Screens> {
790 None
791 }
792
793 /// The system clipboard, or `None` where the host has none.
794 fn clipboard(&self) -> Option<&dyn Clipboard> {
795 None
796 }
797
798 /// The system UI drawn around the app, or `None` where the host has none.
799 fn system_chrome(&self) -> Option<&dyn SystemChrome> {
800 None
801 }
802
803 /// Haptic feedback on the device, or `None` where the host has none.
804 fn haptics(&self) -> Option<&dyn Haptics> {
805 None
806 }
807
808 /// The system's own menu over a text selection, or `None` where the host has none.
809 fn system_context_menu(&self) -> Option<&dyn SystemContextMenu> {
810 None
811 }
812
813 /// The app's menu bar, or `None` where the system has none and the app draws its own, as on
814 /// Windows, Linux and phones (`menus`).
815 fn menu_bar(&self) -> Option<&dyn MenuBar> {
816 None
817 }
818
819 /// Menus the system opens at a point in a view, or `None` where the system has none and the
820 /// framework draws them.
821 fn popup_menus(&self) -> Option<&dyn PopupMenus> {
822 None
823 }
824
825 /// The app's icons in the system's tray, or `None` where the system has no tray.
826 fn tray_icons(&self) -> Option<&dyn TrayIcons> {
827 None
828 }
829
830 /// The system's file dialogs, or `None` where the system has none.
831 fn file_dialogs(&self) -> Option<&dyn FileDialogs> {
832 None
833 }
834
835 /// The system's HTTP client, or `None` where the host has none. A client sends every method,
836 /// streams bodies both ways, follows redirects as the request asks, and cancels a transfer
837 /// dropped mid-way; `NetworkImage` fetches through it, and an app may as well. A host that
838 /// carries the system's session honours its proxy and its certificates.
839 fn http(&self) -> Option<&dyn HttpClient> {
840 None
841 }
842
843 /// The system's file system, or `None` where the host has none, as a browser tab has none.
844 /// Every path an app reads or writes goes through it, a picked file's among them
845 /// ([`PickedFile::read_all`](crate::PickedFile::read_all)); `FileImage` reads through it.
846 fn files(&self) -> Option<&dyn Files> {
847 None
848 }
849
850 /// The system's media players, or `None` where the host has none.
851 fn players(&self) -> Option<&dyn crate::Players> {
852 None
853 }
854
855 /// The system's reading of media without playing it, or `None` where the host has none.
856 fn media_assets(&self) -> Option<&dyn crate::MediaAssets> {
857 None
858 }
859
860 /// The system's image codecs, or `None` where the host has none.
861 fn image_codecs(&self) -> Option<&dyn crate::image_codecs::ImageCodecs> {
862 None
863 }
864
865 /// The system's cameras, or `None` where the host has none. A host with cameras answers
866 /// one with none attached as an empty list.
867 fn cameras(&self) -> Option<&dyn crate::Cameras> {
868 None
869 }
870
871 /// The system's frame readers, which a player or a camera hands its frames to, or `None`
872 /// where the system hands out no frames.
873 fn video_frame_readers(&self) -> Option<&dyn crate::VideoFrameReaders> {
874 None
875 }
876
877 /// The user's caption settings, or `None` where the system keeps none, as Linux and the web
878 /// keep none.
879 fn caption_settings(&self) -> Option<&dyn crate::CaptionSettings> {
880 None
881 }
882
883 /// What the app embeds views of its own with, on layers it makes and places, or `None` where
884 /// the host cannot draw a view into such a layer: everywhere but macOS today.
885 fn view_embedder(&self) -> Option<&dyn crate::ViewEmbedder> {
886 None
887 }
888
889 /// The menu of the app's Dock icon, or `None` where the system has no Dock.
890 fn dock_menu(&self) -> Option<&dyn DockMenu> {
891 None
892 }
893
894 /// The system services a selection toolbar offers, or `None` where the host has none.
895 fn text_services(&self) -> Option<&dyn TextServices> {
896 None
897 }
898
899 /// Application state kept across relaunches, or `None` where the host has none.
900 fn restoration(&self) -> Option<&dyn Restoration> {
901 None
902 }
903
904 /// Quitting at the application's own request, or `None` where the host cannot quit
905 /// itself: a phone, a browser tab.
906 fn app_exit(&self) -> Option<&dyn AppExit> {
907 None
908 }
909
910 /// The system's way to open links and files in other apps, or `None` where it has none.
911 fn opener(&self) -> Option<&dyn Opener> {
912 None
913 }
914
915 /// The system's notifications, or `None` where it has none for the app.
916 fn notifications(&self) -> Option<&dyn Notifications> {
917 None
918 }
919}
920
921impl dyn Platform {
922 /// The host as its own type, for what it offers beyond the interface.
923 pub fn downcast_ref<T: Platform>(&self) -> Option<&T> {
924 (self as &dyn Any).downcast_ref::<T>()
925 }
926}
927
928/// Flutter's `SystemChrome`: the system UI around the app as a whole. The overlays drawn over a
929/// view are its host's ([`ViewHost::system_bars`](crate::ViewHost::system_bars)).
930pub trait SystemChrome {
931 /// Describes the app in the host's application switcher (Flutter
932 /// `SystemChrome.setApplicationSwitcherDescription`).
933 fn set_application_switcher_description(&self, description: &ApplicationSwitcherDescription);
934}
935
936/// Flutter's `HapticFeedback`.
937pub trait Haptics {
938 /// Plays haptic feedback on the device (Flutter's `HapticFeedback.vibrate`
939 /// message on `SystemChannels.platform`).
940 fn feedback(&self, kind: HapticFeedbackType);
941}
942
943/// Flutter's `SystemContextMenu`: the system's own menu over a text selection.
944pub trait SystemContextMenu {
945 /// Shows the system context menu (Flutter's `ContextMenu.showSystemContextMenu`).
946 ///
947 /// `items` is `None` for the deprecated call that lets the platform pick default
948 /// buttons. Built-in items are performed by the host; custom items are reported
949 /// through [`crate::EmbedderClient::custom_context_menu_action`].
950 fn show(&self, target_rect: Rect, items: Option<&[SystemContextMenuItem]>);
951
952 /// Hides the system context menu (Flutter's `ContextMenu.hideSystemContextMenu`).
953 fn hide(&self);
954}
955
956/// The screens the app's views are on: what drawing on each needs, as Flutter's
957/// `PlatformDispatcher.displays` lists them, and where each is, for an app that places a window
958/// against something on them, such as an edge or its own icon, which Flutter's `Display` has no
959/// place for. Positions are in the coordinates of [`HostWindow::frame`](crate::HostWindow::frame):
960/// logical points from the top-left corner of the main screen, y growing down.
961pub trait Screens {
962 /// The screens, the main one first: the one positions start from.
963 fn screens(&self) -> Vec<Screen>;
964
965 /// Where the pointer is now, over a window of the app or not. `None` when the host cannot
966 /// say.
967 fn pointer_location(&self) -> Option<Offset>;
968}
969
970/// Names a screen: Flutter's `Display.id`, which the embedder API calls a
971/// `FlutterEngineDisplayId`. Each host numbers its screens its own way; a screen keeps its
972/// number while it stays connected.
973#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
974#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
975pub struct ScreenId(pub u64);
976
977/// A monitor: where it is (the frames, for placing windows) and what drawing on it needs
978/// (Flutter's `Display`: `id`, `devicePixelRatio`, `refreshRate`; `Display.size` is the frame's
979/// size at `scale`).
980#[derive(Clone, Debug, PartialEq)]
981pub struct Screen {
982 /// Flutter `Display.id`; stable while the screen stays connected.
983 pub id: ScreenId,
984 /// What the system calls it: "Built-in Retina Display". Empty where the host has no name
985 /// for it.
986 pub name: String,
987 /// All of it, in points, placed on the desktop.
988 pub frame: Rect,
989 /// What the system's own bars leave free: the menu bar and the Dock, or the taskbar. The
990 /// whole frame where the host cannot say.
991 pub visible_frame: Rect,
992 /// Flutter `Display.devicePixelRatio`: physical pixels per point, as on every view on the
993 /// screen.
994 pub scale: f64,
995 /// Flutter `Display.refreshRate`, in hertz; none where the host cannot say.
996 pub refresh_rate: Option<f64>,
997}
998
999/// The text services a selection toolbar offers: Flutter's LookUp, SearchWeb and Share
1000/// platform-channel calls.
1001pub trait TextServices {
1002 /// Looks up the given text (Flutter's `LookUp.invoke`).
1003 fn look_up(&self, text: &str);
1004
1005 /// Searches the web for the given text (Flutter's `SearchWeb.invoke`).
1006 fn search_web(&self, text: &str);
1007
1008 /// Shares the given text (Flutter's `Share.invoke`).
1009 fn share(&self, text: &str);
1010}
1011
1012/// Flutter's restoration channel: state kept across relaunches.
1013pub trait Restoration {
1014 /// The restoration data the host kept for this application (the `get` message of
1015 /// Flutter's `SystemChannels.restoration`).
1016 fn get(&self) -> Option<RestorationUpdate>;
1017
1018 /// Hands the host the current restoration data (the `put` message of Flutter's
1019 /// `SystemChannels.restoration`), which keeps it until the operating system asks for it.
1020 fn put(&self, data: RestorationMap);
1021}
1022
1023/// The application quitting itself: the `System.exitApplication` message of Flutter's
1024/// `SystemChannels.platform`, for a required exit. A cancelable exit never reaches the host: the
1025/// framework asks its own listeners first (`ServicesBinding::exit_application`), and quits here
1026/// once they agree.
1027pub trait AppExit {
1028 /// Quits the application the way the system quits one, as Flutter's embedders do, on a
1029 /// later turn of the host's loop, never inside this call.
1030 ///
1031 /// `exit_code` is the process's exit status where the system takes one; Flutter's macOS
1032 /// and Linux embedders ignore it, and a host may too.
1033 fn quit(&self, exit_code: i32);
1034}
1035
1036/// Platform for hand-pumped tests.
1037pub struct InertPlatform;
1038
1039impl Platform for InertPlatform {
1040 /// Android, which is what Flutter's own test binding defaults
1041 /// `debugDefaultTargetPlatform` to: a bare App has no host to speak of,
1042 /// and a deterministic answer beats the machine's.
1043 fn target_platform(&self) -> TargetPlatform {
1044 TargetPlatform::Android
1045 }
1046
1047 fn request_frame(&self, _view: ViewId) {}
1048
1049 fn now(&self) -> Instant {
1050 Instant::now()
1051 }
1052
1053 fn dispatcher(&self) -> Arc<dyn Dispatcher> {
1054 Arc::new(InertDispatcher)
1055 }
1056
1057 fn views(&self) -> Vec<ViewRef> {
1058 Vec::new()
1059 }
1060
1061 fn view(&self, _id: ViewId) -> Option<ViewRef> {
1062 None
1063 }
1064}
1065
1066/// A refresh of a screen, as the host delivers it: Flutter's `FlutterEngineOnVsync`, with the
1067/// platform's clock beside the vsync's.
1068#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1069pub struct Frame {
1070 /// The platform's clock as the host hands the frame over, since the host's origin: what the
1071 /// app's timers run to.
1072 pub elapsed: Duration,
1073 /// The vsync the frame is drawn for, on the same clock as `elapsed`; `None` for a frame drawn
1074 /// outside the display's refresh, as one a resize draws before it returns, whose time is
1075 /// `elapsed`.
1076 pub vsync: Option<FrameVsync>,
1077}
1078
1079/// The times of the vsync a frame is drawn for, on the platform's clock since the host's origin:
1080/// `FlutterEngineOnVsync`'s `frame_start_time_nanos` and `frame_target_time_nanos`.
1081///
1082/// The framework's frame time is `target`, as Flutter's engine hands `_beginFrame` the target time
1083/// (`Animator::BeginFrame`), so animations step by the refresh, not by when a frame's drawing
1084/// happened to start. A later editor must keep both on the clock of [`Frame::elapsed`], so the
1085/// framework can set them against its timers.
1086#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1087pub struct FrameVsync {
1088 /// When the vsync occurred, or will: no later than the frame is handed over.
1089 pub start: Duration,
1090 /// When the host expects the next vsync, the one the frame's picture is for: one refresh
1091 /// after `start`, or `start` where the host knows no refresh period.
1092 pub target: Duration,
1093}
1094
1095#[cfg(test)]
1096mod tests {
1097 use super::{Brightness, InertPlatform, Platform, TargetPlatform};
1098
1099 #[test]
1100 fn inert_platform_is_android() {
1101 assert_eq!(InertPlatform.target_platform(), TargetPlatform::Android);
1102 }
1103
1104 #[test]
1105 fn inert_platform_briefly_shows_passwords() {
1106 assert!(InertPlatform.briefly_show_password());
1107 }
1108
1109 #[test]
1110 fn inert_platform_brightness_is_light() {
1111 assert_eq!(InertPlatform.platform_brightness(), Brightness::Light);
1112 }
1113
1114 #[test]
1115 fn a_platform_downcasts_to_its_own_type_and_no_other() {
1116 struct Other;
1117 impl Platform for Other {
1118 fn target_platform(&self) -> TargetPlatform {
1119 TargetPlatform::Linux
1120 }
1121 fn request_frame(&self, _view: super::ViewId) {}
1122 fn now(&self) -> super::Instant {
1123 super::Instant::now()
1124 }
1125 fn dispatcher(&self) -> std::sync::Arc<dyn super::Dispatcher> {
1126 std::sync::Arc::new(super::InertDispatcher)
1127 }
1128 fn views(&self) -> Vec<super::ViewRef> {
1129 Vec::new()
1130 }
1131 fn view(&self, _id: super::ViewId) -> Option<super::ViewRef> {
1132 None
1133 }
1134 }
1135 let platform: super::PlatformRef = std::rc::Rc::new(InertPlatform);
1136 assert!(platform.downcast_ref::<InertPlatform>().is_some());
1137 assert!(platform.downcast_ref::<Other>().is_none());
1138 }
1139}