Skip to main content

zaxis/app/
commands.rs

1//! Application-level window requests. They are queued and executed by the runner, which is
2//! the only code that touches the event loop, so `update` never needs `ActiveEventLoop`.
3
4use super::{AppStats, WindowInfo, WindowKey, WindowOptions, WindowStatus};
5use crate::{SharedResources, Style, Theme};
6use std::collections::HashMap;
7
8pub enum Command {
9    Open {
10        key: WindowKey,
11        options: Box<WindowOptions>,
12        declared: bool,
13    },
14    Close(WindowKey),
15    RequestClose(WindowKey),
16    Focus(WindowKey),
17    Title(WindowKey, String),
18    Size(WindowKey, f64, f64),
19    Visible(WindowKey, bool),
20    Repaint(Option<WindowKey>),
21    Exit,
22    /// A request the platform cannot honour, with the reason; the application is told through
23    /// [`App::window_failed`](super::App::window_failed).
24    Refused(WindowKey, String),
25}
26
27/// State the runner publishes to callbacks and the requests they queue.
28pub struct Control {
29    pub commands: Vec<Command>,
30    pub status: HashMap<WindowKey, WindowStatus>,
31    pub infos: HashMap<WindowKey, WindowInfo>,
32    pub main: WindowKey,
33    pub resources: SharedResources,
34    /// Exit after the frame being built is presented ([`Frame::close`](super::Frame::close)).
35    pub exit_after_present: bool,
36    pub stats: AppStats,
37    /// How many windows the platform can show at once; `None` for no limit. The browser
38    /// has one canvas, so its runner sets `Some(1)`.
39    pub max_windows: Option<usize>,
40}
41
42impl Control {
43    pub fn new(main: WindowKey, resources: SharedResources) -> Self {
44        Self {
45            commands: Vec::new(),
46            status: HashMap::new(),
47            infos: HashMap::new(),
48            main,
49            resources,
50            exit_after_present: false,
51            stats: AppStats::default(),
52            max_windows: None,
53        }
54    }
55}
56
57/// What [`Windows::open`] did.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum OpenOutcome {
60    /// The window will be created when the runner next processes requests.
61    Requested,
62    /// The key is already open or already requested: nothing was created or recreated.
63    AlreadyOpen,
64    /// The platform cannot show another window (the browser runner has a single canvas).
65    /// Nothing was queued; the key's [`status`](Windows::status) is `Failed` and
66    /// [`App::window_failed`](super::App::window_failed) receives
67    /// [`WindowError::Unsupported`](super::WindowError::Unsupported).
68    Unsupported,
69}
70
71/// Open, close, focus and inspect native windows by [`WindowKey`].
72///
73/// Reached through [`Frame::windows`](super::Frame::windows) and the other callbacks of
74/// [`App`](super::App). Requests take effect after the callback returns, in order. Every
75/// request is addressed to a key, so none of them can reach the wrong window.
76pub struct Windows<'a> {
77    pub(crate) control: &'a mut Control,
78}
79
80impl<'a> Windows<'a> {
81    #[doc(hidden)]
82    pub fn from_control(control: &'a mut Control) -> Self {
83        Self { control }
84    }
85}
86
87impl Windows<'_> {
88    /// Ask for a window. A key that is already open or already requested is left alone: no
89    /// duplicate window, no new surface. A key whose last attempt failed is retried; the
90    /// outcome of a failed creation arrives in [`App::window_failed`](super::App::window_failed)
91    /// and in [`status`](Self::status).
92    pub fn open(&mut self, key: impl Into<WindowKey>, options: WindowOptions) -> OpenOutcome {
93        self.request(key.into(), options, false)
94    }
95
96    pub(crate) fn request(
97        &mut self,
98        key: WindowKey,
99        options: WindowOptions,
100        declared: bool,
101    ) -> OpenOutcome {
102        if matches!(
103            self.control.status.get(&key),
104            Some(WindowStatus::Pending | WindowStatus::Open)
105        ) {
106            return OpenOutcome::AlreadyOpen;
107        }
108        if let Some(limit) = self.control.max_windows {
109            let taken = self
110                .control
111                .status
112                .values()
113                .filter(|status| matches!(status, WindowStatus::Pending | WindowStatus::Open))
114                .count();
115            if taken >= limit {
116                let reason = format!("this platform shows at most {limit} window(s) at a time");
117                self.control
118                    .status
119                    .insert(key.clone(), WindowStatus::Failed(reason.clone()));
120                self.control.commands.push(Command::Refused(key, reason));
121                return OpenOutcome::Unsupported;
122            }
123        }
124        self.control
125            .status
126            .insert(key.clone(), WindowStatus::Pending);
127        self.control.commands.push(Command::Open {
128            key,
129            options: Box::new(options),
130            declared,
131        });
132        OpenOutcome::Requested
133    }
134
135    /// Close one window and its children now, without asking the application. Closing the
136    /// main window follows the [`ExitPolicy`](super::ExitPolicy). A window that is not open
137    /// is ignored, so closing twice is harmless. Its retained UI state is discarded.
138    pub fn close(&mut self, key: impl Into<WindowKey>) {
139        self.control.commands.push(Command::Close(key.into()));
140    }
141
142    /// Behave as if the user asked to close the window: the application receives
143    /// [`App::close_requested`](super::App::close_requested) and may veto it.
144    pub fn request_close(&mut self, key: impl Into<WindowKey>) {
145        self.control
146            .commands
147            .push(Command::RequestClose(key.into()));
148    }
149
150    /// Bring the window forward and give it keyboard focus, restoring it if minimized.
151    /// Systems may refuse to steal focus from another application.
152    pub fn focus(&mut self, key: impl Into<WindowKey>) {
153        self.control.commands.push(Command::Focus(key.into()));
154    }
155
156    pub fn set_title(&mut self, key: impl Into<WindowKey>, title: impl Into<String>) {
157        self.control
158            .commands
159            .push(Command::Title(key.into(), title.into()));
160    }
161
162    /// Request a new inner size in logical pixels; the system may adjust it.
163    pub fn set_inner_size(&mut self, key: impl Into<WindowKey>, width: f64, height: f64) {
164        self.control
165            .commands
166            .push(Command::Size(key.into(), width, height));
167    }
168
169    /// Show or hide a window. A hidden window is not rendered and requests no frames.
170    pub fn set_visible(&mut self, key: impl Into<WindowKey>, visible: bool) {
171        self.control
172            .commands
173            .push(Command::Visible(key.into(), visible));
174    }
175
176    /// Draw `key` again soon. A window repaints on its own input and animations; call this
177    /// when application data changed in another window and this one shows it. Hidden or
178    /// minimized windows catch up when they are shown again.
179    pub fn request_repaint(&mut self, key: impl Into<WindowKey>) {
180        self.control
181            .commands
182            .push(Command::Repaint(Some(key.into())));
183    }
184
185    /// [`request_repaint`](Self::request_repaint) for every window.
186    pub fn request_repaint_all(&mut self) {
187        self.control.commands.push(Command::Repaint(None));
188    }
189
190    /// End the application, closing every window, without asking.
191    pub fn exit(&mut self) {
192        self.control.commands.push(Command::Exit);
193    }
194
195    /// Whether `key` is open or has been requested.
196    pub fn is_open(&self, key: &WindowKey) -> bool {
197        matches!(
198            self.control.status.get(key),
199            Some(WindowStatus::Pending | WindowStatus::Open)
200        )
201    }
202
203    pub fn status(&self, key: &WindowKey) -> Option<&WindowStatus> {
204        self.control.status.get(key)
205    }
206
207    /// State of an open window as of the start of this callback.
208    pub fn info(&self, key: &WindowKey) -> Option<&WindowInfo> {
209        self.control.infos.get(key)
210    }
211
212    /// Keys of open and requested windows, in no particular order.
213    pub fn keys(&self) -> impl Iterator<Item = &WindowKey> {
214        self.control
215            .status
216            .iter()
217            .filter(|(_, status)| !matches!(status, WindowStatus::Failed(_)))
218            .map(|(key, _)| key)
219    }
220
221    pub fn main_key(&self) -> &WindowKey {
222        &self.control.main
223    }
224
225    pub fn stats(&self) -> AppStats {
226        self.control.stats
227    }
228
229    /// The resources every window shares: glyph atlas, image cache, appearance.
230    pub fn resources(&self) -> &SharedResources {
231        &self.control.resources
232    }
233
234    /// Re-theme every window with one call; each applies it in its next frame.
235    pub fn set_theme(&mut self, theme: Theme) {
236        self.control.resources.set_theme(theme);
237    }
238
239    /// Install a resolved style in every window; see [`set_theme`](Self::set_theme).
240    pub fn set_style(&mut self, style: Style) {
241        self.control.resources.set_style(style);
242    }
243}