Skip to main content

mitsuami_core/ui/
tree.rs

1//! The tree's structure, and keeping the backend's native children and
2//! props in step with it.
3
4use std::collections::{BTreeMap, HashMap, HashSet};
5
6use crate::command::Command;
7use crate::widget::{NodeId, Prop, WidgetKind};
8
9use super::{Inner, Ui, in_chrome};
10
11impl Ui {
12    /// Inserts `child` under `parent` at `index` (or at the end), detaching it
13    /// from its previous parent first.
14    pub fn insert_child(&self, parent: NodeId, child: NodeId, index: Option<usize>) {
15        {
16            let mut inner = self.inner.borrow_mut();
17            if !inner.nodes.contains_key(&parent) || !inner.nodes.contains_key(&child) {
18                return;
19            }
20            inner.detach(child);
21            let siblings = &mut inner.nodes.get_mut(&parent).unwrap().children;
22            let index = index.unwrap_or(siblings.len()).min(siblings.len());
23            siblings.insert(index, child);
24            inner.nodes.get_mut(&child).unwrap().parent = Some(parent);
25            inner.mark_resync(parent);
26            inner.styles_dirty = true;
27        }
28        self.changed();
29    }
30
31    pub fn append_child(&self, parent: NodeId, child: NodeId) {
32        self.insert_child(parent, child, None);
33    }
34
35    /// Replaces the children of `parent`, keeping nodes that stay.
36    pub fn set_children(&self, parent: NodeId, children: Vec<NodeId>) {
37        {
38            let mut inner = self.inner.borrow_mut();
39            if !inner.nodes.contains_key(&parent) {
40                return;
41            }
42            // The parent's children are replaced below, so the ones that go
43            // only lose their parent: detaching each would scan them all.
44            let staying: HashSet<NodeId> = children.iter().copied().collect();
45            let old = std::mem::take(&mut inner.nodes.get_mut(&parent).unwrap().children);
46            let mut roots = Vec::new();
47            for child in old.iter().filter(|c| !staying.contains(c)) {
48                if let Some(node) = inner.nodes.get_mut(child) {
49                    node.parent = None;
50                    roots.extend(inner.native_roots(*child));
51                }
52            }
53            // And leave their native parent together, so destroying them
54            // next (as `For` does) doesn't look for each among the others.
55            inner.detach_native_all(&roots);
56            // Children coming from other parents leave each together: one
57            // at a time scanned its siblings for each.
58            let mut moving: BTreeMap<NodeId, HashSet<NodeId>> = BTreeMap::new();
59            for child in &children {
60                let Some(node) = inner.nodes.get_mut(child) else { continue };
61                if let Some(other) = node.parent.filter(|p| *p != parent) {
62                    moving.entry(other).or_default().insert(*child);
63                }
64                node.parent = Some(parent);
65            }
66            for (other, gone) in moving {
67                if let Some(node) = inner.nodes.get_mut(&other) {
68                    node.children.retain(|c| !gone.contains(c));
69                }
70                inner.mark_resync(other);
71            }
72            inner.nodes.get_mut(&parent).unwrap().children = children;
73            inner.mark_resync(parent);
74            inner.styles_dirty = true;
75        }
76        self.changed();
77    }
78
79    /// Removes a node and its whole subtree, natively too.
80    pub fn destroy(&self, id: NodeId) {
81        // Dropped after the borrow: a handler's drop may dispose a scope
82        // (`owner_or_node_scope`) whose cleanups use the `Ui`.
83        let mut removed = Vec::new();
84        {
85            let mut inner = self.inner.borrow_mut();
86            if !inner.nodes.contains_key(&id) {
87                return;
88            }
89            inner.detach(id);
90            inner.focus_dirty = true;
91            // Remove the subtree's native roots from their native parent now,
92            // so the backend sees Remove before Destroy.
93            let roots = inner.native_roots(id);
94            inner.detach_native_all(&roots);
95            let mut subtree = Vec::new();
96            inner.collect_subtree(id, &mut subtree);
97            // Layout boxes go parents first: Taffy takes a box out of its
98            // parent's children by scanning them, unless the parent is gone.
99            for node_id in subtree.iter().rev() {
100                if let Some(t) = inner.nodes[node_id].taffy {
101                    let _ = inner.taffy.remove(t);
102                }
103            }
104            for node_id in subtree {
105                let node = inner.nodes.remove(&node_id).expect("in subtree");
106                inner.resync.remove(&node_id);
107                if node.kind == WidgetKind::Window {
108                    inner.windows.retain(|w| *w != node_id);
109                    inner.destroyed_windows.push(node_id);
110                }
111                inner.focus_orders.remove(&node_id);
112                inner.focused.retain(|window, focused| *window != node_id && *focused != node_id);
113                if node.kind.is_native() {
114                    inner.pending.push(Command::Destroy { id: node_id });
115                }
116                removed.push(node);
117            }
118        }
119        drop(removed);
120        self.changed();
121    }
122}
123
124impl Inner {
125    /// Sends a prop. Until the node's `Create` has gone out, the prop joins
126    /// it, so backends create every widget with its initial props (reactive
127    /// ones included): custom widgets and native views can't be created
128    /// without theirs.
129    pub(super) fn queue_prop(&mut self, id: NodeId, prop: Prop) {
130        // A new range may clamp a slider's value: the value follows it.
131        let then = match prop {
132            Prop::Range { .. } => {
133                self.nodes.get(&id).and_then(|n| n.props.iter().find(|p| matches!(p, Prop::Number(_)))).cloned()
134            }
135            _ => None,
136        };
137        self.queue_prop_now(id, prop);
138        if let Some(number) = then {
139            self.queue_prop_now(id, number);
140        }
141    }
142
143    fn queue_prop_now(&mut self, id: NodeId, prop: Prop) {
144        if !self.created.contains(&id) {
145            self.pending.push(Command::SetProp { id, prop });
146            return;
147        }
148        let create = self.pending.iter_mut().rev().find_map(|command| match command {
149            Command::Create { id: created, props, .. } if *created == id => Some(props),
150            _ => None,
151        });
152        match create {
153            Some(props) => {
154                props.retain(|p| p.key() != prop.key());
155                props.push(prop);
156            }
157            None => self.pending.push(Command::SetProp { id, prop }),
158        }
159    }
160
161    fn mark_resync(&mut self, id: NodeId) {
162        if let Some(native) = self.native_ancestor_or_self(id) {
163            self.resync.insert(native);
164        }
165    }
166
167    fn native_ancestor_or_self(&self, id: NodeId) -> Option<NodeId> {
168        let mut current = Some(id);
169        while let Some(node_id) = current {
170            let node = self.nodes.get(&node_id)?;
171            if node.kind.is_native() {
172                return Some(node_id);
173            }
174            current = node.parent;
175        }
176        None
177    }
178
179    fn detach(&mut self, child: NodeId) {
180        let Some(parent) = self.nodes.get(&child).and_then(|n| n.parent) else { return };
181        if let Some(node) = self.nodes.get_mut(&parent) {
182            node.children.retain(|c| *c != child);
183        }
184        self.nodes.get_mut(&child).unwrap().parent = None;
185        self.mark_resync(parent);
186    }
187
188    /// Removes native nodes from their native parents, immediately. Each
189    /// parent's children are scanned once, however many of them go.
190    fn detach_native_all(&mut self, children: &[NodeId]) {
191        let mut gone: BTreeMap<NodeId, HashSet<NodeId>> = BTreeMap::new();
192        for &child in children {
193            let Some(parent) = self.nodes.get(&child).and_then(|n| n.native_parent) else { continue };
194            self.pending.push(Command::Remove { parent, child });
195            self.nodes.get_mut(&child).unwrap().native_parent = None;
196            gone.entry(parent).or_default().insert(child);
197        }
198        for (parent, children) in gone {
199            let Some(node) = self.nodes.get_mut(&parent) else { continue };
200            node.native_children.retain(|c| !children.contains(c));
201            // A list's rows and a window's toolbar items and sidebar aren't
202            // in its layout box (`layout_list`, `layout_toolbar`).
203            let Some(p) = node.taffy.filter(|_| !node.kind.has_rows()) else { continue };
204            let boxes: HashSet<taffy::NodeId> = children.iter().filter_map(|c| self.nodes[c].taffy).collect();
205            let Ok(mut kept) = self.taffy.children(p) else { continue };
206            let before = kept.len();
207            kept.retain(|t| !boxes.contains(t));
208            if kept.len() != before {
209                let _ = self.taffy.set_children(p, &kept);
210            }
211        }
212    }
213
214    /// The native nodes a subtree contributes to its native parent.
215    fn native_roots(&self, id: NodeId) -> Vec<NodeId> {
216        let node = &self.nodes[&id];
217        if node.kind.is_native() {
218            return vec![id];
219        }
220        node.children.iter().flat_map(|c| self.native_roots(*c)).collect()
221    }
222
223    fn flattened_children(&self, id: NodeId) -> Vec<NodeId> {
224        let mut children: Vec<NodeId> = self.nodes[&id].children.iter().flat_map(|c| self.native_roots(*c)).collect();
225        // A window's toolbar items come after its content, and its sidebar
226        // after them.
227        children.sort_by_key(|c| match self.nodes[c].kind {
228            WidgetKind::ToolbarItem => 1,
229            WidgetKind::Sidebar => 2,
230            _ => 0,
231        });
232        children
233    }
234
235    fn collect_subtree(&self, id: NodeId, out: &mut Vec<NodeId>) {
236        for child in &self.nodes[&id].children {
237            self.collect_subtree(*child, out);
238        }
239        out.push(id);
240    }
241
242    pub(super) fn resync_all(&mut self) {
243        let dirty = std::mem::take(&mut self.resync);
244        for id in dirty {
245            if self.nodes.contains_key(&id) {
246                self.resync_node(id);
247            }
248        }
249    }
250
251    /// Makes the backend's children of `parent` match the core tree.
252    ///
253    /// The children that stay in the same order (the longest run of them)
254    /// stay put; the others that stay are removed, and then every child
255    /// not in place is inserted, in order, each at its final index. A
256    /// reorder costs one pass, and the fewest moves, where moving each
257    /// child into place in turn was quadratic for a list reversed.
258    fn resync_node(&mut self, parent: NodeId) {
259        let desired = self.flattened_children(parent);
260        let current = self.nodes[&parent].native_children.clone();
261        let staying: HashSet<NodeId> = desired.iter().copied().collect();
262        let leaving: Vec<NodeId> = current.iter().copied().filter(|c| !staying.contains(c)).collect();
263        self.detach_native_all(&leaving);
264        let at: HashMap<NodeId, usize> =
265            current.iter().filter(|c| staying.contains(c)).enumerate().map(|(i, c)| (*c, i)).collect();
266        let kept = in_order(&desired, &at);
267        for child in current.iter().filter(|c| at.contains_key(c) && !kept.contains(c)) {
268            self.pending.push(Command::Remove { parent, child: *child });
269        }
270        // Children coming from other parents leave them together, so each
271        // parent's children are scanned once.
272        let adopted: Vec<NodeId> = desired
273            .iter()
274            .copied()
275            .filter(|c| !at.contains_key(c) && self.nodes[c].native_parent.is_some_and(|other| other != parent))
276            .collect();
277        self.detach_native_all(&adopted);
278        // Everything before `index` is in place by now: the kept children
279        // are in their order, and the others went in in theirs.
280        for (index, child) in desired.iter().enumerate() {
281            if !kept.contains(child) {
282                self.pending.push(Command::Insert { parent, child: *child, index });
283            }
284        }
285        for child in &desired {
286            self.nodes.get_mut(child).unwrap().native_parent = Some(parent);
287        }
288        // Toolbar items are laid out on their own (`layout_toolbar`); the
289        // sidebar is the platform's.
290        let taffy_children: Vec<_> =
291            desired.iter().filter(|c| !in_chrome(self.nodes[*c].kind)).filter_map(|c| self.nodes[c].taffy).collect();
292        // A list's rows are laid out on their own (`layout_list`).
293        if let Some(t) = self.nodes[&parent].taffy.filter(|_| !self.nodes[&parent].kind.has_rows()) {
294            let _ = self.taffy.set_children(t, &taffy_children);
295        }
296        self.nodes.get_mut(&parent).unwrap().native_children = desired;
297    }
298
299    /// Whether a node is a page of a `Tabs`.
300    pub(super) fn is_page(&self, id: NodeId) -> bool {
301        self.nodes[&id].parent.is_some_and(|p| self.nodes[&p].kind == WidgetKind::Tabs)
302    }
303
304    /// Whether a node is a page of a `Tabs` that isn't shown: every other
305    /// page than the chosen one.
306    pub(super) fn is_hidden_page(&self, id: NodeId) -> bool {
307        let Some(tabs) = self.nodes[&id].parent.filter(|p| self.nodes[p].kind == WidgetKind::Tabs) else {
308            return false;
309        };
310        let tabs = &self.nodes[&tabs];
311        let shown = crate::find_prop!(tabs.props, SelectedIndex).flatten();
312        shown.and_then(|i| tabs.children.get(i)) != Some(&id)
313    }
314}
315
316/// The longest run of `children` already in order: those whose positions
317/// in `at` (where they are now) increase, found by patience sorting.
318fn in_order(children: &[NodeId], at: &HashMap<NodeId, usize>) -> HashSet<NodeId> {
319    let present: Vec<(NodeId, usize)> = children.iter().filter_map(|c| Some((*c, *at.get(c)?))).collect();
320    // `tails[n]`: the child ending the best run of length n + 1 so far.
321    let mut tails: Vec<usize> = Vec::new();
322    let mut previous: Vec<Option<usize>> = Vec::with_capacity(present.len());
323    for (i, (_, position)) in present.iter().enumerate() {
324        let n = tails.partition_point(|&t| present[t].1 < *position);
325        previous.push(n.checked_sub(1).map(|n| tails[n]));
326        match tails.get_mut(n) {
327            Some(tail) => *tail = i,
328            None => tails.push(i),
329        }
330    }
331    let mut kept = HashSet::with_capacity(tails.len());
332    let mut next = tails.last().copied();
333    while let Some(i) = next {
334        kept.insert(present[i].0);
335        next = previous[i];
336    }
337    kept
338}