Skip to main content

waft_embedder/
window.rs

1//! Asking for views, and the windows around them. Not a Flutter file.
2//!
3//! An app asks for a view in a window configured as a [`WindowConfig`]
4//! (`Platform::request_view`), and the view arrives later, as every view does, carrying the
5//! request's [`RequestId`], as iOS hands back the activity of `requestSceneSessionActivation` with
6//! the connecting scene. On a desktop the host makes the window; where the platform gives the app
7//! views and makes none, on a phone and when embedded, a request is refused. A view in a window
8//! the app may manage, one it asked for or one the platform gave, has a [`HostWindow`]
9//! (`View::window`): the configuration every window wants up front, whether the window is
10//! minimized or occluded, which the host reports with the window's moves
11//! (`EmbedderClient::window_changed`), the limits the user resizes it within where users resize
12//! windows ([`WindowSizeLimits`]), the native handle for anything beyond it, and the window's
13//! closing, which is how a view closes.
14//!
15//! Flutter's windowing API (`widgets/_window.dart`, experimental) builds window archetypes
16//! over the engine's views, each controller making its window within its constructor.
17
18use std::fmt;
19use std::rc::Rc;
20use std::time::Duration;
21
22pub use raw_window_handle::RawWindowHandle;
23
24use crate::{Rect, Size, ViewRef};
25
26/// How a window is made. Sizes and positions are logical, in the host's screen space with
27/// the origin at the top left of the primary screen.
28///
29/// Every option names what the window is for, not how a system does it: the host maps each
30/// onto what its system has, and one its system lacks it leaves at the system's default.
31/// What no option expresses is set through the window's
32/// [`native_handle`](HostWindow::native_handle).
33#[derive(Clone, Debug, PartialEq)]
34pub struct WindowConfig {
35    pub title: String,
36    pub size: [f64; 2],
37    /// Where the window opens; the host chooses when `None`.
38    pub position: Option<[f64; 2]>,
39    /// The system's title bar and border.
40    pub decorations: bool,
41    pub resizable: bool,
42    pub level: WindowLevel,
43    /// Whether showing or clicking the window makes it the focused one. A host may not be
44    /// able to refuse activation.
45    pub activating: bool,
46    /// Whether the window is on every virtual desktop: macOS Spaces, X11 workspaces.
47    pub all_desktops: bool,
48    pub background: WindowBackground,
49    /// Whether the window casts the system's shadow.
50    pub shadow: bool,
51    pub visible: bool,
52    /// What only macOS windows offer; other systems leave it out.
53    pub macos: MacosWindowConfig,
54}
55
56impl Default for WindowConfig {
57    fn default() -> WindowConfig {
58        WindowConfig {
59            title: String::new(),
60            size: [900.0, 600.0],
61            position: None,
62            decorations: true,
63            resizable: true,
64            level: WindowLevel::Normal,
65            activating: true,
66            all_desktops: false,
67            background: WindowBackground::Solid,
68            shadow: true,
69            visible: true,
70            macos: MacosWindowConfig::default(),
71        }
72    }
73}
74
75/// What a window offers on macOS alone.
76#[derive(Clone, Copy, Debug, Default, PartialEq)]
77pub struct MacosWindowConfig {
78    pub title_bar: MacosTitleBar,
79}
80
81/// The title bar of a macOS window.
82#[derive(Clone, Copy, Debug, Default, PartialEq)]
83pub enum MacosTitleBar {
84    /// The system's, with the window's title in it.
85    #[default]
86    Standard,
87    /// None of its own, as Safari's and Finder's windows: the view runs to the window's top edge,
88    /// and the close, minimize and zoom buttons sit over it, centred in a band `height` points tall
89    /// at the top, as far from the left edge as from the band's top. Presses in the band reach the
90    /// app, which moves the window, and does a title bar's double press, from where it draws
91    /// nothing to press ([`HostWindow::drag`], [`HostWindow::title_bar_double_click_action`]).
92    Hidden { height: f64 },
93}
94
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
96pub enum WindowLevel {
97    #[default]
98    Normal,
99    /// Above ordinary windows, as a palette or a panel sits.
100    AlwaysOnTop,
101    /// Below ordinary windows, as a desktop widget sits.
102    AlwaysOnBottom,
103}
104
105/// What the window shows behind the app's painting. Anything but `Solid` lets what is
106/// behind the window show where the app paints nothing.
107#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
108pub enum WindowBackground {
109    #[default]
110    Solid,
111    Transparent,
112    /// The system's blur of what lies behind the window (macOS vibrancy).
113    Blurred,
114    /// The system's glass material (macOS 26's Liquid Glass); the blur where the system
115    /// has none.
116    Glass,
117}
118
119impl WindowBackground {
120    /// Whether what is behind the window can show through it.
121    pub fn sees_through(self) -> bool {
122        self != WindowBackground::Solid
123    }
124}
125
126/// What a double-click on a window's title bar does
127/// ([`HostWindow::title_bar_double_click_action`]).
128#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
129pub enum TitleBarAction {
130    Maximize,
131    Minimize,
132    Nothing,
133    /// The host can't tell, or the system's setting has a value it doesn't know.
134    #[default]
135    Unknown,
136}
137
138/// The number of a request for a view, which the view carries when it arrives
139/// ([`View::request_id`](crate::View::request_id)).
140#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
141pub struct RequestId(pub u64);
142
143/// Why a request for a view got no view.
144#[derive(Clone, Debug, PartialEq, Eq)]
145pub enum ViewError {
146    /// This platform gives the app its views and makes none on request.
147    Unsupported,
148    Failed(String),
149}
150
151impl fmt::Display for ViewError {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        match self {
154            ViewError::Unsupported => f.write_str("the platform makes no views on request"),
155            ViewError::Failed(reason) => {
156                write!(f, "the platform could not make the view: {reason}")
157            }
158        }
159    }
160}
161
162impl std::error::Error for ViewError {}
163
164pub type WindowRef = Rc<dyn HostWindow>;
165
166/// The window around a view the host puts on screen in a window the app may manage.
167pub trait HostWindow: 'static {
168    fn view(&self) -> ViewRef;
169
170    /// The window's logical frame in screen space.
171    fn frame(&self) -> Rect;
172
173    /// Moves and sizes the window, over `animate` when the host can animate a frame.
174    fn set_frame(&self, frame: Rect, animate: Option<Duration>);
175
176    fn set_title(&self, title: &str);
177
178    fn show(&self);
179
180    fn hide(&self);
181
182    /// Flutter `WindowController.isMinimized`; macOS `isMiniaturized`, Windows `IsIconic`.
183    /// `false` where the system does not tell a client, as Wayland does not.
184    fn is_minimized(&self) -> bool;
185
186    /// Covered all over, or otherwise not shown: macOS's occlusion state without its visible bit,
187    /// winit's `Occluded`. Not in Flutter's controller; Waft's, after the platforms. `false`
188    /// where the system does not tell a window, as Windows and Wayland do not.
189    fn is_occluded(&self) -> bool;
190
191    /// Closes the window; its view goes away with it. The user's asking to close it only reports
192    /// it ([`EmbedderClient::view_close_requested`](crate::EmbedderClient::view_close_requested));
193    /// this closes it.
194    fn close(&self);
195
196    /// The smallest and largest size the user may resize this window to; none where users don't
197    /// resize windows (phones). Flutter `WindowController.setConstraints`.
198    fn size_limits(&self) -> Option<&dyn WindowSizeLimits>;
199
200    /// Starts the system's own move of the window from the press under way, as a press on its
201    /// title bar does: for an app that draws its own ([`MacosTitleBar::Hidden`]). Call it from
202    /// the press.
203    fn drag(&self);
204
205    /// Flutter `WindowController.isMaximized`; on macOS, zoomed.
206    fn is_maximized(&self) -> bool;
207
208    /// Flutter `WindowController.setMaximized`; on macOS, zooms the window or returns it to its
209    /// size from before.
210    fn set_maximized(&self, maximized: bool);
211
212    /// Flutter `WindowController.setMinimized`.
213    fn set_minimized(&self, minimized: bool);
214
215    /// What the system's settings say a double-click on a title bar does, for an app that draws
216    /// its own ([`MacosTitleBar::Hidden`]): macOS's "Double-click a window's title bar to".
217    fn title_bar_double_click_action(&self) -> TitleBarAction {
218        TitleBarAction::Unknown
219    }
220
221    /// The native window, for configuration this interface does not carry.
222    fn native_handle(&self) -> Option<RawWindowHandle>;
223}
224
225/// The limits a window the user resizes keeps its view within, its content without the system's
226/// title bar and border, in logical points: Flutter's `BoxConstraints` on a window, its minimum
227/// and maximum apart. A limit holds from when it is set until it is set again, and `None` removes
228/// it.
229pub trait WindowSizeLimits {
230    fn set_min_size(&self, size: Option<Size>);
231
232    fn set_max_size(&self, size: Option<Size>);
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    #[test]
240    fn a_default_window_is_an_ordinary_visible_one() {
241        let config = WindowConfig::default();
242        assert!(config.decorations && config.visible && config.activating);
243        assert_eq!(config.level, WindowLevel::Normal);
244        assert_eq!(config.background, WindowBackground::Solid);
245        assert_eq!(config.macos.title_bar, MacosTitleBar::Standard);
246    }
247
248    #[test]
249    fn every_background_but_solid_sees_through() {
250        assert!(!WindowBackground::Solid.sees_through());
251        assert!(WindowBackground::Transparent.sees_through());
252        assert!(WindowBackground::Blurred.sees_through());
253        assert!(WindowBackground::Glass.sees_through());
254    }
255}