Skip to main content

mitsuami_core/ui/
build.rs

1//! Creating nodes and setting their props, styles and handlers.
2
3use std::collections::BTreeMap;
4use std::rc::Rc;
5
6use crate::a11y::A11yProps;
7use crate::command::{Command, UiEvent};
8use crate::geometry::{Insets, Point, Rect, Size, WindowSize};
9use crate::style::Style;
10use crate::widget::{NodeId, Prop, WidgetKind};
11
12use super::{Fit, Node, Ui};
13
14impl Ui {
15    pub fn create(&self, kind: WidgetKind, props: Vec<Prop>) -> NodeId {
16        let id = {
17            let mut inner = self.inner.borrow_mut();
18            let id = NodeId(inner.next_id);
19            inner.next_id += 1;
20            let taffy = if kind.is_native() {
21                let t = if kind.is_container() {
22                    inner.taffy.new_leaf(taffy::Style::default())
23                } else {
24                    inner.taffy.new_leaf_with_context(taffy::Style::default(), id)
25                };
26                Some(t.expect("taffy: failed to create node"))
27            } else {
28                None
29            };
30            if kind.is_native() {
31                inner.pending.push(Command::Create { id, kind, props: props.clone() });
32                inner.created.insert(id);
33            }
34            inner.nodes.insert(
35                id,
36                Node {
37                    kind,
38                    parent: None,
39                    children: Vec::new(),
40                    native_children: Vec::new(),
41                    native_parent: None,
42                    props,
43                    style: Style::default(),
44                    a11y: A11yProps::default(),
45                    test_id: None,
46                    tab_index: None,
47                    handlers: Vec::new(),
48                    taffy,
49                    frame: Rect::ZERO,
50                    framed: false,
51                    window_size: Size::ZERO,
52                    fit: Fit::None,
53                    heights: Vec::new(),
54                    scroll_offset: Point::ZERO,
55                    row_width: None,
56                    tree_indent: crate::TreeIndent::default(),
57                    viewport_insets: Insets::ZERO,
58                    column_widths: None,
59                    row_heights: BTreeMap::new(),
60                    strip: Size::ZERO,
61                    insets: None,
62                    drawn_at: None,
63                },
64            );
65            inner.styles_dirty = true;
66            id
67        };
68        self.changed();
69        id
70    }
71
72    /// A window fitting its height is sized at its first layout, so give it
73    /// its content before the next commit.
74    pub fn create_window(&self, title: impl Into<String>, size: impl Into<WindowSize>) -> NodeId {
75        let size = match size.into() {
76            // A fraction of the work area of the screen it opens on, as the
77            // platform tells it now; without a screen, a common default.
78            WindowSize::Screen { width, height } => {
79                let area = self.inner.borrow().backend.work_area(None).unwrap_or(Size::new(1024.0, 768.0));
80                WindowSize::Fixed(Size::new(
81                    (area.width * width.clamp(0.0, 1.0)).round(),
82                    (area.height * height.clamp(0.0, 1.0)).round(),
83                ))
84            }
85            size => size,
86        };
87        let mut props = vec![Prop::Title(title.into())];
88        if let WindowSize::FollowHeight(_) = size {
89            props.push(Prop::HeightFollowsContent(true));
90        }
91        let id = self.create(WidgetKind::Window, props);
92        let mut inner = self.inner.borrow_mut();
93        let node = inner.nodes.get_mut(&id).expect("just created");
94        let (size, fit) = match size {
95            WindowSize::Fixed(size) => (size, Fit::None),
96            WindowSize::FitHeight(width) => (Size::new(width, 0.0), Fit::Once),
97            WindowSize::FollowHeight(width) => (Size::new(width, 0.0), Fit::Follow { until_resized: false }),
98            WindowSize::FollowHeightUntilResized(width) => (Size::new(width, 0.0), Fit::Follow { until_resized: true }),
99            WindowSize::Screen { .. } => unreachable!("resolved above"),
100        };
101        node.window_size = size;
102        node.fit = fit;
103        node.frame = Rect { origin: Point::ZERO, size };
104        inner.windows.push(id);
105        // A fitted size is sent with the first frames.
106        if fit == Fit::None {
107            inner.pending.push(Command::SetWindowSize { id, size });
108        }
109        id
110    }
111
112    /// The work area of a window's screen (the screen less its bars and
113    /// docks), as the content size of a window filling it, in points: what
114    /// to size a window to a fraction of its screen with
115    /// [`Ui::set_window_size`]. With `None`, of the screen a new window opens
116    /// on. `None` if the platform can't tell.
117    pub fn work_area(&self, window: Option<NodeId>) -> Option<Size> {
118        self.inner.borrow().backend.work_area(window)
119    }
120
121    /// Centres a window on its screen's work area now, as
122    /// `Placement::Centred` does when it opens. Where the platform places
123    /// windows itself (Wayland, GTK), it stays where it is.
124    pub fn centre_window(&self, window: NodeId) {
125        {
126            let mut inner = self.inner.borrow_mut();
127            if !inner.nodes.get(&window).is_some_and(|n| n.kind == WidgetKind::Window) {
128                return;
129            }
130            inner.pending.push(Command::CentreWindow { window });
131        }
132        self.changed();
133    }
134
135    /// Asks for a window's content size, in points, as the app would resize
136    /// it. The platform may refuse it (a window in full screen keeps the
137    /// screen's), and gives it no smaller than the window's `MinSize`; the
138    /// content is laid out at the size it reports (`WindowResized`). A
139    /// `WindowSize::FollowHeight` window takes only the width: its content
140    /// sets its height. Other windows stop fitting their height.
141    pub fn set_window_size(&self, window: NodeId, size: Size) {
142        {
143            let mut inner = self.inner.borrow_mut();
144            let Some(node) = inner.nodes.get_mut(&window).filter(|n| n.kind == WidgetKind::Window) else { return };
145            let size = match node.fit {
146                Fit::Follow { until_resized: false } => {
147                    Size::new(size.width, node.heights.last().copied().unwrap_or(node.window_size.height))
148                }
149                _ => {
150                    node.fit = Fit::None;
151                    node.heights.clear();
152                    size
153                }
154            };
155            inner.pending.push(Command::SetWindowSize { id: window, size });
156        }
157        self.changed();
158    }
159
160    /// Sets a prop, sending it to the backend only if it changed.
161    pub fn set_prop(&self, id: NodeId, prop: Prop) {
162        // A choice of none, or of a tab or option that isn't there, is the
163        // first, before the backend sees it (`always_chosen`).
164        let prop = match prop {
165            Prop::SelectedIndex(index) => Prop::SelectedIndex(self.choosable(id, index)),
166            prop => prop,
167        };
168        {
169            let mut inner = self.inner.borrow_mut();
170            let inner = &mut *inner;
171            let Some(node) = inner.nodes.get_mut(&id) else { return };
172            if node.prop(&prop) == Some(&prop) {
173                return;
174            }
175            node.props.retain(|p| p.key() != prop.key());
176            node.props.push(prop.clone());
177            if matches!(prop, Prop::Custom(_)) {
178                node.drawn_at = None;
179            }
180            if prop.affects_measure(node.kind)
181                && let Some(t) = node.taffy
182            {
183                let _ = inner.taffy.mark_dirty(t);
184            }
185            // A line limit changes a text's minimum width (`resolve_node`);
186            // a split's position and orientation, its tracks.
187            if matches!(prop, Prop::TextStyle(_) | Prop::MaxLines(_))
188                || (node.kind == WidgetKind::Split && matches!(prop, Prop::Number(_) | Prop::Orientation(_)))
189            {
190                inner.styles_dirty = true;
191            }
192            // New titles, icons or another style may make the tab strip wider
193            // (`size_tab_strips`), and a group's heading wider, or give it
194            // the titled insets.
195            if (matches!(prop, Prop::TabTitles(_) | Prop::TabIcons(_) | Prop::TabsStyle(_))
196                || (node.kind == WidgetKind::Group && matches!(prop, Prop::Title(_))))
197                && let Some(t) = node.taffy
198            {
199                let _ = inner.taffy.mark_dirty(t);
200                inner.styles_dirty |= node.kind == WidgetKind::Group;
201            }
202            // A tab view's page shown, and a surface taking input, are in
203            // the Tab order.
204            if matches!(prop, Prop::SelectedIndex(_) | Prop::TakesInput(_)) {
205                inner.focus_dirty = true;
206            }
207            if node.kind.is_native() {
208                inner.queue_prop(id, prop);
209            }
210        }
211        self.changed();
212        if let Some(chosen) = self.always_chosen(id) {
213            self.set_prop(id, Prop::SelectedIndex(chosen));
214        }
215    }
216
217    /// A `Tabs` or `Select` with tabs or options always has one chosen, the
218    /// first unless the app chose another that's there: GTK's notebook and
219    /// drop-down can't show none. WinUI's selector bar can, and a tab view
220    /// whose app chose no tab (the C ABI's, SourceGit's statistics) showed
221    /// an empty page there. What to choose, if not what's chosen now.
222    fn always_chosen(&self, id: NodeId) -> Option<Option<usize>> {
223        let chosen = {
224            let inner = self.inner.borrow();
225            let node = inner.nodes.get(&id)?;
226            matches!(node.kind, WidgetKind::Tabs | WidgetKind::Select)
227                .then(|| crate::find_prop!(node.props, SelectedIndex).flatten())?
228        };
229        let wanted = self.choosable(id, chosen);
230        (wanted != chosen).then_some(wanted)
231    }
232
233    /// What a `Tabs` or `Select` can have chosen for `index`: it, if it's
234    /// there, or else the first; none only without tabs or options. Any
235    /// other node's index as it is.
236    fn choosable(&self, id: NodeId, index: Option<usize>) -> Option<usize> {
237        let inner = self.inner.borrow();
238        let Some(node) = inner.nodes.get(&id) else { return index };
239        let count = match node.kind {
240            WidgetKind::Tabs => crate::find_prop!(node.props, TabTitles).map(|t| t.len()),
241            WidgetKind::Select => crate::find_prop!(node.props, Options).map(|o| o.len()),
242            _ => return index,
243        };
244        match count {
245            // Titles or options may come after the index.
246            None => index,
247            Some(count) => (count > 0).then(|| index.filter(|i| *i < count).unwrap_or(0)),
248        }
249    }
250
251    pub fn set_style(&self, id: NodeId, style: Style) {
252        {
253            let mut inner = self.inner.borrow_mut();
254            let Some(node) = inner.nodes.get_mut(&id) else { return };
255            if node.style == style {
256                return;
257            }
258            node.style = style;
259            inner.styles_dirty = true;
260        }
261        self.changed();
262    }
263
264    /// Edits a node's style in place (used by reactive style bindings).
265    pub fn update_style(&self, id: NodeId, f: impl FnOnce(&mut Style)) {
266        let style = {
267            let inner = self.inner.borrow();
268            let Some(node) = inner.nodes.get(&id) else { return };
269            let mut style = node.style.clone();
270            f(&mut style);
271            style
272        };
273        self.set_style(id, style);
274    }
275
276    pub fn set_a11y(&self, id: NodeId, a11y: A11yProps) {
277        {
278            let mut inner = self.inner.borrow_mut();
279            let Some(node) = inner.nodes.get_mut(&id) else { return };
280            if node.a11y == a11y {
281                return;
282            }
283            node.a11y = a11y.clone();
284            if node.kind.is_native() {
285                inner.pending.push(Command::SetA11y { id, a11y });
286            }
287        }
288        self.changed();
289    }
290
291    /// Changes part of a node's semantics.
292    pub fn update_a11y(&self, id: NodeId, f: impl FnOnce(&mut A11yProps)) {
293        let Some(mut a11y) = self.inner.borrow().nodes.get(&id).map(|n| n.a11y.clone()) else { return };
294        f(&mut a11y);
295        self.set_a11y(id, a11y);
296    }
297
298    pub fn set_test_id(&self, id: NodeId, test_id: impl Into<String>) {
299        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
300            node.test_id = Some(test_id.into());
301        }
302    }
303
304    /// The current owner, or, with none, a scope of its own that goes when
305    /// node `id` is destroyed, so what a view built straight on a `Ui` (a
306    /// `For`, a `List`) hangs off it is freed with its node.
307    pub(crate) fn owner_or_node_scope(&self, id: NodeId) -> mitsuami_reactive::Owner {
308        use mitsuami_reactive::Owner;
309        if let Some(owner) = Owner::current() {
310            return owner;
311        }
312        struct DisposeOnDrop(Owner);
313        impl Drop for DisposeOnDrop {
314            fn drop(&mut self) {
315                self.0.dispose();
316            }
317        }
318        let scope = Owner::new_root();
319        let guard = DisposeOnDrop(scope);
320        // Kept by a handler that does nothing: the node drops its handlers
321        // when it's destroyed (after the tree's borrow, `destroy`).
322        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
323            node.handlers.push(Rc::new(move |_: &UiEvent| {
324                let _ = &guard;
325            }));
326        }
327        scope
328    }
329
330    /// Adds an event handler. It runs in the reactive scope that is current
331    /// now (usually the component being built), so `inject`, `spawn_local`
332    /// and friends work inside it.
333    pub fn on_event(&self, id: NodeId, handler: impl Fn(&UiEvent) + 'static) {
334        let owner = mitsuami_reactive::Owner::current();
335        let handler = move |event: &UiEvent| match owner {
336            Some(owner) if owner.is_alive() => owner.with(|| handler(event)),
337            _ => handler(event),
338        };
339        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
340            node.handlers.push(Rc::new(handler));
341        }
342    }
343}