Skip to main content

mitsuami_widgets/
window.rs

1//! Windows the app opens while it runs.
2
3use std::rc::Rc;
4
5use mitsuami_core::{
6    AnyView, CurrentWindow, Modality, NodeId, NodeRef, Prop, Size, Ui, UiEvent, View, WidgetKind, WindowSize,
7};
8use mitsuami_reactive::{IntoValue, Signal, Value, computed, effect, inject, on_cleanup, provide, untrack};
9
10/// A window the app opens while it runs: shown while `open` is true, with
11/// its content built when it opens and disposed when it closes. Declare it
12/// anywhere in the tree, next to the state that opens it; it closes with
13/// the scope that declared it, and belongs to the window it's declared in.
14///
15/// The close button asks: [`bind`](Self::bind) closes it by setting the
16/// flag, or [`on_close_request`](Self::on_close_request) lets the app
17/// decide (to ask about unsaved changes, say). Without either, the close
18/// button does nothing.
19///
20/// ```ignore
21/// let editing = signal(false);
22/// Column::new().children((
23///     Button::new("Edit…").on_click(move || editing.set(true)),
24///     Window::new("Machine").bind(editing).content(|| machine_form()),
25/// ))
26/// ```
27///
28/// In `view!`, its title is an attribute and its children are its content:
29/// `<Window title="Machine" bind=editing>…</Window>`.
30pub struct Window<T = Value<String>> {
31    title: T,
32    size: Value<WindowSize>,
33    modality: Value<Option<Modality>>,
34    open: Value<bool>,
35    full_screen: Option<Signal<bool>>,
36    maximized: Option<Signal<bool>>,
37    resizable: Option<Value<bool>>,
38    min_size: Option<Value<Size>>,
39    on_open: Option<Rc<dyn Fn()>>,
40    on_close_request: Option<Rc<dyn Fn()>>,
41    on_active_changed: Option<Rc<dyn Fn(bool)>>,
42    node_ref: Option<NodeRef>,
43    content: Option<Rc<dyn Fn() -> AnyView>>,
44}
45
46impl Window {
47    /// Open, 480 wide, as tall as its content.
48    pub fn new(title: impl IntoValue<String>) -> Window {
49        Window {
50            title: title.into_value(),
51            size: Value::Static(WindowSize::FitHeight(480.0)),
52            modality: Value::Static(None),
53            open: Value::Static(true),
54            full_screen: None,
55            maximized: None,
56            resizable: None,
57            min_size: None,
58            on_open: None,
59            on_close_request: None,
60            on_active_changed: None,
61            node_ref: None,
62            content: None,
63        }
64    }
65}
66
67impl<T> Window<T> {
68    /// Its content size when it opens: a [`Size`](mitsuami_core::Size),
69    /// [`WindowSize::FitHeight`] to fit the height to the content, or
70    /// [`WindowSize::FollowHeight`] to follow it as it changes. Read each
71    /// time it opens, as its modality is, so a change applies at the next
72    /// opening.
73    pub fn size(mut self, size: impl IntoValue<WindowSize>) -> Window<T> {
74        self.size = size.into_value();
75        self
76    }
77
78    /// Modal: while it's open, it blocks the window it's declared in
79    /// ([`Modality::Window`], a sheet on macOS) or the whole app
80    /// ([`Modality::Application`]), and stays above that window. Set
81    /// before it opens. Like any dialog, Escape asks it to close, as its
82    /// close button does (on AppKit a `ButtonRole::Cancel` button takes
83    /// Escape first). A sheet has no close button: give its content a
84    /// way out, e.g. that Cancel button.
85    pub fn modal(mut self, modality: Modality) -> Window<T> {
86        self.modality = Value::Static(Some(modality));
87        self
88    }
89
90    /// Modal or not, as a value that can change: read each time it opens,
91    /// so a change applies at the next opening.
92    pub fn modality(mut self, modality: impl IntoValue<Option<Modality>>) -> Window<T> {
93        self.modality = modality.into_value();
94        self
95    }
96
97    /// Shown while true.
98    pub fn open(mut self, open: impl IntoValue<bool>) -> Window<T> {
99        self.open = open.into_value();
100        self
101    }
102
103    /// Shown while the signal is true; the close button sets it false.
104    pub fn bind(self, open: Signal<bool>) -> Window<T> {
105        self.open(open).on_close_request(move || open.set(false))
106    }
107
108    /// In full screen while `full_screen` is true, the platform's own way:
109    /// a Space of its own on macOS, the whole screen elsewhere, with the
110    /// platform's own way out. The user can change it too (the title bar's
111    /// button on macOS, the window manager's key), which sets the signal.
112    pub fn full_screen(mut self, full_screen: Signal<bool>) -> Window<T> {
113        self.full_screen = Some(full_screen);
114        self
115    }
116
117    /// Maximized while `maximized` is true, as the platform maximizes a
118    /// window: its screen's working area (on macOS, zoomed to fit it). The
119    /// user can change it too (the title bar's button, a double-click on
120    /// it, the window manager's key), which sets the signal.
121    pub fn maximized(mut self, maximized: Signal<bool>) -> Window<T> {
122        self.maximized = Some(maximized);
123        self
124    }
125
126    /// Whether the user can resize it; they can unless it's set false.
127    /// The app can still size it, and a window that follows its content's
128    /// height still does.
129    pub fn resizable(mut self, resizable: impl IntoValue<bool>) -> Window<T> {
130        self.resizable = Some(resizable.into_value());
131        self
132    }
133
134    /// The smallest content size the user can make it. Smaller when it's
135    /// set, it grows to it.
136    pub fn min_size(mut self, size: impl IntoValue<Size>) -> Window<T> {
137        self.min_size = Some(size.into_value());
138        self
139    }
140
141    /// Called each time it opens, before its content is built: to start a
142    /// form from what's saved, say.
143    pub fn on_open(mut self, handler: impl Fn() + 'static) -> Window<T> {
144        self.on_open = Some(Rc::new(handler));
145        self
146    }
147
148    /// Called when the user asks to close it (the close button, ⌘W, Alt+F4).
149    /// It stays open unless the app closes it.
150    pub fn on_close_request(mut self, handler: impl Fn() + 'static) -> Window<T> {
151        self.on_close_request = Some(Rc::new(handler));
152        self
153    }
154
155    /// Called when it becomes the active window, the one taking keys, or stops being it.
156    pub fn on_active_changed(mut self, handler: impl Fn(bool) + 'static) -> Window<T> {
157        self.on_active_changed = Some(Rc::new(handler));
158        self
159    }
160
161    /// Points `node` at the window while it's open, to bring it forward
162    /// from code ([`NodeRef::present`]): `open.set(true)` alone does
163    /// nothing to a window that's open behind other apps' windows.
164    pub fn node_ref(mut self, node: NodeRef) -> Window<T> {
165        self.node_ref = Some(node);
166        self
167    }
168
169    /// What it shows, built each time it opens.
170    pub fn content<V: View>(mut self, content: impl Fn() -> V + 'static) -> Window<T> {
171        self.content = Some(Rc::new(move || AnyView::new(content())));
172        self
173    }
174}
175
176impl View for Window {
177    /// A placeholder in the tree, which takes no room; the window is
178    /// top-level.
179    fn build(self, ui: &Ui) -> NodeId {
180        let placeholder = ui.create(WidgetKind::Fragment, Vec::new());
181        let Window {
182            title,
183            size,
184            modality,
185            open,
186            full_screen,
187            maximized,
188            resizable,
189            min_size,
190            on_open,
191            on_close_request,
192            on_active_changed,
193            node_ref,
194            content,
195        } = self;
196        // The window it's declared in, which a modal window belongs to.
197        let owner = inject::<CurrentWindow>().map(|w| w.0);
198        let ui = ui.clone();
199        let show = move || {
200            let window = ui.create_window(String::new(), size.get());
201            if let Some(modality) = modality.get() {
202                // With no window to block, it blocks the app.
203                let modality = if owner.is_some() { modality } else { Modality::Application };
204                ui.set_prop(window, Prop::Modal { owner, modality });
205            }
206            let title = title.clone();
207            let titled = ui.clone();
208            effect(move || titled.set_prop(window, Prop::Title(title.get())));
209            if let Some(min_size) = min_size.clone() {
210                let ui = ui.clone();
211                effect(move || ui.set_prop(window, Prop::MinSize(min_size.get())));
212            }
213            if let Some(full_screen) = full_screen {
214                let filled = ui.clone();
215                effect(move || filled.set_prop(window, Prop::FullScreen(full_screen.get())));
216                ui.on_event(window, move |event| {
217                    if let UiEvent::FullScreenChanged(on) = event {
218                        full_screen.set(*on);
219                    }
220                });
221            }
222            if let Some(maximized) = maximized {
223                let zoomed = ui.clone();
224                effect(move || zoomed.set_prop(window, Prop::Maximized(maximized.get())));
225                ui.on_event(window, move |event| {
226                    if let UiEvent::MaximizedChanged(on) = event {
227                        maximized.set(*on);
228                    }
229                });
230            }
231            if let Some(resizable) = resizable.clone() {
232                let ui = ui.clone();
233                effect(move || ui.set_prop(window, Prop::Resizable(resizable.get())));
234            }
235            provide(CurrentWindow(window));
236            if let Some(node) = node_ref {
237                node.attach(&ui, window);
238            }
239            if let Some(handler) = &on_open {
240                handler();
241            }
242            if let Some(content) = &content {
243                let root = content().build(&ui);
244                ui.append_child(window, root);
245            }
246            if let Some(handler) = on_close_request.clone() {
247                ui.on_event(window, move |event| {
248                    if *event == UiEvent::WindowCloseRequested {
249                        handler();
250                    }
251                });
252            }
253            if let Some(handler) = on_active_changed.clone() {
254                ui.on_event(window, move |event| {
255                    if let UiEvent::WindowActiveChanged(active) = event {
256                        handler(*active);
257                    }
258                });
259            }
260            let ui = ui.clone();
261            on_cleanup(move || ui.destroy(window));
262        };
263        // In a scope of its own even when it's always open, so what it
264        // provides (its `CurrentWindow`) stays inside it.
265        let open = computed(move || open.get());
266        effect(move || {
267            if open.get() {
268                untrack(&show);
269            }
270        });
271        placeholder
272    }
273}
274
275impl Window {
276    /// `<Window title="Machine" bind=editing>…</Window>`: a `Window<()>`
277    /// until `title` is set, and only then a `View`.
278    #[doc(hidden)]
279    pub fn __tag() -> Window<()> {
280        Window::new(String::new()).retitled(())
281    }
282
283    /// Its content, built each time it opens.
284    #[doc(hidden)]
285    pub fn __children<V: View>(self, content: impl Fn() -> V + 'static) -> Window {
286        self.content(content)
287    }
288}
289
290impl Window<()> {
291    /// The title `view!` sets, which makes the window a `View`.
292    #[doc(hidden)]
293    pub fn title(self, title: impl IntoValue<String>) -> Window {
294        self.retitled(title.into_value())
295    }
296}
297
298impl<T> Window<T> {
299    /// The same window with another title type.
300    fn retitled<U>(self, title: U) -> Window<U> {
301        let Window {
302            title: _,
303            size,
304            modality,
305            open,
306            full_screen,
307            maximized,
308            resizable,
309            min_size,
310            on_open,
311            on_close_request,
312            on_active_changed,
313            node_ref,
314            content,
315        } = self;
316        Window {
317            title,
318            size,
319            modality,
320            open,
321            full_screen,
322            maximized,
323            resizable,
324            min_size,
325            on_open,
326            on_close_request,
327            on_active_changed,
328            node_ref,
329            content,
330        }
331    }
332}