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, and on Android a task with an
7//! activity of its own; where the platform gives the app views and makes none, on an iPhone and
8//! when embedded, a request is refused. A view in a window
9//! the app may manage, one it asked for or one the platform gave, has a [`HostWindow`]
10//! (`View::window`): the configuration every window wants up front, whether the window is
11//! minimized or occluded, which the host reports with the window's moves
12//! (`EmbedderClient::window_changed`), the limits the user resizes it within where users resize
13//! windows ([`WindowSizeLimits`]), the native handle for anything beyond it, and the window's
14//! closing, which is how a view closes. On Android a window is an activity's task, the card in
15//! Recents: its title and icon are the card's, closing it removes the task, and minimizing it sends
16//! the task to the background.
17//!
18//! Flutter's windowing API (`widgets/_window.dart`, experimental) builds window archetypes
19//! over the engine's views, each controller making its window within its constructor.
20
21use std::fmt;
22use std::path::PathBuf;
23use std::rc::Rc;
24use std::time::Duration;
25
26pub use raw_window_handle::RawWindowHandle;
27
28use crate::{IconImage, Rect, Size, ViewRef};
29
30/// How a window is made. Sizes and positions are logical, in the host's screen space with
31/// the origin at the top left of the primary screen.
32///
33/// Every option names what the window is for, not how a system does it: the host maps each
34/// onto what its system has, and one its system lacks it leaves at the system's default.
35/// What no option expresses is set through the window's
36/// [`native_handle`](HostWindow::native_handle).
37#[derive(Clone, Debug, PartialEq)]
38pub struct WindowConfig {
39    pub title: String,
40    /// The window's own icon, where the system shows one for a window rather than for the app:
41    /// the title bar's and the taskbar's on Windows and X11, the card's in Android's Recents. The
42    /// app's icon where `None`.
43    pub icon: Option<IconImage>,
44    pub size: [f64; 2],
45    /// Where the window opens; the host chooses when `None`.
46    pub position: Option<[f64; 2]>,
47    /// The system's title bar and border.
48    pub decorations: bool,
49    pub resizable: bool,
50    pub level: WindowLevel,
51    /// Whether showing or clicking the window makes it the focused one. A host may not be
52    /// able to refuse activation.
53    pub activating: bool,
54    /// Whether the window is on every virtual desktop: macOS Spaces, X11 workspaces.
55    pub all_desktops: bool,
56    pub background: WindowBackground,
57    /// Whether the window casts the system's shadow.
58    pub shadow: bool,
59    pub visible: bool,
60    /// What only macOS windows offer; other systems leave it out.
61    pub macos: MacosWindowConfig,
62    /// What only Windows' windows offer; other systems leave it out.
63    pub windows: WindowsWindowConfig,
64    /// What only Linux's windows offer; other systems leave it out.
65    pub linux: LinuxWindowConfig,
66}
67
68impl Default for WindowConfig {
69    fn default() -> WindowConfig {
70        WindowConfig {
71            title: String::new(),
72            icon: None,
73            size: [900.0, 600.0],
74            position: None,
75            decorations: true,
76            resizable: true,
77            level: WindowLevel::Normal,
78            activating: true,
79            all_desktops: false,
80            background: WindowBackground::Solid,
81            shadow: true,
82            visible: true,
83            macos: MacosWindowConfig::default(),
84            windows: WindowsWindowConfig::default(),
85            linux: LinuxWindowConfig::default(),
86        }
87    }
88}
89
90/// What a window offers on macOS alone.
91#[derive(Clone, Copy, Debug, Default, PartialEq)]
92pub struct MacosWindowConfig {
93    pub title_bar: MacosTitleBar,
94}
95
96/// The title bar of a macOS window.
97#[derive(Clone, Copy, Debug, Default, PartialEq)]
98pub enum MacosTitleBar {
99    /// The system's, with the window's title in it.
100    #[default]
101    Standard,
102    /// None of its own, as Safari's and Finder's windows: the view runs to the window's top edge,
103    /// and the close, minimize and zoom buttons sit over it, centred in a band `height` points tall
104    /// at the top, as far from the left edge as from the band's top. Presses in the band reach the
105    /// app, which moves the window, and does a title bar's double press, from where it draws
106    /// nothing to press ([`HostWindow::drag`], [`HostWindow::title_bar_double_click_action`]).
107    Hidden { height: f64 },
108}
109
110/// What a window offers on Windows alone: the app it is on the taskbar, which one process may give
111/// each of its windows apart, and what a pin of it starts.
112#[derive(Clone, Debug, Default, PartialEq)]
113pub struct WindowsWindowConfig {
114    /// The window's own AppUserModelID (`System.AppUserModel.ID`): the taskbar groups the window
115    /// with that app's, apart from the process's, and pins it as that app. The process's ID where
116    /// `None`. At most 128 characters, without spaces.
117    pub app_user_model_id: Option<String>,
118    /// What a pin of the window starts, where no Start menu shortcut carries its ID: such a
119    /// shortcut is what the taskbar pins instead. Only with an `app_user_model_id`.
120    pub relaunch: Option<WindowsRelaunch>,
121}
122
123/// What a pin of a window starts, and how the pin shows (`System.AppUserModel.RelaunchCommand`,
124/// `RelaunchDisplayNameResource`, `RelaunchIconResource`).
125#[derive(Clone, Debug, PartialEq)]
126pub struct WindowsRelaunch {
127    /// The whole command line a pin runs, its program quoted where its path has spaces.
128    pub command: String,
129    /// The pin's name.
130    pub display_name: String,
131    /// The pin's icon; the program's where `None`. An icon Windows cannot load makes it drop the
132    /// whole relaunch, command and name too, without a word: the pin then starts the process's
133    /// executable alone.
134    pub icon: Option<WindowsIconResource>,
135}
136
137/// An icon in a file, as Windows names one: an `.ico` file and the index of its icon, or a module
138/// and a resource id as a negative index.
139#[derive(Clone, Debug, PartialEq, Eq)]
140pub struct WindowsIconResource {
141    pub path: PathBuf,
142    pub index: i32,
143}
144
145/// What a window offers on Linux alone.
146#[derive(Clone, Debug, Default, PartialEq, Eq)]
147pub struct LinuxWindowConfig {
148    /// The window's own app id (xdg-shell's `set_app_id`; the class, `WM_CLASS`, on X11), by which
149    /// the desktop matches it to the desktop file `<app_id>.desktop`, in place of the app's own.
150    /// The app's where `None`.
151    pub app_id: Option<String>,
152    /// The XDG activation token the window shows with, which lets it take the focus the desktop
153    /// gave the launch that brought it (`XDG_ACTIVATION_TOKEN`): a later launch's, passed on.
154    pub activation_token: Option<String>,
155}
156
157#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
158pub enum WindowLevel {
159    #[default]
160    Normal,
161    /// Above ordinary windows, as a palette or a panel sits.
162    AlwaysOnTop,
163    /// Below ordinary windows, as a desktop widget sits.
164    AlwaysOnBottom,
165}
166
167/// What the window shows behind the app's painting. Anything but `Solid` lets what is
168/// behind the window show where the app paints nothing.
169#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
170pub enum WindowBackground {
171    #[default]
172    Solid,
173    Transparent,
174    /// The system's blur of what lies behind the window (macOS vibrancy).
175    Blurred,
176    /// The system's glass material (macOS 26's Liquid Glass); the blur where the system
177    /// has none.
178    Glass,
179}
180
181impl WindowBackground {
182    /// Whether what is behind the window can show through it.
183    pub fn sees_through(self) -> bool {
184        self != WindowBackground::Solid
185    }
186}
187
188/// What a double-click on a window's title bar does
189/// ([`HostWindow::title_bar_double_click_action`]).
190#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
191pub enum TitleBarAction {
192    Maximize,
193    Minimize,
194    Nothing,
195    /// The host can't tell, or the system's setting has a value it doesn't know.
196    #[default]
197    Unknown,
198}
199
200/// The number of a request for a view, which the view carries when it arrives
201/// ([`View::request_id`](crate::View::request_id)).
202#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
203pub struct RequestId(pub u64);
204
205/// Why a request for a view got no view.
206#[derive(Clone, Debug, PartialEq, Eq)]
207pub enum ViewError {
208    /// This platform gives the app its views and makes none on request.
209    Unsupported,
210    Failed(String),
211}
212
213impl fmt::Display for ViewError {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        match self {
216            ViewError::Unsupported => f.write_str("the platform makes no views on request"),
217            ViewError::Failed(reason) => {
218                write!(f, "the platform could not make the view: {reason}")
219            }
220        }
221    }
222}
223
224impl std::error::Error for ViewError {}
225
226pub type WindowRef = Rc<dyn HostWindow>;
227
228/// The window around a view the host puts on screen in a window the app may manage.
229pub trait HostWindow: 'static {
230    fn view(&self) -> ViewRef;
231
232    /// The window's logical frame in screen space.
233    fn frame(&self) -> Rect;
234
235    /// Moves and sizes the window, over `animate` when the host can animate a frame.
236    fn set_frame(&self, frame: Rect, animate: Option<Duration>);
237
238    fn set_title(&self, title: &str);
239
240    /// The window's own icon from now on ([`WindowConfig::icon`]); the app's icon where `None`.
241    /// A system that shows no icon for a window, as macOS and Wayland do not, drops it.
242    fn set_icon(&self, icon: Option<&IconImage>);
243
244    fn show(&self);
245
246    fn hide(&self);
247
248    /// Flutter `WindowController.isMinimized`; macOS `isMiniaturized`, Windows `IsIconic`.
249    /// `false` where the system does not tell a client, as Wayland does not.
250    fn is_minimized(&self) -> bool;
251
252    /// Covered all over, or otherwise not shown: macOS's occlusion state without its visible bit,
253    /// winit's `Occluded`. Not in Flutter's controller; Waft's, after the platforms. `false`
254    /// where the system does not tell a window, as Windows and Wayland do not.
255    fn is_occluded(&self) -> bool;
256
257    /// Closes the window; its view goes away with it. The user's asking to close it only reports
258    /// it ([`EmbedderClient::view_close_requested`](crate::EmbedderClient::view_close_requested));
259    /// this closes it.
260    fn close(&self);
261
262    /// The smallest and largest size the user may resize this window to; none where users don't
263    /// resize windows (phones). Flutter `WindowController.setConstraints`.
264    fn size_limits(&self) -> Option<&dyn WindowSizeLimits>;
265
266    /// Starts the system's own move of the window from the press under way, as a press on its
267    /// title bar does: for an app that draws its own ([`MacosTitleBar::Hidden`]). Call it from
268    /// the press.
269    fn drag(&self);
270
271    /// Flutter `WindowController.isMaximized`; on macOS, zoomed.
272    fn is_maximized(&self) -> bool;
273
274    /// Flutter `WindowController.setMaximized`; on macOS, zooms the window or returns it to its
275    /// size from before.
276    fn set_maximized(&self, maximized: bool);
277
278    /// Flutter `WindowController.setMinimized`.
279    fn set_minimized(&self, minimized: bool);
280
281    /// What the system's settings say a double-click on a title bar does, for an app that draws
282    /// its own ([`MacosTitleBar::Hidden`]): macOS's "Double-click a window's title bar to".
283    fn title_bar_double_click_action(&self) -> TitleBarAction {
284        TitleBarAction::Unknown
285    }
286
287    /// The native window, for configuration this interface does not carry.
288    fn native_handle(&self) -> Option<RawWindowHandle>;
289}
290
291/// The limits a window the user resizes keeps its view within, its content without the system's
292/// title bar and border, in logical points: Flutter's `BoxConstraints` on a window, its minimum
293/// and maximum apart. A limit holds from when it is set until it is set again, and `None` removes
294/// it.
295pub trait WindowSizeLimits {
296    fn set_min_size(&self, size: Option<Size>);
297
298    fn set_max_size(&self, size: Option<Size>);
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[test]
306    fn a_default_window_is_an_ordinary_visible_one() {
307        let config = WindowConfig::default();
308        assert!(config.decorations && config.visible && config.activating);
309        assert_eq!(config.level, WindowLevel::Normal);
310        assert_eq!(config.background, WindowBackground::Solid);
311        assert_eq!(config.macos.title_bar, MacosTitleBar::Standard);
312        assert_eq!(config.windows, WindowsWindowConfig::default());
313        assert_eq!(config.linux, LinuxWindowConfig::default());
314    }
315
316    #[test]
317    fn every_background_but_solid_sees_through() {
318        assert!(!WindowBackground::Solid.sees_through());
319        assert!(WindowBackground::Transparent.sees_through());
320        assert!(WindowBackground::Blurred.sees_through());
321        assert!(WindowBackground::Glass.sees_through());
322    }
323}