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 = size.into();
76        let mut props = vec![Prop::Title(title.into())];
77        if let WindowSize::FollowHeight(_) = size {
78            props.push(Prop::HeightFollowsContent(true));
79        }
80        let id = self.create(WidgetKind::Window, props);
81        let mut inner = self.inner.borrow_mut();
82        let node = inner.nodes.get_mut(&id).expect("just created");
83        let (size, fit) = match size {
84            WindowSize::Fixed(size) => (size, Fit::None),
85            WindowSize::FitHeight(width) => (Size::new(width, 0.0), Fit::Once),
86            WindowSize::FollowHeight(width) => (Size::new(width, 0.0), Fit::Follow { until_resized: false }),
87            WindowSize::FollowHeightUntilResized(width) => (Size::new(width, 0.0), Fit::Follow { until_resized: true }),
88        };
89        node.window_size = size;
90        node.fit = fit;
91        node.frame = Rect { origin: Point::ZERO, size };
92        inner.windows.push(id);
93        // A fitted size is sent with the first frames.
94        if fit == Fit::None {
95            inner.pending.push(Command::SetWindowSize { id, size });
96        }
97        id
98    }
99
100    /// Asks for a window's content size, in points, as the app would resize
101    /// it. The platform may refuse it (a window in full screen keeps the
102    /// screen's), and gives it no smaller than the window's `MinSize`; the
103    /// content is laid out at the size it reports (`WindowResized`). A
104    /// `WindowSize::FollowHeight` window takes only the width: its content
105    /// sets its height. Other windows stop fitting their height.
106    pub fn set_window_size(&self, window: NodeId, size: Size) {
107        {
108            let mut inner = self.inner.borrow_mut();
109            let Some(node) = inner.nodes.get_mut(&window).filter(|n| n.kind == WidgetKind::Window) else { return };
110            let size = match node.fit {
111                Fit::Follow { until_resized: false } => {
112                    Size::new(size.width, node.heights.last().copied().unwrap_or(node.window_size.height))
113                }
114                _ => {
115                    node.fit = Fit::None;
116                    node.heights.clear();
117                    size
118                }
119            };
120            inner.pending.push(Command::SetWindowSize { id: window, size });
121        }
122        self.changed();
123    }
124
125    /// Sets a prop, sending it to the backend only if it changed.
126    pub fn set_prop(&self, id: NodeId, prop: Prop) {
127        // A choice of none, or of a tab or option that isn't there, is the
128        // first, before the backend sees it (`always_chosen`).
129        let prop = match prop {
130            Prop::SelectedIndex(index) => Prop::SelectedIndex(self.choosable(id, index)),
131            prop => prop,
132        };
133        {
134            let mut inner = self.inner.borrow_mut();
135            let inner = &mut *inner;
136            let Some(node) = inner.nodes.get_mut(&id) else { return };
137            if node.prop(&prop) == Some(&prop) {
138                return;
139            }
140            node.props.retain(|p| p.key() != prop.key());
141            node.props.push(prop.clone());
142            if matches!(prop, Prop::Custom(_)) {
143                node.drawn_at = None;
144            }
145            if prop.affects_measure(node.kind)
146                && let Some(t) = node.taffy
147            {
148                let _ = inner.taffy.mark_dirty(t);
149            }
150            // A line limit changes a text's minimum width (`resolve_node`);
151            // a split's position and orientation, its tracks.
152            if matches!(prop, Prop::TextStyle(_) | Prop::MaxLines(_))
153                || (node.kind == WidgetKind::Split && matches!(prop, Prop::Number(_) | Prop::Orientation(_)))
154            {
155                inner.styles_dirty = true;
156            }
157            // New titles, icons or another style may make the tab strip wider
158            // (`size_tab_strips`), and a group's heading wider, or give it
159            // the titled insets.
160            if (matches!(prop, Prop::TabTitles(_) | Prop::TabIcons(_) | Prop::TabsStyle(_))
161                || (node.kind == WidgetKind::Group && matches!(prop, Prop::Title(_))))
162                && let Some(t) = node.taffy
163            {
164                let _ = inner.taffy.mark_dirty(t);
165                inner.styles_dirty |= node.kind == WidgetKind::Group;
166            }
167            // A tab view's page shown, and a surface taking input, are in
168            // the Tab order.
169            if matches!(prop, Prop::SelectedIndex(_) | Prop::TakesInput(_)) {
170                inner.focus_dirty = true;
171            }
172            if node.kind.is_native() {
173                inner.queue_prop(id, prop);
174            }
175        }
176        self.changed();
177        if let Some(chosen) = self.always_chosen(id) {
178            self.set_prop(id, Prop::SelectedIndex(chosen));
179        }
180    }
181
182    /// A `Tabs` or `Select` with tabs or options always has one chosen, the
183    /// first unless the app chose another that's there: GTK's notebook and
184    /// drop-down can't show none. WinUI's selector bar can, and a tab view
185    /// whose app chose no tab (the C ABI's, SourceGit's statistics) showed
186    /// an empty page there. What to choose, if not what's chosen now.
187    fn always_chosen(&self, id: NodeId) -> Option<Option<usize>> {
188        let chosen = {
189            let inner = self.inner.borrow();
190            let node = inner.nodes.get(&id)?;
191            matches!(node.kind, WidgetKind::Tabs | WidgetKind::Select)
192                .then(|| crate::find_prop!(node.props, SelectedIndex).flatten())?
193        };
194        let wanted = self.choosable(id, chosen);
195        (wanted != chosen).then_some(wanted)
196    }
197
198    /// What a `Tabs` or `Select` can have chosen for `index`: it, if it's
199    /// there, or else the first; none only without tabs or options. Any
200    /// other node's index as it is.
201    fn choosable(&self, id: NodeId, index: Option<usize>) -> Option<usize> {
202        let inner = self.inner.borrow();
203        let Some(node) = inner.nodes.get(&id) else { return index };
204        let count = match node.kind {
205            WidgetKind::Tabs => crate::find_prop!(node.props, TabTitles).map(|t| t.len()),
206            WidgetKind::Select => crate::find_prop!(node.props, Options).map(|o| o.len()),
207            _ => return index,
208        };
209        match count {
210            // Titles or options may come after the index.
211            None => index,
212            Some(count) => (count > 0).then(|| index.filter(|i| *i < count).unwrap_or(0)),
213        }
214    }
215
216    pub fn set_style(&self, id: NodeId, style: Style) {
217        {
218            let mut inner = self.inner.borrow_mut();
219            let Some(node) = inner.nodes.get_mut(&id) else { return };
220            if node.style == style {
221                return;
222            }
223            node.style = style;
224            inner.styles_dirty = true;
225        }
226        self.changed();
227    }
228
229    /// Edits a node's style in place (used by reactive style bindings).
230    pub fn update_style(&self, id: NodeId, f: impl FnOnce(&mut Style)) {
231        let style = {
232            let inner = self.inner.borrow();
233            let Some(node) = inner.nodes.get(&id) else { return };
234            let mut style = node.style.clone();
235            f(&mut style);
236            style
237        };
238        self.set_style(id, style);
239    }
240
241    pub fn set_a11y(&self, id: NodeId, a11y: A11yProps) {
242        {
243            let mut inner = self.inner.borrow_mut();
244            let Some(node) = inner.nodes.get_mut(&id) else { return };
245            if node.a11y == a11y {
246                return;
247            }
248            node.a11y = a11y.clone();
249            if node.kind.is_native() {
250                inner.pending.push(Command::SetA11y { id, a11y });
251            }
252        }
253        self.changed();
254    }
255
256    /// Changes part of a node's semantics.
257    pub fn update_a11y(&self, id: NodeId, f: impl FnOnce(&mut A11yProps)) {
258        let Some(mut a11y) = self.inner.borrow().nodes.get(&id).map(|n| n.a11y.clone()) else { return };
259        f(&mut a11y);
260        self.set_a11y(id, a11y);
261    }
262
263    pub fn set_test_id(&self, id: NodeId, test_id: impl Into<String>) {
264        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
265            node.test_id = Some(test_id.into());
266        }
267    }
268
269    /// The current owner, or, with none, a scope of its own that goes when
270    /// node `id` is destroyed, so what a view built straight on a `Ui` (a
271    /// `For`, a `List`) hangs off it is freed with its node.
272    pub(crate) fn owner_or_node_scope(&self, id: NodeId) -> mitsuami_reactive::Owner {
273        use mitsuami_reactive::Owner;
274        if let Some(owner) = Owner::current() {
275            return owner;
276        }
277        struct DisposeOnDrop(Owner);
278        impl Drop for DisposeOnDrop {
279            fn drop(&mut self) {
280                self.0.dispose();
281            }
282        }
283        let scope = Owner::new_root();
284        let guard = DisposeOnDrop(scope);
285        // Kept by a handler that does nothing: the node drops its handlers
286        // when it's destroyed (after the tree's borrow, `destroy`).
287        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
288            node.handlers.push(Rc::new(move |_: &UiEvent| {
289                let _ = &guard;
290            }));
291        }
292        scope
293    }
294
295    /// Adds an event handler. It runs in the reactive scope that is current
296    /// now (usually the component being built), so `inject`, `spawn_local`
297    /// and friends work inside it.
298    pub fn on_event(&self, id: NodeId, handler: impl Fn(&UiEvent) + 'static) {
299        let owner = mitsuami_reactive::Owner::current();
300        let handler = move |event: &UiEvent| match owner {
301            Some(owner) if owner.is_alive() => owner.with(|| handler(event)),
302            _ => handler(event),
303        };
304        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
305            node.handlers.push(Rc::new(handler));
306        }
307    }
308}