waft_embedder/views.rs
1//! Flutter counterpart: dart:ui `FlutterView`. The host owns the native
2//! window; this stable handle exposes its identity and current configuration.
3
4use crate::{
5 Matrix4, Rect, ScreenId, SelectionRect, Size, SystemMouseCursorKind, SystemUiOverlayStyle,
6 TextEditingValue, TextInputConfiguration,
7};
8
9/// Opaque id for one [`View`] (`FlutterView.viewId`).
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct ViewId(pub u64);
13
14/// An event for the engine to communicate view focus changes to the app.
15/// Flutter counterpart: `ViewFocusEvent` in `dart:ui/platform_dispatcher.dart`.
16#[derive(Clone, Copy, Debug)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct ViewFocusEvent {
19 /// The ID of the view that experienced a focus change.
20 pub view_id: ViewId,
21 /// The state focus changed to.
22 pub state: ViewFocusState,
23 /// The direction focus changed to.
24 pub direction: ViewFocusDirection,
25}
26
27/// Represents the focus state of a given view.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30pub enum ViewFocusState {
31 /// The view does not have platform focus.
32 Unfocused,
33 /// The view has platform focus.
34 Focused,
35}
36
37/// Represents the direction in which focus transitioned across views.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub enum ViewFocusDirection {
41 /// The transition did not have a direction, such as a programmatic request or focus loss.
42 Undefined,
43 /// The transition was forward, typically from pressing Tab.
44 Forward,
45 /// The transition was backward, typically from pressing Shift+Tab.
46 Backward,
47}
48
49/// Physical padding on each side of a view (`dart:ui` `ViewPadding`).
50#[derive(Clone, Copy, Debug, PartialEq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
52pub struct ViewPadding {
53 pub left: f64,
54 pub top: f64,
55 pub right: f64,
56 pub bottom: f64,
57}
58
59impl ViewPadding {
60 /// A view padding that has zeros for each edge.
61 pub const ZERO: ViewPadding = ViewPadding {
62 left: 0.0,
63 top: 0.0,
64 right: 0.0,
65 bottom: 0.0,
66 };
67}
68
69/// The strip along a view's top that the system's window buttons sit in, as Windows's
70/// `AppWindowTitleBar` reports it (`Height`, `LeftInset`, `RightInset`) and the web's window
71/// controls overlay its title bar area. The view's padding already keeps content below it; a title
72/// bar that draws in the strip keeps its items clear of the insets.
73#[derive(Clone, Copy, Debug, PartialEq)]
74#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
75pub struct TitleBarArea {
76 /// How far the strip reaches down from the view's top.
77 pub height: f64,
78 /// How much of the strip the system keeps from its left end: its buttons where they are on
79 /// that side, else as much as the window's rounded corner takes.
80 pub left_inset: f64,
81 /// How much of the strip the system keeps from its right end, as `left_inset` is kept.
82 pub right_inset: f64,
83}
84
85/// Immutable layout constraints for a view (`dart:ui` `ViewConstraints`).
86#[derive(Clone, Copy, Debug, PartialEq)]
87#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
88pub struct ViewConstraints {
89 pub min_width: f64,
90 pub max_width: f64,
91 pub min_height: f64,
92 pub max_height: f64,
93}
94
95impl ViewConstraints {
96 pub const fn new(
97 min_width: f64,
98 max_width: f64,
99 min_height: f64,
100 max_height: f64,
101 ) -> ViewConstraints {
102 ViewConstraints {
103 min_width,
104 max_width,
105 min_height,
106 max_height,
107 }
108 }
109
110 /// Constraints respected only by the given size.
111 pub const fn tight(width: f64, height: f64) -> ViewConstraints {
112 ViewConstraints {
113 min_width: width,
114 max_width: width,
115 min_height: height,
116 max_height: height,
117 }
118 }
119}
120
121impl Default for ViewConstraints {
122 fn default() -> ViewConstraints {
123 ViewConstraints {
124 min_width: 0.0,
125 max_width: f64::INFINITY,
126 min_height: 0.0,
127 max_height: f64::INFINITY,
128 }
129 }
130}
131
132/// Per-view geometry the host reports (`_ViewConfiguration` fields we use).
133#[derive(Clone, Copy, Debug, PartialEq)]
134#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
135pub struct ViewMetrics {
136 pub physical_size: [f64; 2],
137 pub physical_constraints: ViewConstraints,
138 pub device_pixel_ratio: f64,
139 pub padding: ViewPadding,
140 pub view_padding: ViewPadding,
141 pub view_insets: ViewPadding,
142 /// The physical pixels on each side of the view that it can draw into but where the system
143 /// takes input gestures for its navigation, as a swipe in from an edge goes back:
144 /// `_ViewConfiguration.systemGestureInsets`, which `FlutterView.systemGestureInsets` reads.
145 pub system_gesture_insets: ViewPadding,
146 /// The screen the view is on, one of `Platform::screens`: `_ViewConfiguration.displayId`,
147 /// which `FlutterView.display` looks up. `None` while it is on none the host can name, as a
148 /// view without a window is.
149 pub screen: Option<ScreenId>,
150 /// The strip the system's window buttons sit in over the view, in physical pixels, which
151 /// `view_padding.top` already covers; `None` while no buttons are over the view, as in full
152 /// screen and on a phone. dart:ui has no counterpart.
153 pub title_bar_area: Option<TitleBarArea>,
154}
155
156impl Default for ViewMetrics {
157 fn default() -> ViewMetrics {
158 ViewMetrics {
159 physical_size: [0.0, 0.0],
160 physical_constraints: ViewConstraints::tight(0.0, 0.0),
161 device_pixel_ratio: 1.0,
162 padding: ViewPadding::ZERO,
163 view_padding: ViewPadding::ZERO,
164 view_insets: ViewPadding::ZERO,
165 system_gesture_insets: ViewPadding::ZERO,
166 screen: None,
167 title_bar_area: None,
168 }
169 }
170}
171
172/// A `null` field indicates that the platform or view does not have a preference
173/// and the fallback constants should be used instead.
174///
175/// Flutter counterpart: `GestureSettings` (`dart:ui` `window.dart`).
176#[derive(Clone, Copy, Debug, Default, PartialEq)]
177pub struct GestureSettings {
178 /// The number of physical pixels a pointer is allowed to drift before it is
179 /// considered an intentional movement.
180 ///
181 /// If `None`, the framework's default touch slop configuration should be used
182 /// instead.
183 pub physical_touch_slop: Option<f64>,
184
185 /// The number of physical pixels that the first and second tap of a double tap
186 /// can drift apart to still be recognized as a double tap.
187 ///
188 /// If `None`, the framework's default double tap slop configuration should be used
189 /// instead.
190 pub physical_double_tap_slop: Option<f64>,
191}
192
193impl GestureSettings {
194 /// Create a new [`GestureSettings`] object from an existing value, overwriting
195 /// all of the provided fields.
196 pub fn copy_with(
197 self,
198 physical_touch_slop: Option<f64>,
199 physical_double_tap_slop: Option<f64>,
200 ) -> GestureSettings {
201 GestureSettings {
202 physical_touch_slop: physical_touch_slop.or(self.physical_touch_slop),
203 physical_double_tap_slop: physical_double_tap_slop.or(self.physical_double_tap_slop),
204 }
205 }
206}
207
208/// A stable handle to one host-provided view.
209///
210/// [`present`](View::present) is Flutter `FlutterView.render`. The host owns
211/// the surface; the framework builds a [`crate::Scene`] and hands it over. It is [`Any`], so
212/// whoever made a view of its own type, a test among them, finds it again among the platform's.
213///
214/// [`Any`]: std::any::Any
215pub trait View: std::any::Any {
216 fn id(&self) -> ViewId;
217 fn metrics(&self) -> ViewMetrics;
218
219 /// Flutter `FlutterView.gestureSettings`.
220 fn gesture_settings(&self) -> GestureSettings {
221 GestureSettings::default()
222 }
223
224 /// Renders and presents one scene, the frame's layer tree, shared so the host may keep it: to
225 /// present it again when the window is seen again, and to tell a scene equal to the last from
226 /// one worth drawing. Physical pixels; the presenter applies no extra scaling.
227 /// [`slices`](crate::slices) makes of it the picture a host draws and the composition layers a
228 /// host with a compositor places in the same native transaction; a host without one draws the
229 /// picture alone.
230 ///
231 /// `size` is the size the view laid itself out at, in physical pixels, within its
232 /// [`physical_constraints`](ViewMetrics::physical_constraints): Flutter's
233 /// `FlutterView.render(scene, size:)`. Where the constraints are tight it is the size they
234 /// give; where they are loose it is the size of the view's content, which the host shows the
235 /// frame at and tells the view's host of ([`ViewHost::view_size_changed`]).
236 fn present(&self, scene: std::sync::Arc<crate::Scene>, size: Size);
237
238 /// What the view asks of the system: its input methods, its cursor and its focus.
239 fn host(&self) -> &dyn ViewHost;
240
241 /// What whoever gave or asked for this view attached to it, such as which screen to show:
242 /// what the app asked for it with ([`crate::Platform::request_view`]), or what an embedder
243 /// said, as Flutter web's `initialData` does. `None` for a view with none.
244 fn initial_data(&self) -> Option<String> {
245 None
246 }
247
248 /// The request this view arrived for ([`crate::Platform::request_view`],
249 /// [`ViewEmbedder::add_view`]); `None` for a view the platform gave the app unasked.
250 fn request_id(&self) -> Option<crate::RequestId> {
251 None
252 }
253
254 /// The window this view is in, where the platform lets the app manage it, as `NSView.window`
255 /// answers: every window on a desktop, whether the app asked for it or the platform gave it,
256 /// such as WaOS's window around a program's view, every activity's task on Android, and every
257 /// window scene on an iPad that has more than one. `None` for a view in nothing the app may
258 /// manage: an iPhone's screen, a web page's element, a host app's view. Closing a view is its
259 /// window's: a view with none is not the app's to close, and its way out is to quit.
260 fn window(&self) -> Option<crate::WindowRef> {
261 None
262 }
263}
264
265/// What one view asks of the system, provided by whoever hosts the view: a window's view gets its
266/// window's. Chromium's `RenderWidgetHostView` and Android's `SurfaceControlViewHost` are this
267/// piece; where Flutter's embedders take the same requests on the platform as a whole, through
268/// `SystemChannels.textInput`, `SystemChannels.mouseCursor`, `SystemChannels.platform` and
269/// `PlatformDispatcher.requestViewFocusChange`, here each view's own host takes them.
270pub trait ViewHost {
271 /// The input methods that edit text in this view; none where it takes no text.
272 fn text_input(&self) -> Option<&dyn TextInputHost>;
273
274 /// Shows a system cursor for a pointing device over this view: Flutter's
275 /// `activateSystemCursor` message on `SystemChannels.mouseCursor`. A host with one cursor for
276 /// every view shows it wherever the pointer is.
277 fn activate_system_cursor(&self, device: i64, kind: SystemMouseCursorKind);
278
279 /// Flutter's `PlatformDispatcher.requestViewFocusChange` for this view: asks the system to move
280 /// the input focus to it, or away from it. A host whose system has no focus to move ignores
281 /// it. The view's window is not brought forward:
282 /// [`HostWindow::activate`](crate::HostWindow::activate) does that.
283 fn request_focus_change(&self, state: ViewFocusState, direction: ViewFocusDirection);
284
285 /// Informs the host of whether or not the framework will handle back events in this view
286 /// (Flutter `SystemNavigator.setFrameworkHandlesBack`): whether a navigator in the view has a
287 /// route to pop. A host that hears Back only while the view said it handles it follows it, as
288 /// Android's predictive back does, or one whose view cannot answer a press on the spot.
289 ///
290 /// The default drops it: a host that asks the app on the spot, through
291 /// [`EmbedderClient::pop_route`](crate::EmbedderClient::pop_route), has the answer then and
292 /// needs no notice in advance.
293 fn set_framework_handles_back(&self, handles: bool) {
294 let _ = handles;
295 }
296
297 /// The system's bars over this view, the status bar and on Android the navigation bar; `None`
298 /// where the system draws none over it, as over a desktop's window.
299 fn system_bars(&self) -> Option<&dyn SystemBars>;
300
301 /// The view's frames are `size` physical pixels large from now on, a size other than the
302 /// view had: the size it laid itself out at within loose constraints
303 /// ([`ViewMetrics::physical_constraints`]), which is its content's. Heard with the first frame
304 /// of that size, before that frame shows, so whatever shows the view can take the size with
305 /// the picture: Flutter's Windows embedder tells a view's sizing delegate so
306 /// (`FlutterWindowsViewSizingDelegate::DidUpdateViewSize`), and Chromium a widget's delegate in
307 /// auto-resize mode (`RenderWidgetHostDelegate::ResizeDueToAutoResize`).
308 ///
309 /// The default drops it, for a host that gives its view tight constraints, whose frames are
310 /// the size it gave.
311 fn view_size_changed(&self, size: Size) {
312 let _ = size;
313 }
314}
315
316/// The bars the system draws over a view, the status bar and on Android the navigation bar, which
317/// Flutter's `SystemChrome` speaks to for the app as a whole: each window carries its own bars, so
318/// here they are the view's, as Flutter's Android embedding applies them to its one activity's
319/// window.
320pub trait SystemBars {
321 /// Styles the bars (Flutter `SystemChrome.setSystemUIOverlayStyle`).
322 fn set_overlay_style(&self, style: &SystemUiOverlayStyle);
323
324 /// Hides the bars until [`show`](Self::show); what a swipe from a screen's edge does meanwhile
325 /// is `behavior`'s. Flutter's `SystemUiMode.immersive` is `hide(ShowBarsBySwipe)`,
326 /// `immersiveSticky` is `hide(ShowTransientBarsBySwipe)`.
327 fn hide(&self, behavior: SystemBarsBehavior);
328
329 /// Shows the bars again, drawn over the view: how a view starts. Flutter's
330 /// `SystemUiMode.edgeToEdge`.
331 fn show(&self);
332}
333
334/// What a swipe from a screen's edge does while the bars are hidden: Android's
335/// `WindowInsetsController.setSystemBarsBehavior`.
336#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
337pub enum SystemBarsBehavior {
338 /// The swipe brings the bars back, and they stay; the system acts on it as usual. Android's
339 /// `BEHAVIOR_SHOW_BARS_BY_SWIPE`.
340 ShowBarsBySwipe,
341 /// The swipe shows the bars for a moment, over the view, which keeps the touch; a second swipe
342 /// acts. Android's `BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE`, iOS's deferred edge gestures. For
343 /// a game, where a stray swipe must not leave it.
344 ShowTransientBarsBySwipe,
345}
346
347/// The host side of Flutter's text input connection for one view: the calls Flutter's framework
348/// sends its engine on the `flutter/textinput` channel, one method each.
349///
350/// A client is one text field's connection: [`set_client`](Self::set_client) starts a new one,
351/// which a host whose input method keeps state by the field it edits, as UIKit does, gives a field
352/// of its own; [`update_config`](Self::update_config) changes the current one's configuration.
353pub trait TextInputHost {
354 /// Flutter `TextInput.setClient`: a new client, configured with `configuration`, has the
355 /// connection from now on. The keyboard shows only at [`show`](Self::show).
356 fn set_client(&self, configuration: &TextInputConfiguration);
357
358 /// Flutter `TextInput.show`: the input method shows for the current client.
359 fn show(&self);
360
361 /// Flutter `TextInput.updateConfig`: the current client's configuration changed.
362 fn update_config(&self, configuration: &TextInputConfiguration);
363
364 /// Flutter `TextInput.clearClient`: the current client gave the connection up. The keyboard
365 /// stays until [`hide`](Self::hide), so a field taking the connection next keeps it up.
366 fn clear_client(&self);
367
368 /// Flutter `TextInput.hide`: the input method goes.
369 fn hide(&self);
370
371 /// Flutter `TextInputConnection.setEditingState`.
372 fn set_editing_state(&self, value: &TextEditingValue);
373
374 /// Flutter `TextInput.setComposingRect`.
375 fn set_composing_rect(&self, rect: Rect);
376
377 /// Flutter `TextInput.setCaretRect`.
378 fn set_caret_rect(&self, rect: Rect);
379
380 /// Flutter `TextInput.setEditableSizeAndTransform`.
381 fn set_client_geometry(&self, size: Size, transform: &Matrix4);
382
383 /// Flutter `TextInput.setSelectionRects`: the bounds of each grapheme of the field's text in
384 /// sight, in the field's coordinates, which [`set_client_geometry`](Self::set_client_geometry)
385 /// takes to the view's. Flutter's framework sends them on iOS alone, while stylus handwriting is
386 /// enabled, for the system's text input to place its caret, its candidates and its menus.
387 ///
388 /// The default drops them, for a host whose input methods take no geometry beyond the caret.
389 fn set_selection_rects(&self, selection_rects: &[SelectionRect]) {
390 let _ = selection_rects;
391 }
392
393 /// Whether this text input turns editing keys into edits before the framework sees
394 /// them: backspace and delete, caret movement, the line and document ends.
395 ///
396 /// Flutter has no such question because each of its embedders is written for one host:
397 /// its macOS and iOS embedders do interpret those keys, and its text field bindings for
398 /// those platforms step aside so a key is not acted on twice.
399 ///
400 /// Defaults to false, which is what a host built on a windowing library that reports
401 /// plain key presses should answer, whichever platform it runs on. A host that hands the
402 /// framework the operating system's own editing commands answers true, and the field
403 /// then leaves those keys to it.
404 fn handles_editing_keys(&self) -> bool {
405 false
406 }
407
408 /// Whether the host sends the view Edit's commands as events through a command of its own,
409 /// which the user's ⌘C, ⌘X and ⌘V reach once the framework leaves them unhandled: macOS's Edit
410 /// menu, or the host's of a program that runs inside another app. A text field then leaves
411 /// those keys unhandled and acts on the `clipboard_event` the command sends, as Flutter's text
412 /// fields on the web leave them to the browser.
413 ///
414 /// Defaults to false: a host whose system has no such command, or whose app may have set a
415 /// menu bar without Edit's commands, keeps them in the field.
416 fn provides_edit_commands(&self) -> bool {
417 false
418 }
419}
420
421/// What the app uses to embed views of its own, as Flutter's embedder does: adding one on a layer
422/// it makes and places, which answers the view's handle ([`EmbeddedView`]), and handing any view
423/// input ([`Platform::view_embedder`](crate::Platform::view_embedder)).
424pub trait ViewEmbedder {
425 /// Flutter's `AddView`, for the app: asks for a view that draws into `layer`, which the app
426 /// made with the platform's [`compositor`](crate::Platform::compositor), opaque or not, and
427 /// places itself, at `metrics`, asking what it asks of the system of `host`. Constraints in
428 /// `metrics` that are not tight leave the view's size to its content, within them, and `host`
429 /// hears it with each frame of a new size ([`ViewHost::view_size_changed`]). The view arrives
430 /// as a window's does, through `EmbedderClient::view_added`, carrying the handle's request id
431 /// ([`View::request_id`]) and `initial_data` ([`View::initial_data`]), which says what it is
432 /// for, as a window's does (`Platform::request_view`); it is in sight until the app says
433 /// otherwise ([`EmbeddedView::set_in_sight`]), its frames follow the screen its metrics name,
434 /// and it is removed when the handle is dropped. Refused at once, with
435 /// [`ViewError::Unsupported`](crate::ViewError::Unsupported), where the host cannot draw a
436 /// view into `layer`.
437 fn add_view(
438 &self,
439 layer: &std::sync::Arc<dyn crate::CompositionLayer>,
440 metrics: ViewMetrics,
441 host: std::rc::Rc<dyn ViewHost>,
442 initial_data: Option<String>,
443 ) -> Result<EmbeddedView, crate::ViewError>;
444
445 /// Flutter's `SendPointerEvent`, for the app: what pointing devices did over any view, a
446 /// window's included, which the framework hears as it hears the host's own reports
447 /// (`EmbedderClient::pointer_reports`), through the one converter that numbers every pointer.
448 /// Each device of a forwarded stream (its mouse, trackpad and pen, and each touch from landing
449 /// to lifting) takes a device number no other stream uses, a random 64-bit one for now, since
450 /// the converter keeps one state per device number, a forwarding app's own host numbers its
451 /// devices as this one does, 0, 1, 2 upward, and two streams with no order between them would
452 /// mix their devices' states in one (native-surfaces decision 36).
453 fn send_pointer_reports(&self, reports: Vec<crate::PointerReport>);
454
455 /// Flutter's `SendViewFocusEvent`, for the app: a view's focus change, which the framework
456 /// hears as it hears the host's own (`EmbedderClient::view_focus_changed`), so that the keys
457 /// the host reports go where the framework's focus is.
458 fn send_view_focus_event(&self, event: ViewFocusEvent);
459}
460
461/// A view the app added on a layer of its own ([`ViewEmbedder::add_view`]): the app gives it its
462/// metrics and says whether it is in sight, as only the app knows where it placed the layer, and
463/// the view lives as long as this handle: dropping it removes the view, as Flutter's embedder API
464/// removes one with `RemoveView` and Android's `SurfaceControlViewHost` with `release`.
465pub struct EmbeddedView {
466 request_id: crate::RequestId,
467 host: Box<dyn HostEmbeddedView>,
468}
469
470impl EmbeddedView {
471 /// The handle a host answers for a view the app added: the request the view arrives for, and
472 /// the host's side of the view, which the handle's calls reach.
473 pub fn new(request_id: crate::RequestId, host: Box<dyn HostEmbeddedView>) -> EmbeddedView {
474 EmbeddedView { request_id, host }
475 }
476
477 /// The request the view arrives for, as its [`View::request_id`], through
478 /// `EmbedderClient::view_added`.
479 pub fn request_id(&self) -> crate::RequestId {
480 self.request_id
481 }
482
483 /// Flutter's `SendWindowMetricsEvent`: the view takes `metrics`, which the framework hears of
484 /// through `EmbedderClient::view_metrics_changed`.
485 pub fn set_metrics(&self, metrics: ViewMetrics) {
486 self.host.set_metrics(metrics);
487 }
488
489 /// Whether the view is in sight, as only the app knows where it placed the view's layer: its
490 /// frames are held while it is not, as a window's are while the window is minimized or
491 /// occluded.
492 pub fn set_in_sight(&self, in_sight: bool) {
493 self.host.set_in_sight(in_sight);
494 }
495}
496
497impl Drop for EmbeddedView {
498 /// Flutter's `RemoveView`: the view lets go of its layer, and the framework hears of it
499 /// through `EmbedderClient::view_removed`.
500 fn drop(&mut self) {
501 self.host.remove();
502 }
503}
504
505impl std::fmt::Debug for EmbeddedView {
506 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
507 f.debug_struct("EmbeddedView")
508 .field("request_id", &self.request_id)
509 .finish_non_exhaustive()
510 }
511}
512
513/// The host's side of a view the app added, which its [`EmbeddedView`]'s calls reach. A host
514/// implements it for the views it embeds, as it implements [`HostWindow`](crate::HostWindow) for
515/// its windows.
516pub trait HostEmbeddedView {
517 /// The view takes `metrics` ([`EmbeddedView::set_metrics`]).
518 fn set_metrics(&self, metrics: ViewMetrics);
519
520 /// The view is in sight or not ([`EmbeddedView::set_in_sight`]).
521 fn set_in_sight(&self, in_sight: bool);
522
523 /// The view is removed, as its handle is dropped.
524 fn remove(&self);
525}