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