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