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