Skip to main content

day_core/
tree.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The realized tree: nodes own native handles (or are layout-only), a reactive scope, and
5//! layout state. One `Tree<B>` per process, installed thread-local; bindings and event
6//! handlers reach it through [`with_tree`], and tree methods never run user code, so the
7//! single-borrow discipline holds (§3.3, §8.3).
8
9use std::any::Any;
10use std::cell::{Cell, RefCell};
11use std::collections::{HashMap, VecDeque};
12use std::rc::Rc;
13
14use day_reactive::Scope;
15use day_spec::*;
16use slotmap::{Key, KeyData, SlotMap, new_key_type};
17
18use crate::layout::{Alignment, CrossAlign, Layout, PassThrough};
19
20new_key_type! {
21    /// Realized-node key. `NodeId` (the spec-boundary id) is its FFI encoding.
22    pub struct RNode;
23}
24
25#[must_use]
26pub fn rnode_to_id(n: RNode) -> NodeId {
27    NodeId(n.data().as_ffi())
28}
29#[must_use]
30pub fn id_to_rnode(id: NodeId) -> RNode {
31    RNode::from(KeyData::from_ffi(id.0))
32}
33
34/// Read-only layout facts a parent may consult about a child (§7.2 `ChildRef`).
35#[derive(Clone, Copy, Debug, Default, PartialEq)]
36pub struct Flex {
37    /// Wants to fill the horizontal / vertical axis when offered space.
38    pub grow_w: bool,
39    pub grow_h: bool,
40    /// Sized after its rigid siblings in a column, against the height they leave (a
41    /// `.max_height` cap): it gives way to them on a short screen, but unlike `grow_h` it never
42    /// makes the column fill what it is offered.
43    pub yields_h: bool,
44    /// Takes all remaining main-axis space in a stack.
45    pub is_spacer: bool,
46    /// Layout-transparent group (`when`/`each` anchors): stacks lay out its children inline.
47    pub is_group: bool,
48    /// Grid facts (docs/grid.md): consulted only by `GridLayout`; inert everywhere else.
49    pub grid: GridFacts,
50    /// The node is the platform's whole list row (a native `kinds::LIST_ITEM`): it sizes the
51    /// row's height itself, so a list cell gives it only the side margins (docs/list.md "Row
52    /// metrics").
53    pub whole_row: bool,
54}
55
56/// Per-node grid facts (docs/grid.md), carried on [`Flex`]: the shipped form of the §7.2
57/// `ChildRef` facts surface. Set at build time by `grid_row` and the `.grid_span`/`.grid_align`
58/// modifiers; only `GridLayout` reads them.
59#[derive(Clone, Copy, Debug, Default, PartialEq)]
60pub struct GridFacts {
61    /// The node is a `grid_row` carrier: its children are that row's cells.
62    pub is_row: bool,
63    /// Row-only: vertical alignment override for the row's cells.
64    pub row_valign: Option<CrossAlign>,
65    /// Cell-only: columns spanned (0 = unset = 1).
66    pub col_span: u16,
67    /// Cell-only: alignment override within the cell rect.
68    pub align: Option<Alignment>,
69}
70
71/// Cached last-applied props for the dayscript element index (§14.2).
72#[derive(Clone, Debug, Default)]
73pub struct NodeProbe {
74    pub text: String,
75    /// A label's effective font, also used by text reservation measurement.
76    pub font: Option<day_spec::FontSpec>,
77    pub value: f64,
78    pub flag: bool,
79    pub selected: i64,
80    /// A picker's option labels, so `text` can follow the selection through either patch:
81    /// the label is what the control shows, and the index alone cannot reconstruct it.
82    pub options: Vec<String>,
83    pub enabled: bool,
84    /// Native keyboard focus, mirrored from `Event::FocusChanged` (docs/focus.md).
85    pub focused: bool,
86}
87
88pub struct NodeData<H> {
89    pub kind: PieceKind,
90    pub handle: Option<H>,
91    pub parent: RNode,
92    pub children: Vec<RNode>,
93    pub layout: Rc<dyn Layout>,
94    pub flex: Flex,
95    pub scope: Scope,
96    pub id: Option<String>,
97    /// The id a recycled cell's node carried before subtree recycling parked it
98    /// (docs/list.md). A pooled row must stop answering lookups while it is hidden, but its
99    /// next bind may show the same row content again (a slot write of an unchanged value,
100    /// which fires no reactive `id_of` and re-runs no static `.id()`), so the parked id is what
101    /// `restore_subtree_ids` hands back on rebind.
102    pub parked_id: Option<String>,
103    /// Accumulated accessibility annotations (§13): merged from the piece default, `.a11y()`,
104    /// and `.id()`. Stored so each `set_a11y` re-applies the full picture and `a11y_audit`
105    /// (§14.2) can diff the native tree against Day's own expectation.
106    pub a11y: day_spec::A11yProps,
107    // --- layout state (§7.4) ---
108    pub cache: Vec<((u64, u64), Size)>,
109    /// The last `(size, first baseline)` this node answered (docs/baseline.md). One slot, not a
110    /// list: a baseline is asked for at the size the row already settled on, so the query
111    /// repeats at one size per pass. Invalidated with `needs_measure`, alongside `cache`.
112    pub baseline_cache: Option<((u64, u64), Option<f64>)>,
113    pub probe: NodeProbe,
114    pub needs_measure: bool,
115    /// Placement dirt reaches the root even through measure boundaries. Recycled cell
116    /// subtrees are detached from the window tree, so their sweep must see this bit.
117    pub needs_layout: bool,
118    pub last_native_frame: Option<Rect>,
119    pub is_boundary: bool,
120    /// Scroll-content size reported by `ScrollLayout` (§7.6); scroll nodes only. Cached so
121    /// `scroll_to_target` can compose edge targets (bottom = content minus viewport).
122    pub scroll_content: Option<Size>,
123    /// Node-scoped implicit animation (`.animation(anim)`, §8.4): when set, this node's property
124    /// patches and frame changes animate even outside a `with_animation`. The ambient animation
125    /// (`with_animation`) takes precedence when both are present.
126    pub implicit_anim: Option<day_spec::AnimSpec>,
127    /// A `.tweak` closure (or a per-toolkit ext modifier, which routes through it) ran against
128    /// this node's handle (docs/tweaks.md). Read by `set_node_selectable`: a backing swap would
129    /// discard that work, which warrants a loud warning rather than silent loss.
130    pub tweaked: bool,
131}
132
133/// An event handler registered on a realized node.
134pub type EventHandler = Rc<dyn Fn(&Event)>;
135
136/// The recording/telemetry observer installed via [`set_event_observer`] (§14.6): called with
137/// every dispatched `(NodeId, Event)`, in queue order, before the app receives it.
138pub type EventObserver = dyn Fn(NodeId, &Event);
139
140/// `TreeOps::open_window_root`'s answer: the tree-level face of
141/// [`day_spec::WindowOpenReply`], carrying the adopted (or parked) root node.
142#[derive(Clone, Copy, PartialEq, Eq, Debug)]
143pub enum WindowRootReply {
144    /// The native window exists; `root` is its adopted boundary root, laid out already.
145    Open(RNode),
146    /// Native creation is in flight; `root` is parked, with no handle and no layout, until
147    /// `TreeOps::adopt_window_root` completes it.
148    Pending(RNode),
149    /// The toolkit cannot open windows; fall back to the cover tier.
150    Unsupported,
151}
152
153/// One realized window: an adopted boundary root plus the content size it lays out at.
154///
155/// `windows[0]` starts as the app's first window (the `ready` root container) and later entries
156/// are opened through `open_window_root` (docs/windows.md), but the first slot is not
157/// privileged: it can close like any other, after which `windows[0]` is the oldest
158/// window still open, which is what `root()` then answers. The list is never emptied; see
159/// `remove_window_root`.
160struct WindowEntry {
161    root: RNode,
162    size: Size,
163}
164
165/// A node's context menu as the app gave it: fixed items, or a provider asked per summon.
166#[derive(Clone)]
167enum ContextMenuModel {
168    Items(Vec<day_spec::MenuItem>),
169    Provider(day_spec::ContextMenuFn),
170}
171
172pub struct Tree<B: Toolkit> {
173    mounted_id_families: std::collections::BTreeSet<String>,
174    pub toolkit: B,
175    nodes: SlotMap<RNode, NodeData<B::Handle>>,
176    windows: Vec<WindowEntry>,
177    layout_dirty: bool,
178    handlers: HashMap<RNode, Vec<EventHandler>>,
179    /// The gesture kinds each node asked the toolkit for (`enable_gesture`): where a gesture
180    /// addressed to a descendant is redirected (see `dispatch_to_node`).
181    gestures: HashMap<RNode, Vec<day_spec::GestureKind>>,
182    /// A decorated piece's own node, mapped to the outermost node its modifiers wrapped it in
183    /// (`set_element_outer`): how far a gesture addressed to that node may climb.
184    element_outer: HashMap<RNode, RNode>,
185    /// A composed control's interactive node, used by identity modifiers.
186    element_targets: HashMap<RNode, RNode>,
187    // (kind, handle): the kind rides along so the drain can offer a satellite piece its
188    // `release` hook before the backend frees the handle (§15.2).
189    release_queue: Vec<(day_spec::PieceKind, B::Handle)>,
190    /// Recycling-list state keyed by list node (docs/list.md, §10).
191    lists: HashMap<RNode, crate::list::ListState>,
192    trees: HashMap<RNode, crate::tree_driver::TreeState>,
193    /// Each node's context menu as the app gave it, keyed by the node the modifier named (and
194    /// the native root it landed on, where that differs): what the dayscript `context_menu`
195    /// step reads, since the toolkit keeps its own copy in native form.
196    context_menus: HashMap<RNode, ContextMenuModel>,
197    /// Each menu button's provider (`set_button_menu`), keyed by its button node: the menu its
198    /// primary press opens, which the dayscript `context_menu` step chooses from too.
199    button_menus: HashMap<RNode, day_spec::ContextMenuFn>,
200    /// Count of nodes carrying an implicit `.animation` (§8.4). Gates the `resolve_anim` ancestor
201    /// walk: zero ⇒ non-`with_animation` patches skip it entirely (the common, O(1) path).
202    implicit_anim_count: usize,
203}
204
205impl<B: Toolkit> Tree<B> {
206    /// Drop the element ids of `anchor`'s whole subtree: the recycle write shared by tree
207    /// and list cells (a pooled cell keeps its nodes; only the dayscript identity must go).
208    /// Park every id under `anchor` so the (pooled, hidden) cell stops answering lookups. The
209    /// ids are kept, not dropped: `restore_subtree_ids` brings them back on the next bind.
210    fn clear_subtree_ids(&mut self, anchor: RNode) {
211        let mut stack = vec![anchor];
212        while let Some(n) = stack.pop() {
213            if let Some(d) = self.nodes.get_mut(n) {
214                if let Some(id) = d.id.take() {
215                    d.parked_id = Some(id);
216                }
217                stack.extend(d.children.iter().copied());
218            }
219        }
220    }
221
222    /// The inverse of `clear_subtree_ids`, run when a pooled cell is bound again: every node
223    /// that still has no id takes its parked one back. A node whose reactive `id_of` already
224    /// re-fired keeps the fresh id, and the parked copy is dropped either way.
225    fn restore_subtree_ids(&mut self, anchor: RNode) {
226        let mut stack = vec![anchor];
227        while let Some(n) = stack.pop() {
228            if let Some(d) = self.nodes.get_mut(n) {
229                if let Some(id) = d.parked_id.take()
230                    && d.id.is_none()
231                {
232                    d.id = Some(id);
233                }
234                stack.extend(d.children.iter().copied());
235            }
236        }
237    }
238
239    pub fn new(toolkit: B, root_handle: B::Handle, window_size: Size) -> Self {
240        let mut nodes = SlotMap::with_key();
241        let root = nodes.insert(NodeData {
242            kind: kinds::CONTAINER,
243            handle: Some(root_handle),
244            parent: RNode::null(),
245            children: Vec::new(),
246            layout: Rc::new(PassThrough),
247            flex: Flex::default(),
248            scope: Scope::root(),
249            id: None,
250            parked_id: None,
251            a11y: A11yProps::default(),
252            cache: Vec::new(),
253            baseline_cache: None,
254            probe: NodeProbe::default(),
255            needs_measure: true,
256            needs_layout: true,
257            last_native_frame: None,
258            scroll_content: None,
259            implicit_anim: None,
260            tweaked: false,
261            is_boundary: true,
262        });
263        Tree {
264            mounted_id_families: std::collections::BTreeSet::default(),
265            toolkit,
266            nodes,
267            windows: vec![WindowEntry {
268                root,
269                size: window_size,
270            }],
271            layout_dirty: true,
272            handlers: HashMap::new(),
273            gestures: HashMap::new(),
274            element_outer: HashMap::new(),
275            element_targets: HashMap::new(),
276            release_queue: Vec::new(),
277            lists: HashMap::new(),
278            trees: HashMap::new(),
279            context_menus: HashMap::new(),
280            button_menus: HashMap::new(),
281            implicit_anim_count: 0,
282        }
283    }
284
285    /// Create a node whose native handle is a foreign cell adopted from a recycling list host:
286    /// the same "wrap an externally-owned handle" trick the window root uses (docs/list.md).
287    pub(crate) fn create_cell_anchor(
288        &mut self,
289        handle: B::Handle,
290        scope: Scope,
291        layout: Rc<dyn Layout>,
292    ) -> RNode {
293        self.nodes.insert(NodeData {
294            kind: kinds::LIST_CELL,
295            handle: Some(handle),
296            parent: RNode::null(),
297            children: Vec::new(),
298            layout,
299            flex: Flex::default(),
300            scope,
301            id: None,
302            parked_id: None,
303            a11y: A11yProps::default(),
304            cache: Vec::new(),
305            baseline_cache: None,
306            probe: NodeProbe::default(),
307            needs_measure: true,
308            needs_layout: true,
309            last_native_frame: None,
310            scroll_content: None,
311            implicit_anim: None,
312            tweaked: false,
313            is_boundary: true,
314        })
315    }
316
317    pub fn root(&self) -> RNode {
318        self.windows[0].root
319    }
320
321    pub(crate) fn node(&self, n: RNode) -> Option<&NodeData<B::Handle>> {
322        self.nodes.get(n)
323    }
324    pub(crate) fn node_mut(&mut self, n: RNode) -> Option<&mut NodeData<B::Handle>> {
325        self.nodes.get_mut(n)
326    }
327
328    /// The animation intent for a change to `node` (§8.4): the ambient `with_animation` if one is
329    /// in scope, else the nearest `.animation` on `node` or an ancestor (SwiftUI-style
330    /// propagation). `None` ⇒ the change applies instantly. The ancestor walk is skipped entirely
331    /// when no implicit animations exist anywhere (`implicit_anim_count == 0`).
332    pub(crate) fn resolve_anim(&self, node: RNode) -> Option<day_spec::AnimSpec> {
333        // Reduced motion (the user's setting, or a scripted run's fast mode): every property
334        // and frame animation lands at its destination (docs/accessibility.md).
335        if crate::reduce_motion_now() {
336            return None;
337        }
338        if let Some(a) = crate::anim::current_anim() {
339            return Some(a);
340        }
341        if self.implicit_anim_count == 0 {
342            return None;
343        }
344        let mut cur = node;
345        loop {
346            let n = self.nodes.get(cur)?;
347            if n.implicit_anim.is_some() {
348                return n.implicit_anim;
349            }
350            if n.parent == cur {
351                return None;
352            }
353            cur = n.parent;
354        }
355    }
356
357    /// Nearest ancestor (or self) with a native handle.
358    fn native_ancestor(&self, mut n: RNode) -> RNode {
359        loop {
360            let Some(node) = self.nodes.get(n) else {
361                // Stale node: fall back to the primary window's root (harmless, since the
362                // caller is about to no-op against it).
363                return self.windows[0].root;
364            };
365            if node.handle.is_some() {
366                return n;
367            }
368            n = node.parent;
369        }
370    }
371
372    /// In-order native descendants of `container` (its native children, not descending into them).
373    fn native_descendants(&self, container: RNode, out: &mut Vec<RNode>) {
374        let Some(node) = self.nodes.get(container) else {
375            return;
376        };
377        for &c in &node.children {
378            match self.nodes.get(c) {
379                Some(cd) if cd.handle.is_some() => out.push(c),
380                Some(_) => self.native_descendants(c, out),
381                None => {}
382            }
383        }
384    }
385
386    /// Index that `child`'s first native node occupies (or will occupy) among `ancestor`'s
387    /// native children: an in-order walk counting native roots before reaching `child`'s subtree.
388    fn native_index_for(&self, ancestor: RNode, target: RNode) -> usize {
389        fn walk<B: Toolkit>(tree: &Tree<B>, n: RNode, target: RNode, count: &mut usize) -> bool {
390            if n == target {
391                return true;
392            }
393            let Some(node) = tree.nodes.get(n) else {
394                return false;
395            };
396            if node.handle.is_some() && n != target {
397                // A native node counts as one slot; do not descend (its children are inside it).
398                *count += 1;
399                return false;
400            }
401            for &c in &node.children {
402                if walk(tree, c, target, count) {
403                    return true;
404                }
405            }
406            false
407        }
408        let mut count = 0;
409        let Some(anc) = self.nodes.get(ancestor) else {
410            return 0;
411        };
412        for &c in &anc.children {
413            if c == target || self.subtree_contains(c, target) {
414                // Count native roots in this subtree before target.
415                let mut cnt = count;
416                walk(self, c, target, &mut cnt);
417                return cnt;
418            }
419            let mut roots = Vec::new();
420            match self.nodes.get(c) {
421                Some(cd) if cd.handle.is_some() => count += 1,
422                Some(_) => {
423                    self.native_descendants(c, &mut roots);
424                    count += roots.len();
425                }
426                None => {}
427            }
428        }
429        count
430    }
431
432    fn subtree_contains(&self, root: RNode, target: RNode) -> bool {
433        if root == target {
434            return true;
435        }
436        let Some(node) = self.nodes.get(root) else {
437            return false;
438        };
439        node.children
440            .iter()
441            .any(|&c| self.subtree_contains(c, target))
442    }
443
444    /// Attach `child` under `parent` at child-list `index`, wiring native insertion.
445    fn attach_impl(&mut self, parent: RNode, child: RNode, index: usize) {
446        {
447            let p = self
448                .nodes
449                .get_mut(parent)
450                .expect("attach to missing parent");
451            let idx = index.min(p.children.len());
452            p.children.insert(idx, child);
453        }
454        self.nodes
455            .get_mut(child)
456            .expect("attach missing child")
457            .parent = parent;
458        // Native wiring: every native root inside `child`'s subtree inserts under the nearest
459        // native ancestor at its in-order position.
460        let ancestor = self.native_ancestor(parent);
461        let anc_handle = self.nodes[ancestor]
462            .handle
463            .clone()
464            .expect("native ancestor");
465        let mut roots = Vec::new();
466        match self.nodes.get(child) {
467            Some(cd) if cd.handle.is_some() => roots.push(child),
468            Some(_) => self.native_descendants(child, &mut roots),
469            None => {}
470        }
471        for r in roots {
472            let idx = self.native_index_for(ancestor, r);
473            let h = self.nodes[r].handle.clone().unwrap();
474            self.toolkit.insert(&anc_handle, &h, idx);
475        }
476        self.mark_needs_measure_impl(parent);
477    }
478
479    fn remove_subtree_impl(&mut self, node: RNode) {
480        // Detach native roots from their native ancestor, queue every handle for release,
481        // drop handler entries, then remove the node records.
482        let parent = self.nodes.get(node).map_or(RNode::null(), |n| n.parent);
483        if let Some(p) = self.nodes.get_mut(parent) {
484            p.children.retain(|&c| c != node);
485        }
486        // A realized node may be owned outside a window (for example an audio session).
487        // It has no native parent until inserted. native_ancestor(null) falls back to the
488        // primary root, which must not receive a remove for a widget it never contained.
489        let anc_handle = if parent.is_null() {
490            None
491        } else {
492            let ancestor = self.native_ancestor(parent);
493            self.nodes.get(ancestor).and_then(|n| n.handle.clone())
494        };
495        let mut roots = Vec::new();
496        match self.nodes.get(node) {
497            Some(nd) if nd.handle.is_some() => roots.push(node),
498            Some(_) => self.native_descendants(node, &mut roots),
499            None => {}
500        }
501        if let Some(anc_handle) = anc_handle {
502            for r in &roots {
503                let h = self.nodes[*r].handle.clone().unwrap();
504                self.toolkit.remove(&anc_handle, &h);
505            }
506        }
507        self.collect_and_release(node);
508        if parent.is_null() {
509            self.layout_dirty = true;
510        } else {
511            self.mark_needs_measure_impl(parent);
512        }
513    }
514
515    /// Remove `start` and its whole day subtree from the node table: dispose list-cell
516    /// scopes, drop handler entries, queue every handle for release, decrement the
517    /// implicit-animation count. Shared by [`Self::remove_subtree_impl`] and
518    /// `remove_window_root` so the bookkeeping cannot drift between them.
519    fn collect_and_release(&mut self, start: RNode) {
520        let mut stack = vec![start];
521        while let Some(n) = stack.pop() {
522            // A list node's per-cell row subtrees live in scopes owned by the list machinery
523            // (not the node tree): dispose them with the node, or their bindings (e.g. a
524            // localized row label) outlive the list and patch freed native cells on the
525            // next locale/theme change (a use-after-free on raw-pointer backends like Qt).
526            self.context_menus.remove(&n);
527            self.button_menus.remove(&n);
528            if let Some(list) = self.lists.remove(&n) {
529                for (_, cell) in list.cells {
530                    cell.scope.dispose();
531                    // The cell's day subtree lives outside the node tree (anchored to a
532                    // native cell, not a list child): remove it with the list, or its nodes
533                    // linger as zombies: stale element ids that hijack `find_by_id`, and
534                    // handlers whose captured signals are disposed so every press no-ops.
535                    stack.push(cell.anchor);
536                }
537            }
538            // Tree cells follow the identical rule (docs/tree.md).
539            if let Some(tree) = self.trees.remove(&n) {
540                for (_, cell) in tree.cells {
541                    cell.scope.dispose();
542                    stack.push(cell.anchor);
543                }
544            }
545            let Some(data) = self.nodes.remove(n) else {
546                continue;
547            };
548            self.handlers.remove(&n);
549            self.gestures.remove(&n);
550            self.element_outer.remove(&n);
551            self.element_targets.remove(&n);
552            day_spec::keys::forget(rnode_to_id(n));
553            if data.implicit_anim.is_some() {
554                self.implicit_anim_count = self.implicit_anim_count.saturating_sub(1);
555            }
556            if let Some(h) = data.handle {
557                // …but a cell anchor's handle is not day's to free: it is the native list host's
558                // cell, borrowed through `adopt` (§15.3), and the host frees its cell pool
559                // when the host is released. Queuing it here deletes it a second time: heap
560                // corruption on the raw-pointer backends (xaml/qt). Dropping the handle still
561                // balances whatever `adopt` retained (AppKit/UIKit/GTK/Android refcounts).
562                if data.kind != kinds::LIST_CELL {
563                    self.release_queue.push((data.kind, h));
564                }
565            }
566            stack.extend(data.children);
567        }
568    }
569
570    fn mark_needs_measure_impl(&mut self, node: RNode) {
571        let mut cur = node;
572        let mut measure = true;
573        while let Some(n) = self.nodes.get_mut(cur) {
574            n.needs_layout = true;
575            if measure {
576                n.needs_measure = true;
577                n.cache.clear();
578            }
579            if n.is_boundary {
580                measure = false;
581            }
582            if n.parent.is_null() {
583                break;
584            }
585            cur = n.parent;
586        }
587        self.layout_dirty = true;
588    }
589
590    /// Forget every cached measurement under `node`, `node` included. The opposite walk from
591    /// [`Self::mark_needs_measure_impl`]: a cell re-laid at a new width (`list_layout_cell_width`,
592    /// `tree_layout_cell_width`) has to measure its whole row afresh, or a `grow` child keeps the
593    /// size it was given at the old width, is placed at that width again, and its own children
594    /// stay put; a trailing control then sits past the row's new edge.
595    fn invalidate_subtree(&mut self, node: RNode) {
596        let mut stack = vec![node];
597        while let Some(cur) = stack.pop() {
598            if let Some(n) = self.nodes.get_mut(cur) {
599                n.needs_measure = true;
600                n.cache.clear();
601                stack.extend(n.children.iter().copied());
602            }
603        }
604    }
605
606    /// Lay the list cell `key`'s row out at `width` × its `RowHeight`: the one place a list row
607    /// is placed, shared by the first-approximation pass (`list_layout_cell`) and the backend's
608    /// correction (`list_layout_cell_width`).
609    fn layout_list_cell_at(&mut self, node: RNode, key: usize, width: f64) {
610        let Some(state) = self.lists.get(&node) else {
611            return;
612        };
613        let (anchor, stale, header) = match state.cells.get(&key) {
614            Some(b) if b.active => (b.anchor, b.laid_width != Some(width), b.header),
615            _ => return,
616        };
617        // A section header sizes to its content in every list: a `Uniform` pitch is the
618        // items' (docs/list.md "Sections").
619        let row_height = if header {
620            day_spec::props::RowHeight::Automatic
621        } else {
622            state.driver.row_height
623        };
624        // A new width: nothing measured at the old one may survive, or a `grow` child keeps it.
625        // The same width again (the dirty-cell sweep re-lays every bound cell on every pass)
626        // keeps the row's measurement cache; re-measuring every row's text each pass is what
627        // made a 500-row list's binds take whole seconds (the sweep runs once per bind).
628        if stale {
629            self.invalidate_subtree(anchor);
630            if let Some(b) = self
631                .lists
632                .get_mut(&node)
633                .and_then(|s| s.cells.get_mut(&key))
634            {
635                b.laid_width = Some(width);
636            }
637        }
638        let height = match row_height {
639            day_spec::props::RowHeight::Uniform(h) => h,
640            day_spec::props::RowHeight::Automatic => {
641                crate::layout::measure_node(self, anchor, Proposal::new(Some(width), None)).height
642            }
643        };
644        let previous = self
645            .lists
646            .get_mut(&node)
647            .and_then(|s| s.cells.get_mut(&key))
648            .and_then(|b| b.laid_height.replace(height));
649        // A self-sizing row the host already sized has a new height: say so, or the native row
650        // keeps the old one and its content clips or leaves a gap. The first layout needs no
651        // patch: the host reads `cell_height` right after `bind_row` returns.
652        if previous.is_some_and(|p| (p - height).abs() > 0.25)
653            && let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone())
654        {
655            self.toolkit.update(
656                &handle,
657                kinds::LIST,
658                &day_spec::props::ListPatch::RowSizeInvalidated { cell: key, height } as &dyn Any,
659                None,
660            );
661        }
662        crate::layout::place_node(
663            self,
664            anchor,
665            Rect::new(0.0, 0.0, width, height),
666            Point::ZERO,
667            true,
668        );
669        // Placed: the dirty-cell sweep need not lay this row again until something in it
670        // changes; placement dirt reaches this anchor even through a nested measure boundary.
671        // Left set, the sweep re-laid every bound cell of every list on every layout pass.
672        self.nodes[anchor].needs_measure = false;
673    }
674
675    /// The tree twin of [`Self::layout_list_cell_at`]: lay tree cell `key`'s row out at `width`
676    /// × its `RowHeight`, keeping the row's measurement cache unless the width changed.
677    fn layout_tree_cell_at(&mut self, node: RNode, key: usize, width: f64) {
678        let Some(state) = self.trees.get(&node) else {
679            return;
680        };
681        let (anchor, stale) = match state.cells.get(&key) {
682            Some(b) => (b.anchor, b.laid_width != Some(width)),
683            None => return,
684        };
685        let row_height = state.driver.row_height;
686        let native_height = state.cells.get(&key).and_then(|b| b.native_height);
687        if stale {
688            self.invalidate_subtree(anchor);
689            if let Some(b) = self
690                .trees
691                .get_mut(&node)
692                .and_then(|s| s.cells.get_mut(&key))
693            {
694                b.laid_width = Some(width);
695            }
696        }
697        let height = native_height.unwrap_or_else(|| match row_height {
698            day_spec::props::RowHeight::Uniform(h) => h,
699            day_spec::props::RowHeight::Automatic => {
700                crate::layout::measure_node(self, anchor, Proposal::new(Some(width), None)).height
701            }
702        });
703        if let Some(b) = self
704            .trees
705            .get_mut(&node)
706            .and_then(|s| s.cells.get_mut(&key))
707        {
708            b.laid_height = Some(height);
709        }
710        crate::layout::place_node(
711            self,
712            anchor,
713            Rect::new(0.0, 0.0, width, height),
714            Point::ZERO,
715            true,
716        );
717        self.nodes[anchor].needs_measure = false;
718    }
719
720    fn layout_now(&mut self) {
721        // Every window lays out independently at its own size; the release queue drains
722        // once, after all of them (a released handle may be referenced by no window).
723        for i in 0..self.windows.len() {
724            let (root, size) = (self.windows[i].root, self.windows[i].size);
725            let p = Proposal::exact(size);
726            let _ = crate::layout::measure_node(self, root, p);
727            crate::layout::place_node(self, root, Rect::from_size(size), Point::ZERO, true);
728        }
729        // Bound list cells live outside the window trees: their anchors are parentless
730        // boundaries, laid out at bind time, so the window pass above never reaches them.
731        // Placement dirt reaches a cell's anchor even when measurement invalidation stops at
732        // a nested fixed frame. Sweep the marked cells so newly inserted descendants receive
733        // frames and a row label that grew mid-edit does not keep its stale frame.
734        let dirty_cells: Vec<(RNode, usize)> = self
735            .lists
736            .iter()
737            .flat_map(|(list, state)| {
738                state.cells.iter().filter_map(|(key, cell)| {
739                    if !cell.active {
740                        return None;
741                    }
742                    self.nodes
743                        .get(cell.anchor)
744                        .filter(|n| n.needs_layout)
745                        .map(|_| (*list, *key))
746                })
747            })
748            .collect();
749        let dirty_tree_cells: Vec<(RNode, usize)> = self
750            .trees
751            .iter()
752            .flat_map(|(tree, state)| {
753                state.cells.iter().filter_map(|(key, cell)| {
754                    self.nodes
755                        .get(cell.anchor)
756                        .filter(|n| n.needs_layout)
757                        .map(|_| (*tree, *key))
758                })
759            })
760            .collect();
761        for (tree, key) in dirty_tree_cells {
762            self.tree_layout_cell(tree, key);
763        }
764        for (list, key) in dirty_cells {
765            self.list_layout_cell(list, key);
766        }
767        let queue = std::mem::take(&mut self.release_queue);
768        for (kind, h) in queue {
769            // The piece's own teardown runs first, while the handle is still valid: it may read
770            // the native view to unregister an observer. `release` then frees it (§15.2).
771            self.toolkit.release_piece(kind, &h);
772            self.toolkit.release(h);
773        }
774    }
775}
776
777// ---------------------------------------------------------------------------
778// Object-safe tree surface for pieces / bindings / handlers
779// ---------------------------------------------------------------------------
780
781/// A programmatic scroll destination (§7.6, docs/scroll.md). Edges are axis extremes
782/// (`Top`/`Bottom` vertical, `Leading`/`Trailing` horizontal, i.e. start/end in layout direction);
783/// `Offset` pins the viewport origin to a content-space point (clamped by the platform);
784/// `Id` reveals the element with that dayscript id inside its nearest enclosing scroll.
785#[derive(Clone, Debug, PartialEq)]
786pub enum ScrollTarget {
787    Top,
788    Bottom,
789    Leading,
790    Trailing,
791    Offset(Point),
792    Id(String),
793}
794
795pub trait TreeOps {
796    // The parameter list mirrors NodeData's fields one-to-one; grouping them into a
797    // params struct would just move the same list behind a constructor.
798    #[allow(clippy::too_many_arguments)]
799    fn create_node(
800        &mut self,
801        kind: PieceKind,
802        props: &dyn Any,
803        layout: Rc<dyn Layout>,
804        flex: Flex,
805        native: bool,
806        is_boundary: bool,
807        scope: Scope,
808    ) -> RNode;
809    fn attach(&mut self, parent: RNode, child: RNode);
810    /// Move an existing subtree without disposing its scope or native handles.
811    fn reparent(&mut self, child: RNode, parent: RNode) -> bool;
812    fn native_window_tabs(&self) -> bool;
813    fn native_document_tabs(&self) -> bool;
814    fn group_windows(&mut self, roots: &[RNode]);
815    fn window_tab_order(&self, root: RNode) -> Vec<day_spec::NodeId>;
816
817    fn attach_at(&mut self, parent: RNode, child: RNode, index: usize);
818    fn reorder_children(&mut self, parent: RNode, order: Vec<RNode>);
819    fn remove_subtree(&mut self, node: RNode);
820    /// Whether `node` still exists (diagnostics: stale-id probes).
821    fn node_exists(&self, node: RNode) -> bool;
822    /// Whether the platform renders in dark appearance (see `Toolkit::dark_mode`).
823    fn dark_mode(&mut self) -> bool;
824    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color;
825    /// Whether the user asked for less motion (see `Toolkit::reduce_motion`).
826    fn reduce_motion(&mut self) -> bool;
827    /// Apply an app-level appearance override (see `Toolkit::set_appearance`).
828    fn set_appearance(&mut self, dark: Option<bool>);
829    /// Put a badge on the app icon (see `Toolkit::set_app_badge`, docs/badge.md).
830    fn set_app_badge(&mut self, badge: &day_spec::AppBadge);
831    fn on_event(&mut self, node: RNode, h: EventHandler);
832    fn handlers_for(&self, node: RNode) -> Vec<EventHandler>;
833    /// The node itself if it has a native view, else the one a chain of single-child
834    /// layout-only wrappers leads down to: the descent `enable_gesture` and `set_focusable`
835    /// make, for a modifier that has to reach the view (`Decorate::on_key`'s key mark).
836    fn native_view_of(&self, node: RNode) -> Option<RNode>;
837    /// The layout-only wrappers directly above `node` (single child, no native view), nearest
838    /// first: the same element as `node`, where an id or a modifier often sits.
839    fn wrappers_above(&self, node: RNode) -> Vec<RNode>;
840    /// The node a `kind` gesture addressed to `node` is delivered to: `node` itself when it
841    /// enabled that gesture, else the nearest node above it, within the same element, that did
842    /// (where a `.padding(..).on_tap(..)` registered its handler), else `None`. The element's
843    /// nodes are those its modifiers wrapped it in (`set_element_outer`), native containers
844    /// such as `.background(..)` included, plus any layout-only wrappers directly above. What
845    /// makes a dayscript step by id reach the handler the way a native gesture on the inner
846    /// view reaches the recognizer on its superview.
847    fn gesture_target(&self, node: RNode, kind: day_spec::GestureKind) -> Option<RNode>;
848    /// Record that a decorated piece's own node `inner` sits inside wrappers up to `outer`: the
849    /// span one element's modifiers built, which `gesture_target` climbs. A no-op when the two
850    /// are the same node.
851    fn set_element_outer(&mut self, inner: RNode, outer: RNode);
852    /// Identify a composed control by its interactive child rather than its layout container.
853    fn set_element_target(&mut self, outer: RNode, target: RNode);
854    fn element_target(&self, node: RNode) -> RNode;
855    fn set_id(&mut self, node: RNode, id: String);
856    /// Families attached at least once, including subsequently disposed/recycled nodes.
857    fn mounted_id_families(&self) -> Vec<String>;
858    /// Merge non-default grid cell facts onto a node's [`Flex`]: what the `.grid_span`/
859    /// `.grid_align` modifiers call (docs/grid.md). Called at build time, before the first layout.
860    fn set_grid_facts(&mut self, node: RNode, facts: GridFacts);
861    /// Give a wrapper that takes its size from `inner` (an overlay host) the inner node's
862    /// [`Flex::whole_row`], so a decorated platform row still reads as one to its list cell.
863    fn forward_whole_row(&mut self, wrapper: RNode, inner: RNode);
864    fn set_a11y(&mut self, node: RNode, a11y: A11yProps);
865    /// Speak `text` through the screen reader (`Toolkit::announce`, docs/accessibility.md).
866    fn announce(&mut self, text: &str, urgent: bool);
867    /// Attach a native gesture recognizer to `node` (docs/shapes.md): the backend then emits
868    /// `Event::Tap/LongPress/Drag` for it. The node must have a native handle.
869    fn enable_gesture(&mut self, node: RNode, kind: day_spec::GestureKind);
870    /// Move native keyboard focus to (or away from) `node` (docs/focus.md).
871    fn focus_node(&mut self, node: RNode, focused: bool);
872    /// Opt a container into the platform's focus system (docs/focus.md); what
873    /// `Decorate::focusable` calls. The node must have a native view somewhere under it.
874    fn set_focusable(&mut self, node: RNode, focusable: bool);
875    /// Mirror a `FocusChanged` event into the node's dayscript probe (pump-only).
876    fn set_probe_focused(&mut self, node: RNode, focused: bool);
877    /// Record which row of a nav host is current, on the `kinds::NAV` host that `.id()` tags
878    /// (docs/navigation.md). The host's `NavPatch::Select` carries a resident-page index
879    /// (visit order, which only coincides with row order when every page is built up front), so
880    /// the nav host reports the row index here instead. `None` = nothing selected (`-1`).
881    fn set_probe_selected(&mut self, node: RNode, selected: Option<usize>);
882    /// Record an external piece's current value in the node's dayscript probe, both the
883    /// numeric form (`assert_value`) and its display text (`assert_text`). The core patch
884    /// inspection only knows the builtin patch types, so a satellite piece (a stepper, a
885    /// rating) reports its own state through this instead (docs/extending.md).
886    fn set_probe_value(&mut self, node: RNode, value: f64, text: String);
887    fn set_app_menu(&mut self, items: Vec<day_spec::MenuItem>);
888    fn set_context_menu(&mut self, node: RNode, items: Vec<day_spec::MenuItem>);
889    /// Edit `root`'s window toolbar (docs/toolbars.md). `root` is a window root: the primary
890    /// root or one returned by `open_window_root`.
891    /// `false` when the toolkit did not apply it (the root has no native handle yet, or the
892    /// toolkit has no bar for it).
893    fn edit_window_toolbar(&mut self, root: RNode, ops: Vec<day_spec::ToolbarOp>) -> bool;
894    /// Apply a targeted change to one item of `root`'s toolbar; `false` as above.
895    fn patch_window_toolbar(&mut self, root: RNode, patch: day_spec::ToolbarPatch) -> bool;
896    /// Programmatic scroll (§7.6, docs/scroll.md): resolve `target` against a scroll node's
897    /// content/viewport and drive `Toolkit::scroll_to`. Returns false when `node` isn't a
898    /// realized scroll, or a supported native navigation menu with a top/bottom target
899    /// (the caller reports the miss; dayscript retries).
900    fn scroll_to_target(&mut self, node: RNode, target: &ScrollTarget, animated: bool) -> bool;
901    /// Scroll the nearest enclosing scroll ancestor so `node`'s frame is visible (minimal
902    /// scroll, `scrollRectToVisible` semantics). False when no scroll ancestor exists.
903    fn scroll_reveal(&mut self, node: RNode, animated: bool) -> bool;
904    fn patch(&mut self, node: RNode, patch: Box<dyn Any>, affects_size: bool);
905    fn replay(&mut self, node: RNode, ops: Vec<DrawOp>);
906    fn request_frame(&mut self, root: RNode, cb: day_spec::FrameCallback) -> day_spec::CancelFrame;
907    /// Set (or clear) a node's implicit `.animation` (§8.4): subsequent property patches and frame
908    /// changes on this node (or its descendants) animate with `anim` even outside a
909    /// `with_animation`.
910    fn set_implicit_anim(&mut self, node: RNode, anim: Option<day_spec::AnimSpec>);
911    /// Apply an animatable opacity (0..1) to `node`'s native handle (§8.4), animating if an
912    /// animation is in scope. No-op if the node has no handle.
913    fn set_node_opacity(&mut self, node: RNode, opacity: f64);
914    /// Apply an animatable [`Transform`] to `node`'s native handle (§8.4): the cheap movement/
915    /// scaling channel that never relayouts. No-op if the node has no handle.
916    fn set_node_transform(&mut self, node: RNode, t: day_spec::Transform);
917    /// Make `node`'s text user-selectable (the `.selectable()` modifier). One-shot and unmanaged;
918    /// No-op if the node has no handle.
919    fn set_node_selectable(&mut self, node: RNode, selectable: bool);
920    /// Apply a text field's [`InputTraits`](day_spec::InputTraits) (docs/textfield.md).
921    /// Idempotent; called again with the whole set when a reactive member changes. No-op if
922    /// the node has no handle.
923    fn set_node_input_traits(&mut self, node: RNode, traits: &day_spec::InputTraits);
924    /// Shape the pointer over `node` (the `.cursor()` modifier, docs/cursor.md). Idempotent;
925    /// called again when a reactive cursor changes. No-op if the node has no handle.
926    fn set_node_cursor(&mut self, node: RNode, cursor: day_spec::Cursor);
927    /// Make `node` move its window when dragged, like a title bar (`.window_drag_region()`,
928    /// docs/window-chrome.md).
929    fn set_node_drag_region(&mut self, node: RNode, drag: bool);
930    /// Record that a `.tweak` closure ran against `node`'s current handle (docs/tweaks.md), so
931    /// a later backing swap (`set_node_selectable` on a toolkit that rebuilds the widget) can
932    /// warn about the discarded work instead of losing it silently.
933    fn note_node_tweaked(&mut self, node: RNode) {
934        let _ = node;
935    }
936    fn mark_needs_measure(&mut self, node: RNode);
937    fn mark_layout_dirty(&mut self);
938    /// Forget every measurement Day holds and re-lay every bound list and tree row: the system
939    /// text size changed ([`crate::note_text_size_changed`]), so every text measurement is
940    /// stale, and a cached one would keep each label at its old size.
941    fn invalidate_all_measurements(&mut self);
942    fn layout_if_needed(&mut self);
943    fn set_window_size(&mut self, s: Size);
944    /// Report the app's current route to the backend (`Toolkit::set_route`); web-dom mirrors
945    /// it into the URL hash (docs/navigation.md). Called by the turn-end route sync when the
946    /// route actually changed.
947    fn set_route(&mut self, route: &str);
948    fn child_count(&self, node: RNode) -> usize;
949    fn first_child(&self, node: RNode) -> Option<RNode>;
950    /// `node`'s parent, `None` at a root: the window root, or a list cell's anchor, whose
951    /// parent is the native cell rather than a Day node.
952    fn parent_of(&self, node: RNode) -> Option<RNode>;
953    fn node_kind(&self, node: RNode) -> Option<PieceKind>;
954    /// The app-authored `.id()` string on `node` (`find_by_id`'s inverse), or `None` for an id-less
955    /// or disposed node. Backs the free [`id_of`], the recorder's `NodeId` → id lookup (§14.6).
956    fn node_id(&self, node: RNode) -> Option<String>;
957    /// A clone of the node's native handle boxed as `Any` (None for layout-only or disposed
958    /// nodes). `TreeOps` is object-safe, so the generic `Toolkit::Handle` can't appear here;
959    /// toolkit ext modules downcast to their concrete Handle type. This is the tweaks door
960    /// (docs/tweaks.md): cloning is cheap on every backend (a retain / gobject ref / `GlobalRef`
961    /// clone / Copy pointer) and the clone never outlives the native widget's own refcounting.
962    fn node_handle_any(&self, node: RNode) -> Option<Box<dyn Any>>;
963    fn node_frame(&self, node: RNode) -> Option<Rect>;
964    fn node_probe(&self, node: RNode) -> Option<NodeProbe>;
965    /// The node's accumulated accessibility annotations (§13): `a11y_audit`'s expectation.
966    fn node_a11y(&self, node: RNode) -> Option<A11yProps>;
967    /// The node's actual native state (`a11y_audit` diffs it against `node_a11y`, and
968    /// `assert_native` against the probe).
969    fn read_native(&self, node: RNode) -> Option<day_spec::NativeSnapshot>;
970    /// For every node with an `.id()` and a native handle: `(id, kind, expected, actual)`, the
971    /// raw material for the `a11y_audit` step (§14.2). Comparison/policy lives in day-script.
972    fn a11y_nodes(&self) -> Vec<(String, PieceKind, A11yProps, day_spec::NativeSnapshot)>;
973    fn find_by_id(&self, id: &str) -> Option<RNode>;
974    /// Show/hide the sidebar pane of the navigation host `host`: what the sidebar affordance
975    /// a `nav(Sidebar)` contributes for itself drives. `false` when the toolkit has no
976    /// pane to toggle there (or no sidebar concept at all). Per host, so a second window's
977    /// button collapses its own sidebar (docs/toolbars.md, docs/navigation.md).
978    fn toggle_sidebar(&mut self, _host: RNode) -> bool {
979        false
980    }
981    /// Press the platform's back affordance (`Toolkit::native_back`): the native path a
982    /// real tap takes, which `nav_back()` (Day's rail) never runs. `false` when nothing is
983    /// popped by it.
984    fn native_back(&mut self) -> bool {
985        false
986    }
987    /// Arm or release the platform's system back for the app's handlers
988    /// (`Toolkit::set_system_back`, docs/navigation.md "Handling the system Back").
989    fn set_system_back(&mut self, _armed: bool) {}
990    /// Establish a screenshot checkpoint for the window rooted at `root`, or the primary
991    /// window for `None` (see `Toolkit::prepare_snapshot`).
992    ///
993    /// # Errors
994    ///
995    /// Returns a message when that window is gone or the toolkit cannot set the checkpoint.
996    fn prepare_snapshot(
997        &mut self,
998        root: Option<RNode>,
999        revision: u32,
1000    ) -> Result<day_spec::capture::Readiness, String>;
1001    /// Capture the primary window's content (see `Toolkit::snapshot_window`).
1002    ///
1003    /// # Errors
1004    ///
1005    /// Returns the toolkit's message when it cannot capture the window.
1006    fn snapshot(&mut self) -> Result<Vec<u8>, String>;
1007    /// Where the primary window's root sits in [`Self::snapshot`]'s image, in points (see
1008    /// `Toolkit::snapshot_origin`); `None` when the toolkit does not say.
1009    fn snapshot_origin(&mut self) -> Option<Point>;
1010    /// The same capture with the window's own chrome (see `Toolkit::snapshot_window_chrome`).
1011    ///
1012    /// # Errors
1013    ///
1014    /// Returns the toolkit's message when it cannot capture the window.
1015    fn snapshot_chrome(&mut self) -> Result<Vec<u8>, String>;
1016
1017    // --- raster images (docs/images.md) -------------------------------------------------
1018    // Request-shaped, like `present`: the answer arrives as `Event::ImageDecoded` /
1019    // `Event::ImageEncoded` and resolves the waiter in `crate::image`.
1020
1021    /// Decode encoded bytes into a native image under `id` (see `Toolkit::decode_image`).
1022    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]);
1023    /// What a decoded image is (see `Toolkit::image_info`).
1024    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo>;
1025    /// An image's metadata beyond its pixels (see `Toolkit::image_properties`).
1026    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties>;
1027    /// Encode a decoded image back to bytes (see `Toolkit::encode_image`).
1028    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec);
1029    /// Which formats this toolkit encodes (see `Toolkit::encode_formats`).
1030    fn image_encode_formats(&mut self) -> Vec<day_spec::ImageFormat>;
1031    /// Release a decoded image (see `Toolkit::release_image`).
1032    fn release_image(&mut self, id: day_spec::BitmapId);
1033    /// Render a canvas drawing into a bitmap under `id` (see `Toolkit::render_bitmap`); the
1034    /// answer arrives as `Event::BitmapRendered`.
1035    fn render_bitmap(
1036        &mut self,
1037        req: u64,
1038        id: day_spec::BitmapId,
1039        ops: &[day_spec::DrawOp],
1040        size: Size,
1041        scale: f64,
1042    );
1043    /// Render canvas drawings into a PDF (see `Toolkit::render_pdf`); the answer arrives as
1044    /// `Event::PdfRendered`.
1045    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo);
1046    /// Whether the toolkit can rasterize its own window at all (`Cap::Snapshot`).
1047    fn window_image_support(&mut self) -> day_spec::Support;
1048    /// The platform's font families (see `Toolkit::font_families`); cached by day-core.
1049    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo>;
1050    /// Measure one line of canvas text (see `Toolkit::measure_text`).
1051    fn measure_text(
1052        &mut self,
1053        text: &str,
1054        size: f64,
1055        font: &day_spec::CanvasFont,
1056    ) -> Option<day_spec::TextMetrics>;
1057    /// Whether native transitions have settled (see `Toolkit::ui_idle`).
1058    fn ui_idle(&mut self) -> bool;
1059    fn root_node(&self) -> RNode;
1060
1061    // --- secondary windows (docs/windows.md) -------------------------------------------
1062
1063    /// Open a native window and adopt its content container as an additional boundary
1064    /// root. Inserts the root record, asks `Toolkit::open_window`, and answers per the
1065    /// toolkit's reply: `Open(root)` = live now (handle installed, window entry pushed),
1066    /// `Pending(root)` = native creation is in flight (the record is parked without a
1067    /// handle until [`Self::adopt_window_root`]), `Unsupported` = the placeholder was
1068    /// removed again; present the content as a cover instead.
1069    fn open_window_root(&mut self, options: &WindowOptions, kind: WindowKind) -> WindowRootReply;
1070    /// Complete a `Pending` open: adopt `raw` as the window's content container, install
1071    /// it on the parked root, and start laying out at `size`. `false` = the root is gone
1072    /// (closed before completion); the caller should drop the native window again.
1073    fn adopt_window_root(&mut self, root: RNode, raw: day_spec::RawHandle, size: Size) -> bool;
1074    /// Remove an (already childless) window root: bookkeeping + handle release + window
1075    /// entry removal. Never the primary. Idempotent; also valid for a parked Pending root.
1076    fn remove_window_root(&mut self, root: RNode);
1077    /// A secondary window's content size changed (its `WindowResized` handler).
1078    fn set_root_size(&mut self, root: RNode, s: Size);
1079
1080    /// Ask the toolkit to size the window whose content root is `root` to `size`
1081    /// (`WindowOptions::size_to_fit`). Also updates Day's own layout size for that root, so the
1082    /// content is re-laid at the size the window actually became.
1083    fn fit_window(&mut self, root: RNode, size: Size);
1084    /// Register an extra layout root: a node that stays attached in the tree (native
1085    /// re-homing needs the parent link) but lays out independently at its own reported
1086    /// size: the cover-fallback surface (docs/windows.md). The primary root's `PassThrough`
1087    /// layout only descends into its first child, so a second top-level surface must drive
1088    /// its own layout entry. `set_root_size` resizes it; drop it before subtree removal.
1089    fn add_extra_layout_root(&mut self, node: RNode, size: Size);
1090    /// Unregister an extra layout root (the entry only; the node itself is removed by the
1091    /// ordinary `remove_subtree`).
1092    fn drop_extra_layout_root(&mut self, node: RNode);
1093    /// Ask the platform to close the window whose root is `root` (async; the platform
1094    /// confirms with `Event::WindowClosed`).
1095    fn close_native_window(&mut self, root: RNode);
1096    /// End the app: the last primary window has closed (docs/windows.md close policy).
1097    fn quit_app(&mut self);
1098    /// Bring the window whose root is `root` to front and make it key.
1099    fn focus_native_window(&mut self, root: RNode);
1100    /// Retitle the window whose root is `root`.
1101    fn set_native_window_title(&mut self, root: RNode, title: &str);
1102    /// Apply a property change to the window whose root is `root` (docs/windows.md "Window
1103    /// properties"). Ignored for a root with no native handle yet.
1104    fn apply_window(&mut self, root: RNode, change: &day_spec::WindowChange);
1105    /// Install the app's Dock menu (docs/menus.md).
1106    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]);
1107    /// Show the app's status items (docs/status-item.md).
1108    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]);
1109    /// Show progress on the app's Dock or taskbar icon.
1110    fn set_app_progress(&mut self, progress: day_spec::AppProgress);
1111    /// Show or hide the macOS Dock icon.
1112    fn set_dock_visible(&mut self, visible: bool);
1113    /// Keep the process running when its last window closes (day-core decides when to quit).
1114    fn set_keep_running(&mut self, keep: bool);
1115    /// The outer frame of the window whose root is `root` (docs/windows.md).
1116    fn native_window_frame(&self, root: RNode) -> Option<day_spec::Rect>;
1117    /// The attached displays.
1118    fn monitors(&self) -> Vec<day_spec::Monitor>;
1119    /// Replace the app's run-time launcher shortcuts.
1120    fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]);
1121    /// Snapshot the window whose root is `root` (the primary answers `snapshot`).
1122    ///
1123    /// # Errors
1124    ///
1125    /// Returns a message when that window is gone or the toolkit cannot capture it.
1126    fn snapshot_of(&mut self, root: RNode) -> Result<Vec<u8>, String>;
1127    /// Toolkit capability probe (pieces pick presentation with it, e.g. `Cap::NavSplit`).
1128    fn capability(&self, cap: Cap) -> Support;
1129    /// Attach pull recognition to a mounted scroll view.
1130    fn attach_refresh(&mut self, node: RNode, host: NodeId);
1131    fn set_presented(&mut self, node: RNode, visible: bool);
1132    /// Does the running backend deliver this lifecycle phase (docs/lifecycle.md)?
1133    fn supports_lifecycle(&self, phase: day_spec::Lifecycle) -> bool;
1134    /// Present a native modal for request `req` (docs/dialogs.md).
1135    fn present(&mut self, req: u64, spec: &present::PresentSpec);
1136    /// Dismiss the modal for `req` (programmatic resolve while it is still up).
1137    fn dismiss(&mut self, req: u64);
1138    /// Open `url` in the platform's default handler (what the `link` piece calls).
1139    fn open_url(&mut self, url: &str);
1140    fn share_support(&self) -> Support;
1141    fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<RNode>) -> bool;
1142    /// Read the system's current associations for `query` (see
1143    /// `Toolkit::application_handlers`).
1144    ///
1145    /// # Errors
1146    ///
1147    /// Returns `ApplicationError::Unsupported` where the backend has no association query, or
1148    /// the platform's own failure.
1149    fn application_handlers(
1150        &mut self,
1151        query: &day_spec::applications::HandlerQuery,
1152    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>;
1153    fn open_url_with_application(
1154        &mut self,
1155        url: &str,
1156        application: &str,
1157        completion: day_spec::applications::OpenApplicationCompletion,
1158    );
1159
1160    /// Re-send the union of every mounted `defers_system_gestures` request (docs/cover.md).
1161    fn defer_system_gestures(&mut self, edges: day_spec::Edges);
1162    /// Re-send whether any mounted `status_bar_hidden` request asks to hide the status bar
1163    /// (docs/cover.md).
1164    fn set_status_bar_hidden(&mut self, hidden: bool);
1165
1166    // Recycling list methods (docs/list.md, §10). Called by day-core's `ListSource` closures
1167    // (via `with_tree`) when the native list pulls rows; never nested inside another borrow.
1168    // (`len`/`token_at` read the piece's snapshot directly and don't need the tree.)
1169    fn install_list(&mut self, node: RNode, driver: crate::list::ListDriver);
1170    /// Decide whether row `key`'s cell must be built (returns a fresh anchor) or rebound.
1171    /// `header`: the row about to bind is a section header (docs/list.md "Sections"); a cell
1172    /// that held the other kind is rebuilt.
1173    fn list_prepare_cell(
1174        &mut self,
1175        node: RNode,
1176        key: usize,
1177        cell: RawHandle,
1178        header: bool,
1179    ) -> crate::list::CellStep;
1180    /// Record a freshly built row (or section header) for a cell.
1181    fn list_store_cell(
1182        &mut self,
1183        node: RNode,
1184        key: usize,
1185        anchor: RNode,
1186        built: crate::list::BuiltRow,
1187        header: bool,
1188    );
1189    /// Lay the row out inside its cell bounds (row content width × the `RowHeight`).
1190    fn list_layout_cell(&mut self, node: RNode, key: usize);
1191    /// Re-lay the row at the cell's actual width (the list's width is only the first
1192    /// approximation: a native row's chrome, `GtkListView`'s themed `row` node, makes the cell
1193    /// narrower, and a row laid at the list's width holds the whole list wider than its frame).
1194    fn list_layout_cell_width(&mut self, node: RNode, key: usize, width: f64);
1195    /// The height the cell's row was last laid at (`ListSource::cell_height`); 0 before its
1196    /// first layout.
1197    fn list_cell_height(&self, node: RNode, key: usize) -> f64;
1198    /// The physical-cell keys of every bound cell of the list at `node` (for a bulk re-layout
1199    /// after the list's own width changed).
1200    /// Active cells eligible for width-change layout; excludes cells parked by `recycle`.
1201    fn list_cell_keys(&self, node: RNode) -> Vec<usize>;
1202    /// A pooled cell left the visible row set (an emulated backend hides rows past a shrunk
1203    /// source instead of destroying them): clear the cell subtree's element ids so stale rows
1204    /// stop answering dayscript lookups. The cell itself stays pooled; the next bind re-ids it.
1205    fn list_recycle_cell(&mut self, node: RNode, key: usize);
1206    /// The host discarded cell `key` of list `node` for good: dispose the row built in it.
1207    fn list_release_cell(&mut self, node: RNode, key: usize);
1208    /// Cell `key` is the host's pinned header copy (`ListSource::bind_pinned`): park its ids, now
1209    /// and on every rebind, so lookups find the header row in the list.
1210    fn list_pin_cell(&mut self, node: RNode, key: usize);
1211    /// Apply a data change: the native host re-queries the source.
1212    fn list_reload(&mut self, node: RNode);
1213    fn list_splice(&mut self, node: RNode, deltas: Vec<day_spec::props::RowDelta>);
1214    fn set_undo_state(&mut self, state: &day_spec::UndoState);
1215    fn set_edit_state(&mut self, state: &day_spec::EditState);
1216    fn modifiers(&mut self) -> day_spec::Modifiers;
1217    /// Imperatively scroll the native list so its last row is fully visible (no-op if empty).
1218    fn list_scroll_to_end(&mut self, node: RNode);
1219    /// Imperatively scroll the native list so row `row` is visible (clamped; no-op if empty).
1220    fn list_scroll_to_row(&mut self, node: RNode, row: usize);
1221    /// Programmatically sync the list's selected rows (empty = clear). The toolkit applies
1222    /// without re-emitting a selection event.
1223    fn list_set_selected(&mut self, node: RNode, rows: Vec<usize>);
1224    /// Enter or leave the list's native editing mode (`ListPatch::Editing`); a toolkit
1225    /// without one ignores it.
1226    fn list_set_editing(&mut self, node: RNode, on: bool);
1227    /// The list's driver, for the guard → commit path `list_try_reorder` runs outside the
1228    /// borrow (`None` when `node` hosts no list).
1229    fn list_driver(&mut self, node: RNode) -> Option<std::rc::Rc<crate::list::ListDriver>>;
1230
1231    // Hierarchical tree methods (docs/tree.md): the list methods' shape, token-addressed. Called
1232    // by day-core's `TreeSource` closures (via `with_tree`) when the native tree pulls
1233    // rows; never nested inside another borrow.
1234    fn install_tree(&mut self, node: RNode, driver: crate::tree_driver::TreeDriver);
1235    /// Decide whether the cell for `key` must be built (fresh anchor) or rebound.
1236    fn tree_prepare_cell(
1237        &mut self,
1238        node: RNode,
1239        key: usize,
1240        cell: RawHandle,
1241    ) -> crate::tree_driver::TreeCellStep;
1242    /// Record a freshly built row for a cell.
1243    fn tree_store_cell(
1244        &mut self,
1245        node: RNode,
1246        key: usize,
1247        anchor: RNode,
1248        built: crate::tree_driver::TreeBuiltRow,
1249    );
1250    /// Lay the row out inside its cell bounds (row content width × the `RowHeight`).
1251    fn tree_layout_cell(&mut self, node: RNode, key: usize);
1252    /// Re-lay the row at the cell's actual width (indentation makes tree cells per-row wide).
1253    fn tree_layout_cell_width(&mut self, node: RNode, key: usize, width: f64);
1254    fn tree_layout_cell_size(&mut self, node: RNode, key: usize, size: Size);
1255    /// The height the cell's row was last laid at (`TreeSource::cell_height`); 0 before its
1256    /// first layout.
1257    fn tree_cell_height(&self, node: RNode, key: usize) -> f64;
1258    /// The cell went back to the host's reuse pool: clear the row subtree's element ids, so
1259    /// a collapsed-away row stops answering `find_by_id` (dayscript `assert_missing`) and a
1260    /// stale id can never hijack a lookup. The next bind re-sets the live row's id.
1261    fn tree_recycle_cell(&mut self, node: RNode, key: usize);
1262    /// Apply a data change: the native host re-queries the source (expansion and selection
1263    /// survive by token).
1264    fn tree_reload(&mut self, node: RNode);
1265    /// Programmatically disclose/collapse one row (no `TreeExpanded` echo).
1266    fn tree_set_expanded(&mut self, node: RNode, token: u64, expanded: bool);
1267    /// Programmatically sync the tree's selected rows (no selection-event echo).
1268    fn tree_set_selected(&mut self, node: RNode, tokens: Vec<u64>);
1269    /// Scroll this row into view, realizing it if needed (ancestors already expanded).
1270    fn tree_reveal(&mut self, node: RNode, token: u64);
1271    /// The tree's driver, for the guard → commit path `tree_try_move` runs outside the
1272    /// borrow (`None` when `node` hosts no tree).
1273    fn tree_driver(&mut self, node: RNode) -> Option<std::rc::Rc<crate::tree_driver::TreeDriver>>;
1274    /// Install native transfer behavior on a realized host.
1275    fn set_drag_source(&mut self, node: RNode, source: day_spec::transfer::Source);
1276    fn set_drop_target(&mut self, node: RNode, target: day_spec::transfer::Target);
1277    /// Install a summon-time context-menu provider on `node` (docs/menus.md).
1278    fn set_context_menu_fn(&mut self, node: RNode, f: day_spec::ContextMenuFn);
1279    /// Make the button `node` a pull-down menu button whose primary press opens the menu `f`
1280    /// builds (docs/menus.md "Menu buttons").
1281    fn set_button_menu(&mut self, node: RNode, f: day_spec::ContextMenuFn);
1282    /// The context menu the app gave `node` (or its nearest ancestor that has one), as a
1283    /// provider; what the dayscript `context_menu` step chooses from. Returned rather than
1284    /// called, because a provider is app code: it may select what it summons over and flush,
1285    /// which re-enters the tree, so the caller asks it once the tree borrow has ended.
1286    fn context_menu_of(&mut self, node: RNode) -> Option<day_spec::ContextMenuFn>;
1287}
1288
1289impl<B: Toolkit> TreeOps for Tree<B> {
1290    fn set_presented(&mut self, node: RNode, visible: bool) {
1291        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
1292            self.toolkit.set_presented(&handle, visible);
1293        }
1294    }
1295
1296    fn attach_refresh(&mut self, node: RNode, host: NodeId) {
1297        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
1298            self.toolkit.attach_refresh(&handle, host);
1299        }
1300    }
1301
1302    fn capability(&self, cap: Cap) -> Support {
1303        self.toolkit.capability(cap)
1304    }
1305
1306    fn supports_lifecycle(&self, phase: day_spec::Lifecycle) -> bool {
1307        self.toolkit.supports_lifecycle(phase)
1308    }
1309
1310    fn present(&mut self, req: u64, spec: &present::PresentSpec) {
1311        self.toolkit.present(req, spec);
1312    }
1313
1314    fn dismiss(&mut self, req: u64) {
1315        self.toolkit.dismiss(req);
1316    }
1317
1318    fn open_url(&mut self, url: &str) {
1319        self.toolkit.open_url(url);
1320    }
1321    fn share_support(&self) -> Support {
1322        self.toolkit.share_support()
1323    }
1324    fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<RNode>) -> bool {
1325        let handle = anchor
1326            .and_then(|n| self.nodes.get(n))
1327            .and_then(|n| n.handle.clone());
1328        self.toolkit.share(spec, handle.as_ref())
1329    }
1330
1331    fn application_handlers(
1332        &mut self,
1333        query: &day_spec::applications::HandlerQuery,
1334    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
1335    {
1336        self.toolkit.application_handlers(query)
1337    }
1338
1339    fn open_url_with_application(
1340        &mut self,
1341        url: &str,
1342        application: &str,
1343        completion: day_spec::applications::OpenApplicationCompletion,
1344    ) {
1345        self.toolkit
1346            .open_url_with_application(url, application, completion);
1347    }
1348
1349    fn set_appearance(&mut self, dark: Option<bool>) {
1350        self.toolkit.set_appearance(dark);
1351    }
1352
1353    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
1354        self.toolkit.set_app_badge(badge);
1355    }
1356
1357    fn defer_system_gestures(&mut self, edges: day_spec::Edges) {
1358        self.toolkit.defer_system_gestures(edges);
1359    }
1360
1361    fn set_status_bar_hidden(&mut self, hidden: bool) {
1362        self.toolkit.set_status_bar_hidden(hidden);
1363    }
1364
1365    fn create_node(
1366        &mut self,
1367        kind: PieceKind,
1368        props: &dyn Any,
1369        layout: Rc<dyn Layout>,
1370        flex: Flex,
1371        native: bool,
1372        is_boundary: bool,
1373        scope: Scope,
1374    ) -> RNode {
1375        let mut probe = NodeProbe {
1376            enabled: true,
1377            ..Default::default()
1378        };
1379        {
1380            use day_spec::props::*;
1381            if let Some(p) = props.downcast_ref::<LabelProps>() {
1382                probe.text.clone_from(&p.text);
1383                probe.font = Some(p.font);
1384            } else if let Some(p) = props.downcast_ref::<NavMenuProps>() {
1385                probe.selected = p.selected.map_or(-1, |i| i as i64);
1386                probe.value = probe.selected as f64;
1387            } else if let Some(p) = props.downcast_ref::<ButtonProps>() {
1388                probe.text.clone_from(&p.title);
1389                probe.enabled = p.enabled;
1390                // The selected state reads like a toggle's (`assert_on`).
1391                probe.flag = p.selected;
1392            } else if let Some(p) = props.downcast_ref::<ToggleProps>() {
1393                probe.flag = p.on;
1394                probe.enabled = p.enabled;
1395            } else if let Some(p) = props.downcast_ref::<SliderProps>() {
1396                probe.value = p.value;
1397                probe.enabled = p.enabled;
1398            } else if let Some(p) = props.downcast_ref::<TextFieldProps>() {
1399                probe.text.clone_from(&p.text);
1400                probe.enabled = p.enabled;
1401            } else if let Some(p) = props.downcast_ref::<ProgressProps>() {
1402                // `flag` marks indeterminate; `value` holds the determinate fraction.
1403                probe.flag = p.value.is_none();
1404                probe.value = p.value.unwrap_or(0.0);
1405            } else if let Some(p) = props.downcast_ref::<PickerProps>() {
1406                probe.selected = p.selected as i64;
1407                probe.value = p.selected as f64;
1408                // A picker's text is the option it shows: what `assert_text` should see
1409                // (the index is `assert_value`'s answer). Kept current by both patches below.
1410                probe.text = p.options.get(p.selected).cloned().unwrap_or_default();
1411                probe.options.clone_from(&p.options);
1412                probe.enabled = p.enabled;
1413            } else if let Some(p) = props.downcast_ref::<TextAreaProps>() {
1414                probe.text.clone_from(&p.text);
1415            }
1416        }
1417        let node = self.nodes.insert(NodeData {
1418            kind,
1419            handle: None,
1420            parent: RNode::null(),
1421            children: Vec::new(),
1422            layout,
1423            flex,
1424            scope,
1425            id: None,
1426            parked_id: None,
1427            a11y: A11yProps::default(),
1428            cache: Vec::new(),
1429            baseline_cache: None,
1430            probe,
1431            needs_measure: true,
1432            needs_layout: true,
1433            last_native_frame: None,
1434            scroll_content: None,
1435            implicit_anim: None,
1436            tweaked: false,
1437            is_boundary,
1438        });
1439        if native {
1440            let h = self.toolkit.realize(kind, props, rnode_to_id(node));
1441            self.nodes[node].handle = Some(h);
1442        }
1443        node
1444    }
1445
1446    fn attach(&mut self, parent: RNode, child: RNode) {
1447        let index = self.nodes.get(parent).map_or(0, |p| p.children.len());
1448        self.attach_impl(parent, child, index);
1449    }
1450
1451    fn native_window_tabs(&self) -> bool {
1452        self.toolkit.native_window_tabs()
1453    }
1454    fn native_document_tabs(&self) -> bool {
1455        self.toolkit.native_document_tabs()
1456    }
1457    fn group_windows(&mut self, roots: &[RNode]) {
1458        let hosts = roots
1459            .iter()
1460            .filter_map(|r| self.nodes.get(*r)?.handle.clone())
1461            .collect::<Vec<_>>();
1462        self.toolkit.group_windows(&hosts);
1463    }
1464    fn window_tab_order(&self, root: RNode) -> Vec<day_spec::NodeId> {
1465        self.nodes
1466            .get(root)
1467            .and_then(|n| n.handle.as_ref())
1468            .map_or_default(|h| self.toolkit.window_tab_order(h))
1469    }
1470    fn reparent(&mut self, child: RNode, parent: RNode) -> bool {
1471        if !self.nodes.contains_key(child) || !self.nodes.contains_key(parent) {
1472            return false;
1473        }
1474        let old = self.nodes[child].parent;
1475        if old == parent {
1476            return true;
1477        }
1478        // Reject cycles and window roots: only content may migrate.
1479        if self.windows.iter().any(|w| w.root == child) {
1480            return false;
1481        }
1482        let mut up = parent;
1483        while let Some(n) = self.nodes.get(up) {
1484            if up == child {
1485                return false;
1486            }
1487            up = n.parent;
1488        }
1489        let ancestor = self.native_ancestor(old);
1490        let handle = self.nodes.get(ancestor).and_then(|n| n.handle.clone());
1491        let mut roots = Vec::new();
1492        if self.nodes[child].handle.is_some() {
1493            roots.push(child);
1494        } else {
1495            self.native_descendants(child, &mut roots);
1496        }
1497        if let Some(h) = handle {
1498            for r in roots {
1499                // roots contains only nodes with handles, collected above without mutation.
1500                self.toolkit
1501                    .remove(&h, self.nodes[r].handle.as_ref().unwrap());
1502            }
1503        }
1504        if let Some(p) = self.nodes.get_mut(old) {
1505            p.children.retain(|n| *n != child);
1506        }
1507        self.mark_needs_measure_impl(old);
1508        self.attach(parent, child);
1509        self.layout_dirty = true;
1510        true
1511    }
1512
1513    fn attach_at(&mut self, parent: RNode, child: RNode, index: usize) {
1514        self.attach_impl(parent, child, index);
1515    }
1516
1517    fn reorder_children(&mut self, parent: RNode, order: Vec<RNode>) {
1518        // Nothing moved, and the resync below is not free. `each` re-runs its diff whenever the
1519        // source closure's tracked reads wake it, which is far more often than the order changes:
1520        // a projection that reads its store coarsely re-runs for every keystroke in a field that
1521        // store also feeds. Re-inserting every native descendant on each of those is churn on the
1522        // backends that can re-parent cheaply, and on the ones whose `move_child` detaches first
1523        // (android, arkui) it also drops the keyboard focus of a text field inside the subtree
1524        // (docs/focus.md): the field a user was typing into loses focus per character.
1525        if self.nodes.get(parent).is_some_and(|p| p.children == order) {
1526            return;
1527        }
1528        if let Some(p) = self.nodes.get_mut(parent) {
1529            p.children = order;
1530        }
1531        // Full native resync of the nearest native ancestor: rebuild in-order positions.
1532        let ancestor = self.native_ancestor(parent);
1533        let anc_handle = self.nodes[ancestor]
1534            .handle
1535            .clone()
1536            .expect("native ancestor");
1537        let mut desired = Vec::new();
1538        self.native_descendants(ancestor, &mut desired);
1539        for (i, r) in desired.iter().enumerate() {
1540            let h = self.nodes[*r].handle.clone().unwrap();
1541            self.toolkit.move_child(&anc_handle, &h, i);
1542        }
1543        self.mark_needs_measure_impl(parent);
1544    }
1545
1546    fn remove_subtree(&mut self, node: RNode) {
1547        // Window roots have no native parent to detach from; they go through
1548        // `remove_window_root` (docs/windows.md), never here.
1549        debug_assert!(
1550            !self.windows.iter().any(|w| w.root == node),
1551            "remove_subtree called with a window root"
1552        );
1553        self.remove_subtree_impl(node);
1554    }
1555
1556    fn on_event(&mut self, node: RNode, h: EventHandler) {
1557        self.handlers.entry(node).or_default().push(h);
1558    }
1559
1560    fn handlers_for(&self, node: RNode) -> Vec<EventHandler> {
1561        self.handlers.get(&node).cloned().unwrap_or_default()
1562    }
1563    fn native_view_of(&self, node: RNode) -> Option<RNode> {
1564        let mut cur = node;
1565        for _ in 0..16 {
1566            let n = self.nodes.get(cur)?;
1567            if n.handle.is_some() {
1568                return Some(cur);
1569            }
1570            match n.children.as_slice() {
1571                [only] => cur = *only,
1572                _ => return None,
1573            }
1574        }
1575        None
1576    }
1577    fn gesture_target(&self, node: RNode, kind: day_spec::GestureKind) -> Option<RNode> {
1578        let has = |n: RNode| self.gestures.get(&n).is_some_and(|k| k.contains(&kind));
1579        if has(node) {
1580            return Some(node);
1581        }
1582        // Climb the element's own wrappers, native ones included. An element nested in another
1583        // (`.any()` and more modifiers) extends the span to the enclosing element's outer node.
1584        let mut cur = node;
1585        let mut bound = self.element_outer.get(&node).copied();
1586        while let Some(outer) = bound {
1587            if cur == outer {
1588                bound = self.element_outer.get(&outer).copied();
1589                continue;
1590            }
1591            let Some(parent) = self.nodes.get(cur).map(|n| n.parent) else {
1592                break;
1593            };
1594            if parent == cur || !self.nodes.contains_key(parent) {
1595                break;
1596            }
1597            cur = parent;
1598            if has(cur) {
1599                return Some(cur);
1600            }
1601        }
1602        self.wrappers_above(cur).into_iter().find(|w| has(*w))
1603    }
1604
1605    fn set_element_target(&mut self, outer: RNode, target: RNode) {
1606        if outer != target {
1607            self.element_targets.insert(outer, target);
1608            self.set_element_outer(target, outer);
1609        }
1610    }
1611
1612    fn element_target(&self, node: RNode) -> RNode {
1613        self.element_targets
1614            .get(&node)
1615            .copied()
1616            .filter(|n| self.nodes.contains_key(*n))
1617            .unwrap_or(node)
1618    }
1619
1620    fn set_element_outer(&mut self, inner: RNode, outer: RNode) {
1621        if inner != outer {
1622            self.element_outer.insert(inner, outer);
1623        }
1624    }
1625
1626    fn wrappers_above(&self, node: RNode) -> Vec<RNode> {
1627        let mut out = Vec::new();
1628        let mut cur = node;
1629        for _ in 0..16 {
1630            let Some(parent) = self.nodes.get(cur).map(|n| n.parent) else {
1631                break;
1632            };
1633            match self.nodes.get(parent) {
1634                Some(p) if p.handle.is_none() && p.children.len() == 1 && parent != cur => {
1635                    out.push(parent);
1636                    cur = parent;
1637                }
1638                _ => break,
1639            }
1640        }
1641        out
1642    }
1643    fn node_exists(&self, node: RNode) -> bool {
1644        self.nodes.contains_key(node)
1645    }
1646    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
1647        self.toolkit.system_color(role)
1648    }
1649
1650    fn dark_mode(&mut self) -> bool {
1651        self.toolkit.dark_mode()
1652    }
1653    fn reduce_motion(&mut self) -> bool {
1654        self.toolkit.reduce_motion()
1655    }
1656
1657    fn mounted_id_families(&self) -> Vec<String> {
1658        self.mounted_id_families.iter().cloned().collect()
1659    }
1660    fn set_id(&mut self, node: RNode, id: String) {
1661        if self.nodes.contains_key(node) {
1662            self.mounted_id_families
1663                .insert(crate::element_id::family_of(&id).to_owned());
1664        }
1665        if let Some(n) = self.nodes.get_mut(node) {
1666            n.id = Some(id.clone());
1667            n.a11y.merge(&A11yProps {
1668                identifier: Some(id),
1669                ..Default::default()
1670            });
1671            if let Some(h) = n.handle.clone() {
1672                self.toolkit.set_a11y(&h, &n.a11y);
1673            }
1674        }
1675    }
1676
1677    fn forward_whole_row(&mut self, wrapper: RNode, inner: RNode) {
1678        let whole = self.nodes.get(inner).is_some_and(|n| n.flex.whole_row);
1679        if let Some(n) = self.nodes.get_mut(wrapper) {
1680            n.flex.whole_row = whole;
1681        }
1682    }
1683
1684    fn set_grid_facts(&mut self, node: RNode, facts: GridFacts) {
1685        if let Some(n) = self.nodes.get_mut(node) {
1686            let g = &mut n.flex.grid;
1687            if facts.is_row {
1688                g.is_row = true;
1689            }
1690            if facts.row_valign.is_some() {
1691                g.row_valign = facts.row_valign;
1692            }
1693            if facts.col_span != 0 {
1694                g.col_span = facts.col_span;
1695            }
1696            if facts.align.is_some() {
1697                g.align = facts.align;
1698            }
1699        }
1700    }
1701
1702    fn announce(&mut self, text: &str, urgent: bool) {
1703        self.toolkit.announce(text, urgent);
1704    }
1705
1706    fn set_a11y(&mut self, node: RNode, a11y: A11yProps) {
1707        if let Some(n) = self.nodes.get_mut(node) {
1708            // Merge onto whatever's already recorded (piece default role, an earlier `.a11y`/`.id`)
1709            // and re-apply the full picture; backends set each present field idempotently (§13).
1710            n.a11y.merge(&a11y);
1711            // A canvas has no text of its own: what it tells a screen reader (its value, else
1712            // its label) is its text, so `assert_text` reads a drawn readout the way it reads
1713            // a label.
1714            if n.kind == kinds::CANVAS
1715                && let Some(text) = n.a11y.value.clone().or_else(|| n.a11y.label.clone())
1716            {
1717                n.probe.text = text;
1718            }
1719            if let Some(h) = n.handle.clone() {
1720                self.toolkit.set_a11y(&h, &n.a11y);
1721            }
1722        }
1723    }
1724
1725    fn enable_gesture(&mut self, node: RNode, kind: day_spec::GestureKind) {
1726        let kinds = self.gestures.entry(node).or_default();
1727        if !kinds.contains(&kind) {
1728            kinds.push(kind);
1729        }
1730        // `.on_tap`/`.on_drag` often land on a layout-only wrapper (`.frame()`, `.padding()`,
1731        // `.grow(Dimension::Both)` produce one) that has no native view to carry a recognizer. Descend
1732        // through single-child layout-only nodes to the nearest native descendant and attach
1733        // there, but deliver events against the original node, where the modifier registered
1734        // its handler.
1735        let mut cur = node;
1736        for _ in 0..16 {
1737            let Some(n) = self.nodes.get(cur) else { return };
1738            if let Some(h) = n.handle.clone() {
1739                if kind == day_spec::GestureKind::Tap && n.kind == kinds::BUTTON {
1740                    log::warn!(
1741                        "tap gesture attached to native button {:?} (id: {:?}): \
1742                         use .action(...) instead of .on_tap(...) or .on_tap_at(...). \
1743                         A separate gesture recognizer can delay pressed feedback and \
1744                         bypass native keyboard, accessibility, and disabled behavior",
1745                        rnode_to_id(cur),
1746                        n.id,
1747                    );
1748                }
1749                self.toolkit.enable_gesture(&h, rnode_to_id(node), kind);
1750                return;
1751            }
1752            match n.children.as_slice() {
1753                [only] => cur = *only,
1754                _ => break,
1755            }
1756        }
1757        log::warn!(
1758            "enable_gesture({kind:?}) found no native view under the target node — \
1759             the gesture will not fire natively (attach it to a piece with a native handle)"
1760        );
1761    }
1762
1763    fn focus_node(&mut self, node: RNode, focused: bool) {
1764        // The wrapper-descent `set_focusable` makes: an id (and so a `focus:` step) often lands
1765        // on a layout-only wrapper (`.frame`, `.padding`), and focusing it did nothing at all.
1766        let mut cur = node;
1767        for _ in 0..16 {
1768            let Some(n) = self.nodes.get(cur) else { return };
1769            if let Some(h) = n.handle.clone() {
1770                self.toolkit.focus(&h, rnode_to_id(node), focused);
1771                return;
1772            }
1773            match n.children.as_slice() {
1774                [only] => cur = *only,
1775                _ => return,
1776            }
1777        }
1778    }
1779
1780    fn set_focusable(&mut self, node: RNode, focusable: bool) {
1781        // Same wrapper-descent as `enable_gesture`: `.focusable()` often lands on a
1782        // layout-only wrapper; the duty needs the nearest native view, events keep the
1783        // original node.
1784        let mut cur = node;
1785        for _ in 0..16 {
1786            let Some(n) = self.nodes.get(cur) else { return };
1787            if let Some(h) = n.handle.clone() {
1788                self.toolkit.set_focusable(&h, rnode_to_id(node), focusable);
1789                return;
1790            }
1791            match n.children.as_slice() {
1792                [only] => cur = *only,
1793                _ => break,
1794            }
1795        }
1796        log::warn!(
1797            "set_focusable found no native view under the target node — \
1798             the piece will not join the focus order"
1799        );
1800    }
1801
1802    fn set_probe_focused(&mut self, node: RNode, focused: bool) {
1803        if let Some(n) = self.nodes.get_mut(node) {
1804            n.probe.focused = focused;
1805        }
1806        // The layout-only wrappers directly above a native view are the same element: an id
1807        // (`.frame(..).id(..)`) and a modifier often sit on one, while the toolkit reports
1808        // focus on the view itself. Mirror the state up through them, the inverse of the
1809        // descent `set_focusable` and `focus_node` make.
1810        for w in self.wrappers_above(node) {
1811            if let Some(p) = self.nodes.get_mut(w) {
1812                p.probe.focused = focused;
1813            }
1814        }
1815        // And down through the single-child layout-only chain to the native view: the
1816        // toolkit reports focus against the node that enabled it (a `.focusable()` or
1817        // `.focused(..)` wrapper), while `.id` names the piece's own node below it
1818        // (docs/api-style.md "Modifier classes"), which is what a dayscript `assert_focused`
1819        // resolves. Both are the same element.
1820        let mut cur = node;
1821        for _ in 0..16 {
1822            let Some(n) = self.nodes.get(cur) else { break };
1823            if n.handle.is_some() && cur != node {
1824                if let Some(p) = self.nodes.get_mut(cur) {
1825                    p.probe.focused = focused;
1826                }
1827                break;
1828            }
1829            let next = match n.children.as_slice() {
1830                [only] => *only,
1831                _ => break,
1832            };
1833            if let Some(p) = self.nodes.get_mut(next) {
1834                p.probe.focused = focused;
1835            }
1836            cur = next;
1837        }
1838        // Remember which node has it, beyond the per-node flag: keys follow focus
1839        // (docs/menus.md), so dayscript's `key:` step needs the same answer the platform gives.
1840        // A loss only clears the record if this node is still the one holding it; gains land
1841        // before losses in the pump, so a hand-off has already named the new owner.
1842        FOCUSED.with(|f| match focused {
1843            true => f.set(Some(node)),
1844            false if f.get() == Some(node) => f.set(None),
1845            false => {}
1846        });
1847    }
1848
1849    fn set_probe_selected(&mut self, node: RNode, selected: Option<usize>) {
1850        if let Some(n) = self.nodes.get_mut(node) {
1851            // Both fields, as a picker does: `assert_value` reads `value` for a number and
1852            // `assert_selected` reads `selected`, and a nav host answers either.
1853            n.probe.selected = selected.map_or(-1, |i| i as i64);
1854            n.probe.value = n.probe.selected as f64;
1855        }
1856    }
1857
1858    fn set_probe_value(&mut self, node: RNode, value: f64, text: String) {
1859        if let Some(n) = self.nodes.get_mut(node) {
1860            n.probe.value = value;
1861            n.probe.text = text;
1862        }
1863    }
1864
1865    fn set_app_menu(&mut self, items: Vec<day_spec::MenuItem>) {
1866        collect_menu_families(&items, &mut self.mounted_id_families);
1867        self.toolkit.set_app_menu(&items);
1868    }
1869
1870    fn edit_window_toolbar(&mut self, root: RNode, ops: Vec<day_spec::ToolbarOp>) -> bool {
1871        let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) else {
1872            return false;
1873        };
1874        for op in &ops {
1875            if let day_spec::ToolbarOp::Insert { item, .. } = op {
1876                self.mounted_id_families
1877                    .insert(crate::element_id::family_of(&item.id).to_owned());
1878            }
1879        }
1880        self.toolkit.edit_toolbar(&h, &ops)
1881    }
1882
1883    fn patch_window_toolbar(&mut self, root: RNode, patch: day_spec::ToolbarPatch) -> bool {
1884        let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) else {
1885            return false;
1886        };
1887        self.toolkit.update_toolbar(&h, &patch);
1888        true
1889    }
1890
1891    fn set_context_menu(&mut self, node: RNode, items: Vec<day_spec::MenuItem>) {
1892        // The modifier often sits on a handle-less layout wrapper (`.padding`/`.frame` build
1893        // those): the native affordance needs a real view, so fall through to the first
1894        // native root under the node. Silently dropping the menu here is what made
1895        // `label(..).padding(..).context_menu(..)` dead on every backend.
1896        let target = if self.nodes.get(node).is_some_and(|n| n.handle.is_some()) {
1897            Some(node)
1898        } else {
1899            let mut roots = Vec::new();
1900            self.native_descendants(node, &mut roots);
1901            roots.first().copied()
1902        };
1903        let Some(t) = target else {
1904            log::warn!("context_menu on a subtree with no native view — menu dropped");
1905            return;
1906        };
1907        collect_menu_families(&items, &mut self.mounted_id_families);
1908        let model = ContextMenuModel::Items(items.clone());
1909        self.context_menus.insert(node, model.clone());
1910        self.context_menus.insert(t, model);
1911        if let Some(h) = self.nodes.get(t).and_then(|n| n.handle.clone()) {
1912            self.toolkit.set_context_menu(&h, rnode_to_id(t), &items);
1913        }
1914    }
1915
1916    fn scroll_to_target(&mut self, node: RNode, target: &ScrollTarget, animated: bool) -> bool {
1917        // `Id` routes through reveal: the element names the scroll implicitly.
1918        if let ScrollTarget::Id(id) = target {
1919            let Some(el) = self.find_by_id(id) else {
1920                return false;
1921            };
1922            return self.scroll_reveal(el, animated);
1923        }
1924        let Some(n) = self.nodes.get(node) else {
1925            return false;
1926        };
1927        if n.kind == kinds::NAV_MENU {
1928            return match (n.handle.clone(), target) {
1929                (Some(h), ScrollTarget::Top | ScrollTarget::Bottom) => self
1930                    .toolkit
1931                    .nav_scroll_to_edge(&h, matches!(target, ScrollTarget::Bottom)),
1932                _ => false,
1933            };
1934        }
1935        if n.kind != kinds::SCROLL {
1936            return false;
1937        }
1938        let Some(h) = n.handle.clone() else {
1939            return false;
1940        };
1941        let viewport = n.last_native_frame.map_or(Size::ZERO, |f| f.size);
1942        let content = n.scroll_content.unwrap_or(viewport);
1943        // Compose a content-space rect whose minimal reveal lands on the target
1944        // (`Toolkit::scroll_to` is scrollRectToVisible semantics on every backend).
1945        let rect = match target {
1946            ScrollTarget::Top | ScrollTarget::Leading => Rect::new(0.0, 0.0, 1.0, 1.0),
1947            ScrollTarget::Bottom => Rect::new(0.0, (content.height - 1.0).max(0.0), 1.0, 1.0),
1948            ScrollTarget::Trailing => Rect::new((content.width - 1.0).max(0.0), 0.0, 1.0, 1.0),
1949            // A viewport-sized rect: minimal reveal pins the viewport origin to the point
1950            // (exactly, when the point is within the scrollable range).
1951            ScrollTarget::Offset(p) => Rect::new(p.x, p.y, viewport.width, viewport.height),
1952            ScrollTarget::Id(_) => unreachable!("routed to scroll_reveal above"),
1953        };
1954        self.toolkit
1955            .scroll_to(&h, rect, animated && !crate::reduce_motion_now());
1956        true
1957    }
1958
1959    fn scroll_reveal(&mut self, node: RNode, animated: bool) -> bool {
1960        // The element's frame is relative to its nearest REALIZED native ancestor (§7);
1961        // accumulate native origins up to (not including) the enclosing scroll, which puts
1962        // the rect in the scroll's content space, which is what Toolkit::scroll_to expects.
1963        let Some(mut rect) = self.nodes.get(node).and_then(|n| n.last_native_frame) else {
1964            return false;
1965        };
1966        let mut anc = match self.nodes.get(node) {
1967            Some(n) => n.parent,
1968            None => return false,
1969        };
1970        loop {
1971            let Some(a) = self.nodes.get(anc) else {
1972                return false; // walked off the root: no scroll ancestor
1973            };
1974            if a.kind == kinds::SCROLL {
1975                let Some(h) = a.handle.clone() else {
1976                    return false;
1977                };
1978                self.toolkit
1979                    .scroll_to(&h, rect, animated && !crate::reduce_motion_now());
1980                return true;
1981            }
1982            if a.handle.is_some()
1983                && let Some(f) = a.last_native_frame
1984            {
1985                rect.origin.x += f.origin.x;
1986                rect.origin.y += f.origin.y;
1987            }
1988            anc = a.parent;
1989        }
1990    }
1991
1992    fn patch(&mut self, node: RNode, patch: Box<dyn Any>, affects_size: bool) {
1993        {
1994            use day_spec::props::*;
1995            if let Some(n) = self.nodes.get_mut(node) {
1996                if let Some(p) = patch.downcast_ref::<LabelPatch>() {
1997                    // Both text-carrying variants: a `.markdown()` label re-parses through
1998                    // `Runs`, and a probe that only tracked `Text` would report the string the
1999                    // label was born with forever (docs/text-runs.md).
2000                    match p {
2001                        LabelPatch::Text(t) | LabelPatch::Runs(t, _) => {
2002                            n.probe.text.clone_from(t);
2003                        }
2004                        LabelPatch::Font(font) => n.probe.font = Some(*font),
2005                        LabelPatch::Color(_) => {}
2006                    }
2007                } else if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
2008                    match p {
2009                        ButtonPatch::Title(t) => n.probe.text.clone_from(t),
2010                        ButtonPatch::Content(c) => n.probe.text.clone_from(&c.title),
2011                        ButtonPatch::Enabled(e) => n.probe.enabled = *e,
2012                        ButtonPatch::Selected(on) => n.probe.flag = *on,
2013                        // The style is a look, not something a probe asserts on.
2014                        ButtonPatch::Style(_) => {}
2015                    }
2016                } else if let Some(p) = patch.downcast_ref::<TogglePatch>() {
2017                    match p {
2018                        TogglePatch::On(v) => n.probe.flag = *v,
2019                        TogglePatch::Enabled(e) => n.probe.enabled = *e,
2020                    }
2021                } else if let Some(p) = patch.downcast_ref::<SliderPatch>() {
2022                    match p {
2023                        SliderPatch::Value(v) => n.probe.value = *v,
2024                        SliderPatch::Enabled(e) => n.probe.enabled = *e,
2025                    }
2026                } else if let Some(p) = patch.downcast_ref::<PickerPatch>() {
2027                    match p {
2028                        PickerPatch::Selected(i) => {
2029                            n.probe.selected = *i as i64;
2030                            n.probe.value = *i as f64;
2031                        }
2032                        PickerPatch::Options(opts) => n.probe.options.clone_from(opts),
2033                        PickerPatch::Enabled(e) => n.probe.enabled = *e,
2034                    }
2035                    let i = n.probe.selected.max(0) as usize;
2036                    n.probe.text = n.probe.options.get(i).cloned().unwrap_or_default();
2037                } else if let Some(TextAreaPatch::SetText(t)) =
2038                    patch.downcast_ref::<TextAreaPatch>()
2039                {
2040                    n.probe.text.clone_from(t);
2041                } else if let Some(ProgressPatch::Value(v)) = patch.downcast_ref::<ProgressPatch>()
2042                {
2043                    n.probe.flag = v.is_none();
2044                    n.probe.value = v.unwrap_or(0.0);
2045                } else if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
2046                    match p {
2047                        TextFieldPatch::Text { text, .. } => n.probe.text.clone_from(text),
2048                        TextFieldPatch::Enabled(e) => n.probe.enabled = *e,
2049                        _ => {}
2050                    }
2051                } else if let Some(NavMenuPatch::Selected(sel)) =
2052                    patch.downcast_ref::<NavMenuPatch>()
2053                {
2054                    n.probe.selected = sel.map_or(-1, |i| i as i64);
2055                    n.probe.value = n.probe.selected as f64;
2056                }
2057            }
2058        }
2059        let Some(n) = self.nodes.get(node) else {
2060            return;
2061        };
2062        let kind = n.kind;
2063        if let Some(h) = n.handle.clone() {
2064            let anim = self.resolve_anim(node);
2065            self.toolkit.update(&h, kind, patch.as_ref(), anim.as_ref());
2066        }
2067        if affects_size {
2068            self.mark_needs_measure_impl(node);
2069        }
2070    }
2071
2072    fn set_implicit_anim(&mut self, node: RNode, anim: Option<day_spec::AnimSpec>) {
2073        let had = self
2074            .nodes
2075            .get(node)
2076            .is_some_and(|n| n.implicit_anim.is_some());
2077        if let Some(n) = self.nodes.get_mut(node) {
2078            n.implicit_anim = anim;
2079        } else {
2080            return;
2081        }
2082        match (had, anim.is_some()) {
2083            (false, true) => self.implicit_anim_count += 1,
2084            (true, false) => self.implicit_anim_count = self.implicit_anim_count.saturating_sub(1),
2085            _ => {}
2086        }
2087    }
2088
2089    fn set_node_opacity(&mut self, node: RNode, opacity: f64) {
2090        let Some(h) = self.nodes.get(node).and_then(|n| n.handle.clone()) else {
2091            return;
2092        };
2093        let anim = self.resolve_anim(node);
2094        self.toolkit.set_opacity(&h, opacity, anim.as_ref());
2095    }
2096
2097    fn set_node_transform(&mut self, node: RNode, t: day_spec::Transform) {
2098        let Some(n) = self.nodes.get(node) else {
2099            return;
2100        };
2101        let Some(h) = n.handle.clone() else {
2102            return;
2103        };
2104        // The node's laid-out size, passed so backends resolve the transform's anchor to a pixel
2105        // pivot without querying the (possibly not-yet-allocated) native widget (§8.4).
2106        let size = n.last_native_frame.map_or(Size::ZERO, |f| f.size);
2107        let anim = self.resolve_anim(node);
2108        self.toolkit.set_transform(&h, t, size, anim.as_ref());
2109    }
2110
2111    fn set_node_selectable(&mut self, node: RNode, selectable: bool) {
2112        let Some(h) = self.nodes.get(node).and_then(|n| n.handle.clone()) else {
2113            return;
2114        };
2115        // A toolkit may have to rebuild the widget as a selection-capable class (UIKit's
2116        // label → read-only text view); adopt the replacement so patches and layout follow it.
2117        if let Some(new) = self.toolkit.set_selectable(&h, selectable)
2118            && let Some(n) = self.nodes.get_mut(node)
2119        {
2120            if n.tweaked {
2121                log::warn!(
2122                    "`.selectable()` rebuilt this widget as a different native class, \
2123                     discarding an earlier tweak's changes — apply `.selectable()` BEFORE the \
2124                     tweak so it runs against the widget that ships (docs/tweaks.md)."
2125                );
2126            }
2127            n.handle = Some(new);
2128        }
2129    }
2130
2131    fn set_node_input_traits(&mut self, node: RNode, traits: &day_spec::InputTraits) {
2132        let Some(h) = self.nodes.get(node).and_then(|n| n.handle.clone()) else {
2133            return;
2134        };
2135        // A toolkit whose secure field is its own class rebuilds the widget (AppKit, WinUI);
2136        // adopt the replacement so patches, layout and focus follow it.
2137        if let Some(new) = self.toolkit.set_input_traits(&h, traits)
2138            && let Some(n) = self.nodes.get_mut(node)
2139        {
2140            if n.tweaked {
2141                log::warn!(
2142                    "a text field's `.secure()` rebuilt this widget as a different native \
2143                     class, discarding an earlier tweak's changes (docs/tweaks.md)."
2144                );
2145            }
2146            n.handle = Some(new);
2147            n.last_native_frame = None;
2148            self.mark_needs_measure_impl(node);
2149        }
2150    }
2151
2152    fn set_node_cursor(&mut self, node: RNode, cursor: day_spec::Cursor) {
2153        // The wrapper descent `enable_gesture` makes: `.padding(…).cursor(…)` lands on a
2154        // layout-only wrapper with no view of its own, and the cursor belongs on the view it
2155        // wraps.
2156        let Some(h) = self
2157            .native_view_of(node)
2158            .and_then(|n| self.nodes.get(n))
2159            .and_then(|n| n.handle.clone())
2160        else {
2161            return;
2162        };
2163        self.toolkit.set_cursor(&h, cursor);
2164    }
2165
2166    fn set_node_drag_region(&mut self, node: RNode, drag: bool) {
2167        // Same descent: `row(…).padding(8.0).window_drag_region()` marks the row.
2168        let Some(h) = self
2169            .native_view_of(node)
2170            .and_then(|n| self.nodes.get(n))
2171            .and_then(|n| n.handle.clone())
2172        else {
2173            log::warn!(
2174                "window_drag_region found no native view under the target node; give the \
2175                 region a piece with a native view (a background, a row)"
2176            );
2177            return;
2178        };
2179        self.toolkit.set_drag_region(&h, drag);
2180    }
2181
2182    fn note_node_tweaked(&mut self, node: RNode) {
2183        if let Some(n) = self.nodes.get_mut(node) {
2184            n.tweaked = true;
2185        }
2186    }
2187
2188    fn request_frame(&mut self, root: RNode, cb: day_spec::FrameCallback) -> day_spec::CancelFrame {
2189        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
2190            self.toolkit.request_frame(&h, cb)
2191        } else {
2192            Box::new(|| {})
2193        }
2194    }
2195
2196    fn replay(&mut self, node: RNode, ops: Vec<DrawOp>) {
2197        let Some(n) = self.nodes.get(node) else {
2198            return;
2199        };
2200        let size = n.last_native_frame.map_or(Size::ZERO, |f| f.size);
2201        if let Some(h) = n.handle.clone() {
2202            self.toolkit.replay(&h, &ops, size);
2203        }
2204    }
2205
2206    fn mark_needs_measure(&mut self, node: RNode) {
2207        self.mark_needs_measure_impl(node);
2208    }
2209
2210    fn mark_layout_dirty(&mut self) {
2211        self.layout_dirty = true;
2212    }
2213
2214    fn invalidate_all_measurements(&mut self) {
2215        for (_, n) in &mut self.nodes {
2216            n.needs_measure = true;
2217            n.needs_layout = true;
2218            n.cache.clear();
2219        }
2220        // Cells keep a row's measurements while its width holds; forgetting the width makes the
2221        // dirty-cell sweep measure each bound row afresh, and a self-sizing row whose height
2222        // changes reports it (`ListPatch::RowSizeInvalidated`).
2223        for state in self.lists.values_mut() {
2224            for cell in state.cells.values_mut() {
2225                cell.laid_width = None;
2226            }
2227        }
2228        for state in self.trees.values_mut() {
2229            for cell in state.cells.values_mut() {
2230                cell.laid_width = None;
2231            }
2232        }
2233        self.layout_dirty = true;
2234    }
2235
2236    fn layout_if_needed(&mut self) {
2237        if !self.layout_dirty {
2238            return;
2239        }
2240        self.layout_dirty = false;
2241        self.layout_now();
2242    }
2243
2244    fn set_route(&mut self, route: &str) {
2245        self.toolkit.set_route(route);
2246    }
2247
2248    fn set_window_size(&mut self, s: Size) {
2249        // The primary window (`WINDOW_NODE` routing); secondary windows resize through
2250        // `set_root_size` with their own root.
2251        if s != self.windows[0].size {
2252            self.windows[0].size = s;
2253            let root = self.windows[0].root;
2254            self.mark_needs_measure_impl(root);
2255        }
2256    }
2257
2258    fn child_count(&self, node: RNode) -> usize {
2259        self.nodes.get(node).map_or(0, |n| n.children.len())
2260    }
2261
2262    fn first_child(&self, node: RNode) -> Option<RNode> {
2263        self.nodes
2264            .get(node)
2265            .and_then(|n| n.children.first().copied())
2266    }
2267
2268    fn parent_of(&self, node: RNode) -> Option<RNode> {
2269        self.nodes
2270            .get(node)
2271            .map(|n| n.parent)
2272            .filter(|p| !p.is_null() && *p != node)
2273    }
2274
2275    fn node_kind(&self, node: RNode) -> Option<PieceKind> {
2276        self.nodes.get(node).map(|n| n.kind)
2277    }
2278
2279    fn node_id(&self, node: RNode) -> Option<String> {
2280        self.nodes.get(node).and_then(|n| n.id.clone())
2281    }
2282
2283    fn node_handle_any(&self, node: RNode) -> Option<Box<dyn Any>> {
2284        self.nodes
2285            .get(node)
2286            .and_then(|n| n.handle.clone())
2287            .map(|h| Box::new(h) as Box<dyn Any>)
2288    }
2289
2290    fn node_frame(&self, node: RNode) -> Option<Rect> {
2291        self.nodes.get(node).and_then(|n| n.last_native_frame)
2292    }
2293
2294    fn node_probe(&self, node: RNode) -> Option<NodeProbe> {
2295        self.nodes.get(node).map(|n| n.probe.clone())
2296    }
2297
2298    fn node_a11y(&self, node: RNode) -> Option<A11yProps> {
2299        self.nodes.get(node).map(|n| n.a11y.clone())
2300    }
2301
2302    fn read_native(&self, node: RNode) -> Option<day_spec::NativeSnapshot> {
2303        let n = self.nodes.get(node)?;
2304        let h = n.handle.as_ref()?;
2305        Some(self.toolkit.read_native(h))
2306    }
2307
2308    fn a11y_nodes(&self) -> Vec<(String, PieceKind, A11yProps, day_spec::NativeSnapshot)> {
2309        self.nodes
2310            .values()
2311            .filter_map(|n| {
2312                let id = n.id.clone()?;
2313                let h = n.handle.as_ref()?;
2314                Some((id, n.kind, n.a11y.clone(), self.toolkit.read_native(h)))
2315            })
2316            .collect()
2317    }
2318
2319    fn find_by_id(&self, id: &str) -> Option<RNode> {
2320        // A settings page can exist both in the app sidebar and in its focused window/cover.
2321        // Slot order can otherwise mix fields from one form with the Save button of another.
2322        let focused = crate::windows::focused_window().map_or_else(
2323            || self.root(),
2324            |w| id_to_rnode(crate::windows::window_node_id(&w)),
2325        );
2326        let mut fallback = None;
2327        for (key, node) in &self.nodes {
2328            if node.id.as_deref() != Some(id) {
2329                continue;
2330            }
2331            fallback.get_or_insert(key);
2332            let mut ancestor = key;
2333            while let Some(node) = self.nodes.get(ancestor) {
2334                // Covers are children of the primary root but own a separate layout root.
2335                // Stop at the nearest root so a closing cover cannot masquerade as primary.
2336                if self.windows.iter().any(|w| w.root == ancestor) {
2337                    if ancestor == focused {
2338                        return Some(key);
2339                    }
2340                    break;
2341                }
2342                ancestor = if node.kind == kinds::LIST_CELL && node.parent.is_null() {
2343                    // Recycling-list/tree cells are independent layout anchors, not children
2344                    // in the owner's layout. Follow their logical owner for window lookup.
2345                    self.lists
2346                        .iter()
2347                        .find_map(|(&owner, state)| {
2348                            state
2349                                .cells
2350                                .values()
2351                                .any(|c| c.anchor == ancestor)
2352                                .then_some(owner)
2353                        })
2354                        .or_else(|| {
2355                            self.trees.iter().find_map(|(&owner, state)| {
2356                                state
2357                                    .cells
2358                                    .values()
2359                                    .any(|c| c.anchor == ancestor)
2360                                    .then_some(owner)
2361                            })
2362                        })
2363                        .unwrap_or(node.parent)
2364                } else {
2365                    node.parent
2366                };
2367            }
2368        }
2369        fallback
2370    }
2371
2372    fn toggle_sidebar(&mut self, host: RNode) -> bool {
2373        let Some(h) = self.nodes.get(host).and_then(|n| n.handle.as_ref()) else {
2374            return false;
2375        };
2376        self.toolkit.toggle_sidebar(h)
2377    }
2378
2379    fn native_back(&mut self) -> bool {
2380        self.toolkit.native_back()
2381    }
2382
2383    fn set_system_back(&mut self, armed: bool) {
2384        self.toolkit.set_system_back(armed);
2385    }
2386
2387    fn prepare_snapshot(
2388        &mut self,
2389        root: Option<RNode>,
2390        revision: u32,
2391    ) -> Result<day_spec::capture::Readiness, String> {
2392        let host = match root {
2393            Some(root) if self.windows[0].root != root => Some(
2394                self.nodes
2395                    .get(root)
2396                    .and_then(|n| n.handle.clone())
2397                    .ok_or("window is gone")?,
2398            ),
2399            _ => None,
2400        };
2401        self.toolkit.prepare_snapshot(host.as_ref(), revision)
2402    }
2403
2404    fn snapshot(&mut self) -> Result<Vec<u8>, String> {
2405        self.toolkit.snapshot_window()
2406    }
2407
2408    fn snapshot_origin(&mut self) -> Option<Point> {
2409        let root = self.windows[0].root;
2410        let h = self.nodes.get(root).and_then(|n| n.handle.clone())?;
2411        self.toolkit.snapshot_origin(&h)
2412    }
2413
2414    fn snapshot_chrome(&mut self) -> Result<Vec<u8>, String> {
2415        self.toolkit.snapshot_window_chrome()
2416    }
2417
2418    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
2419        self.toolkit.decode_image(req, id, bytes);
2420    }
2421
2422    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
2423        self.toolkit.image_info(id)
2424    }
2425
2426    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
2427        self.toolkit.image_properties(id)
2428    }
2429
2430    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
2431        self.toolkit.encode_image(req, id, spec);
2432    }
2433
2434    fn image_encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
2435        self.toolkit.encode_formats()
2436    }
2437
2438    fn release_image(&mut self, id: day_spec::BitmapId) {
2439        self.toolkit.release_image(id);
2440    }
2441
2442    fn render_bitmap(
2443        &mut self,
2444        req: u64,
2445        id: day_spec::BitmapId,
2446        ops: &[day_spec::DrawOp],
2447        size: Size,
2448        scale: f64,
2449    ) {
2450        self.toolkit.render_bitmap(req, id, ops, size, scale);
2451    }
2452
2453    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
2454        self.toolkit.render_pdf(req, pages, info);
2455    }
2456
2457    fn window_image_support(&mut self) -> day_spec::Support {
2458        self.toolkit.capability(day_spec::Cap::Snapshot)
2459    }
2460
2461    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
2462        self.toolkit.font_families()
2463    }
2464
2465    fn measure_text(
2466        &mut self,
2467        text: &str,
2468        size: f64,
2469        font: &day_spec::CanvasFont,
2470    ) -> Option<day_spec::TextMetrics> {
2471        self.toolkit.measure_text(text, size, font)
2472    }
2473
2474    fn ui_idle(&mut self) -> bool {
2475        self.toolkit.ui_idle()
2476    }
2477
2478    fn root_node(&self) -> RNode {
2479        self.windows[0].root
2480    }
2481
2482    fn open_window_root(&mut self, options: &WindowOptions, kind: WindowKind) -> WindowRootReply {
2483        // The same "wrap an externally-owned handle" record as the primary root and the
2484        // list cell anchors; the handle arrives now (desktop) or at adoption (mobile).
2485        let root = self.nodes.insert(NodeData {
2486            kind: kinds::CONTAINER,
2487            handle: None,
2488            parent: RNode::null(),
2489            children: Vec::new(),
2490            layout: Rc::new(PassThrough),
2491            flex: Flex::default(),
2492            scope: Scope::root(),
2493            id: None,
2494            parked_id: None,
2495            a11y: A11yProps::default(),
2496            cache: Vec::new(),
2497            baseline_cache: None,
2498            probe: NodeProbe::default(),
2499            needs_measure: true,
2500            needs_layout: true,
2501            last_native_frame: None,
2502            scroll_content: None,
2503            implicit_anim: None,
2504            tweaked: false,
2505            is_boundary: true,
2506        });
2507        match self.toolkit.open_window(rnode_to_id(root), options, kind) {
2508            day_spec::WindowOpenReply::Open(h) => {
2509                self.nodes[root].handle = Some(h);
2510                self.windows.push(WindowEntry {
2511                    root,
2512                    size: options.size,
2513                });
2514                self.layout_dirty = true;
2515                WindowRootReply::Open(root)
2516            }
2517            day_spec::WindowOpenReply::Pending => WindowRootReply::Pending(root),
2518            day_spec::WindowOpenReply::Unsupported => {
2519                self.nodes.remove(root);
2520                WindowRootReply::Unsupported
2521            }
2522        }
2523    }
2524
2525    fn adopt_window_root(&mut self, root: RNode, raw: day_spec::RawHandle, size: Size) -> bool {
2526        let Some(node) = self.nodes.get_mut(root) else {
2527            return false; // closed before the native side finished; the caller drops the window
2528        };
2529        let handle = self.toolkit.adopt(raw);
2530        node.handle = Some(handle);
2531        node.needs_measure = true;
2532        self.windows.push(WindowEntry { root, size });
2533        self.layout_dirty = true;
2534        true
2535    }
2536
2537    fn remove_window_root(&mut self, root: RNode) {
2538        // Any window may go, including the first one opened (docs/windows.md close policy);
2539        // the app's life is the life of its primary windows, not of `windows[0]` specifically.
2540        //
2541        // The last entry is kept, because `root()` has to answer for the whole tree and callers
2542        // are in no position to handle "no windows". Reaching that point means the last window
2543        // has closed, which is the app exiting: its content is already gone (teardown removes
2544        // the children first) and the empty shell outlives nothing.
2545        if self.windows.len() <= 1 {
2546            self.collect_and_release(root);
2547            self.layout_dirty = true;
2548            return;
2549        }
2550        self.windows.retain(|w| w.root != root);
2551        // No native detach: a window root has no native parent; the platform window is
2552        // already closed (or the backend releases it with the content handle).
2553        self.collect_and_release(root);
2554        self.layout_dirty = true;
2555    }
2556
2557    fn set_root_size(&mut self, root: RNode, s: Size) {
2558        if let Some(w) = self.windows.iter_mut().find(|w| w.root == root)
2559            && w.size != s
2560        {
2561            w.size = s;
2562            self.mark_needs_measure_impl(root);
2563        }
2564    }
2565
2566    fn fit_window(&mut self, root: RNode, size: Size) {
2567        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
2568            self.toolkit.fit_window(&h, size);
2569        }
2570        self.set_root_size(root, size);
2571    }
2572
2573    fn add_extra_layout_root(&mut self, node: RNode, size: Size) {
2574        if !self.windows.iter().any(|w| w.root == node) {
2575            self.windows.push(WindowEntry { root: node, size });
2576            self.layout_dirty = true;
2577        }
2578    }
2579
2580    fn drop_extra_layout_root(&mut self, node: RNode) {
2581        debug_assert!(
2582            self.windows.first().map(|w| w.root) != Some(node),
2583            "drop_extra_layout_root called with the primary root"
2584        );
2585        self.windows.retain(|w| w.root != node);
2586    }
2587
2588    fn close_native_window(&mut self, root: RNode) {
2589        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
2590            self.toolkit.close_window(&h);
2591        }
2592    }
2593
2594    fn quit_app(&mut self) {
2595        self.toolkit.quit_app();
2596    }
2597
2598    fn focus_native_window(&mut self, root: RNode) {
2599        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
2600            self.toolkit.focus_window(&h);
2601        }
2602    }
2603
2604    fn set_native_window_title(&mut self, root: RNode, title: &str) {
2605        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
2606            self.toolkit.set_window_title(&h, title);
2607        }
2608    }
2609
2610    fn apply_window(&mut self, root: RNode, change: &day_spec::WindowChange) {
2611        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
2612            self.toolkit.apply_window(&h, change);
2613        }
2614    }
2615
2616    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
2617        self.toolkit.set_dock_menu(items);
2618    }
2619
2620    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
2621        self.toolkit.set_status_items(items);
2622    }
2623
2624    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
2625        self.toolkit.set_app_progress(progress);
2626    }
2627
2628    fn set_dock_visible(&mut self, visible: bool) {
2629        self.toolkit.set_dock_visible(visible);
2630    }
2631
2632    fn set_keep_running(&mut self, keep: bool) {
2633        self.toolkit.set_keep_running(keep);
2634    }
2635
2636    fn native_window_frame(&self, root: RNode) -> Option<day_spec::Rect> {
2637        let h = self.nodes.get(root).and_then(|n| n.handle.clone())?;
2638        self.toolkit.window_frame(&h)
2639    }
2640
2641    fn monitors(&self) -> Vec<day_spec::Monitor> {
2642        self.toolkit.monitors()
2643    }
2644
2645    fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]) {
2646        self.toolkit.set_launcher_shortcuts(shortcuts);
2647    }
2648
2649    fn snapshot_of(&mut self, root: RNode) -> Result<Vec<u8>, String> {
2650        if self.windows[0].root == root {
2651            return self.toolkit.snapshot_window();
2652        }
2653        match self.nodes.get(root).and_then(|n| n.handle.clone()) {
2654            Some(h) => self.toolkit.snapshot_window_of(&h),
2655            None => Err("window is gone".into()),
2656        }
2657    }
2658
2659    fn install_list(&mut self, node: RNode, driver: crate::list::ListDriver) {
2660        let driver = Rc::new(driver);
2661        let sections = driver
2662            .sections
2663            .is_some()
2664            .then(|| crate::list::register_sections(node, driver.clone()));
2665        self.lists.insert(
2666            node,
2667            crate::list::ListState {
2668                driver: driver.clone(),
2669                cells: HashMap::new(),
2670                sections: sections.clone(),
2671            },
2672        );
2673        let source = crate::list::make_source(node, &driver, sections.as_ref());
2674        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
2675            self.toolkit.attach_list(&handle, source);
2676        }
2677    }
2678
2679    fn list_prepare_cell(
2680        &mut self,
2681        node: RNode,
2682        key: usize,
2683        cell: RawHandle,
2684        header: bool,
2685    ) -> crate::list::CellStep {
2686        // A cell that held the other kind (a header's cell reused for an item, or the reverse)
2687        // cannot be rebound: its subtree is the wrong piece. Dispose it as a release would and
2688        // build afresh in the same native cell.
2689        if let Some(state) = self.lists.get_mut(&node)
2690            && state.cells.get(&key).is_some_and(|b| b.header != header)
2691            && let Some(old) = state.cells.remove(&key)
2692        {
2693            old.scope.dispose();
2694            self.remove_subtree_impl(old.anchor);
2695        }
2696        if let Some(state) = self.lists.get_mut(&node)
2697            && let Some(bound) = state.cells.get_mut(&key)
2698        {
2699            bound.active = true;
2700            let (rebind, anchor, pinned) = (bound.rebind.clone(), bound.anchor, bound.pinned);
2701            // A pooled cell coming back: its ids were parked when it was recycled, and a
2702            // rebind to unchanged content would never re-set them (see `parked_id`). A pinned
2703            // header copy keeps its ids parked.
2704            if !pinned {
2705                self.restore_subtree_ids(anchor);
2706            }
2707            return crate::list::CellStep::Rebind { rebind, anchor };
2708        }
2709        // First use of this cell: adopt the native cell and anchor a fresh subtree under it,
2710        // inside the platform's row margins (docs/list.md "Row metrics").
2711        let mut metrics = match self.nodes.get(node).and_then(|n| n.handle.clone()) {
2712            Some(list) => self.toolkit.list_row_metrics(&list),
2713            None => day_spec::RowMetrics::default(),
2714        };
2715        // A section header lines up with the rows (the side insets) but is no row: its own
2716        // padding sets its height, and the platform's least row height is a touch target's,
2717        // which a header is not.
2718        if header {
2719            metrics.insets.top = 0.0;
2720            metrics.insets.bottom = 0.0;
2721            metrics.min_height = 0.0;
2722        }
2723        let handle = self.toolkit.adopt(cell);
2724        let anchor = self.create_cell_anchor(
2725            handle,
2726            Scope::child(),
2727            Rc::new(crate::layout::CellMetrics(metrics)),
2728        );
2729        crate::list::CellStep::Build { anchor }
2730    }
2731
2732    fn list_store_cell(
2733        &mut self,
2734        node: RNode,
2735        key: usize,
2736        anchor: RNode,
2737        built: crate::list::BuiltRow,
2738        header: bool,
2739    ) {
2740        if let Some(state) = self.lists.get_mut(&node) {
2741            state.cells.insert(
2742                key,
2743                crate::list::BoundCell {
2744                    anchor,
2745                    active: true,
2746                    scope: built.scope,
2747                    rebind: built.rebind,
2748                    native_width: None,
2749                    laid_width: None,
2750                    laid_height: None,
2751                    header,
2752                    pinned: false,
2753                },
2754            );
2755        }
2756    }
2757
2758    fn list_layout_cell(&mut self, node: RNode, key: usize) {
2759        // The width the backend last granted this cell, once it has said so (GtkListView's themed
2760        // `row` node pads the cell, so it is narrower than the list); until then the list's own
2761        // content width, which is right wherever the cell IS the row. Every path that re-lays a
2762        // row (a rebind, the dirty-cell sweep, a data change) comes through here, so a width
2763        // the backend corrected once stays corrected.
2764        let native = self
2765            .lists
2766            .get(&node)
2767            .and_then(|s| s.cells.get(&key))
2768            .and_then(|c| c.native_width);
2769        let width = native.unwrap_or_else(|| {
2770            self.nodes
2771                .get(node)
2772                .and_then(|n| n.last_native_frame)
2773                .map_or(self.windows[0].size.width, |f| f.size.width)
2774        });
2775        self.layout_list_cell_at(node, key, width);
2776    }
2777
2778    fn list_layout_cell_width(&mut self, node: RNode, key: usize, width: f64) {
2779        // The backend's word on the cell's width (`ListSource::layout_cell`), remembered so the
2780        // next first-approximation pass does not undo it.
2781        if let Some(cell) = self
2782            .lists
2783            .get_mut(&node)
2784            .and_then(|s| s.cells.get_mut(&key))
2785        {
2786            cell.native_width = Some(width);
2787        }
2788        self.layout_list_cell_at(node, key, width);
2789    }
2790
2791    fn list_cell_height(&self, node: RNode, key: usize) -> f64 {
2792        self.lists
2793            .get(&node)
2794            .and_then(|s| s.cells.get(&key))
2795            .filter(|b| b.active)
2796            .and_then(|b| b.laid_height)
2797            .unwrap_or(0.0)
2798    }
2799
2800    fn list_cell_keys(&self, node: RNode) -> Vec<usize> {
2801        self.lists.get(&node).map_or_default(|s| {
2802            s.cells
2803                .iter()
2804                .filter_map(|(key, cell)| cell.active.then_some(*key))
2805                .collect()
2806        })
2807    }
2808
2809    fn list_reload(&mut self, node: RNode) {
2810        if let Some(map) = self.lists.get(&node).and_then(|s| s.sections.as_ref()) {
2811            map.invalidate();
2812        }
2813        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
2814            self.toolkit.update(
2815                &handle,
2816                kinds::LIST,
2817                &day_spec::props::ListPatch::Reload as &dyn Any,
2818                None,
2819            );
2820        }
2821    }
2822
2823    fn list_splice(&mut self, node: RNode, deltas: Vec<day_spec::props::RowDelta>) {
2824        // A sectioned list's deltas name items, and the headers around them move too: the
2825        // host re-queries instead (docs/list.md "Sections").
2826        if self.lists.get(&node).is_some_and(|s| s.sections.is_some()) {
2827            self.list_reload(node);
2828            return;
2829        }
2830        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
2831            self.toolkit.update(
2832                &handle,
2833                kinds::LIST,
2834                &day_spec::props::ListPatch::Splice(deltas) as &dyn Any,
2835                None,
2836            );
2837        }
2838    }
2839
2840    fn set_undo_state(&mut self, state: &day_spec::UndoState) {
2841        self.toolkit.set_undo_state(state);
2842    }
2843
2844    fn set_edit_state(&mut self, state: &day_spec::EditState) {
2845        self.toolkit.set_edit_state(state);
2846    }
2847
2848    fn modifiers(&mut self) -> day_spec::Modifiers {
2849        self.toolkit.modifiers()
2850    }
2851
2852    fn list_scroll_to_end(&mut self, node: RNode) {
2853        // Empty list: nothing to scroll to (the row count is read straight from the piece's
2854        // snapshot, with no tree access, so this guard is cheap and backend-independent).
2855        if self.lists.get(&node).map_or(0, |s| (s.driver.len)()) == 0 {
2856            return;
2857        }
2858        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
2859            self.toolkit.update(
2860                &handle,
2861                kinds::LIST,
2862                &day_spec::props::ListPatch::ScrollToEnd as &dyn Any,
2863                None,
2864            );
2865        }
2866    }
2867
2868    fn list_scroll_to_row(&mut self, node: RNode, row: usize) {
2869        let len = self.lists.get(&node).map_or(0, |s| (s.driver.len)());
2870        if len == 0 {
2871            return;
2872        }
2873        let mut row = row.min(len - 1);
2874        if let Some(map) = self.lists.get(&node).and_then(|s| s.sections.as_ref()) {
2875            row = map.display_of(row).unwrap_or(row);
2876        }
2877        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
2878            self.toolkit.update(
2879                &handle,
2880                kinds::LIST,
2881                &day_spec::props::ListPatch::ScrollToRow(row) as &dyn Any,
2882                None,
2883            );
2884        }
2885    }
2886
2887    fn list_set_editing(&mut self, node: RNode, on: bool) {
2888        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
2889            self.toolkit.update(
2890                &handle,
2891                kinds::LIST,
2892                &day_spec::props::ListPatch::Editing(on) as &dyn Any,
2893                None,
2894            );
2895        }
2896    }
2897
2898    fn list_set_selected(&mut self, node: RNode, rows: Vec<usize>) {
2899        let rows = match self.lists.get(&node).and_then(|s| s.sections.as_ref()) {
2900            Some(map) => rows.iter().filter_map(|i| map.display_of(*i)).collect(),
2901            None => rows,
2902        };
2903        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
2904            self.toolkit.update(
2905                &handle,
2906                kinds::LIST,
2907                &day_spec::props::ListPatch::Selected(rows) as &dyn Any,
2908                None,
2909            );
2910        }
2911    }
2912
2913    fn list_driver(&mut self, node: RNode) -> Option<std::rc::Rc<crate::list::ListDriver>> {
2914        self.lists.get(&node).map(|s| s.driver.clone())
2915    }
2916
2917    fn install_tree(&mut self, node: RNode, driver: crate::tree_driver::TreeDriver) {
2918        let driver = Rc::new(driver);
2919        self.trees.insert(
2920            node,
2921            crate::tree_driver::TreeState {
2922                driver: driver.clone(),
2923                cells: HashMap::new(),
2924            },
2925        );
2926        let source = crate::tree_driver::make_tree_source(node, driver);
2927        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
2928            self.toolkit.attach_tree(&handle, source);
2929        }
2930    }
2931
2932    fn tree_prepare_cell(
2933        &mut self,
2934        node: RNode,
2935        key: usize,
2936        cell: RawHandle,
2937    ) -> crate::tree_driver::TreeCellStep {
2938        if let Some(state) = self.trees.get(&node)
2939            && let Some(bound) = state.cells.get(&key)
2940        {
2941            let (rebind, anchor) = (bound.rebind.clone(), bound.anchor);
2942            // Same rule as `list_prepare_cell`: give a pooled cell its parked ids back.
2943            self.restore_subtree_ids(anchor);
2944            return crate::tree_driver::TreeCellStep::Rebind { rebind, anchor };
2945        }
2946        // First use of this cell: adopt the native cell and anchor a fresh subtree under it.
2947        // The centering anchor layout, not the list's PassThrough: tree rows have a fixed
2948        // Uniform height and content that hugs, so the content centers in the cell.
2949        let handle = self.toolkit.adopt(cell);
2950        let anchor =
2951            self.create_cell_anchor(handle, Scope::child(), Rc::new(crate::layout::CellCenter));
2952        crate::tree_driver::TreeCellStep::Build { anchor }
2953    }
2954
2955    fn tree_store_cell(
2956        &mut self,
2957        node: RNode,
2958        key: usize,
2959        anchor: RNode,
2960        built: crate::tree_driver::TreeBuiltRow,
2961    ) {
2962        if let Some(state) = self.trees.get_mut(&node) {
2963            state.cells.insert(
2964                key,
2965                crate::tree_driver::TreeBoundCell {
2966                    anchor,
2967                    scope: built.scope,
2968                    rebind: built.rebind,
2969                    native_width: None,
2970                    native_height: None,
2971                    laid_width: None,
2972                    laid_height: None,
2973                },
2974            );
2975        }
2976    }
2977
2978    fn tree_layout_cell(&mut self, node: RNode, key: usize) {
2979        // The width the backend last granted this cell, once it has said so (indentation makes
2980        // every tree cell's width its own); until then the tree's own content width. Every path
2981        // that re-lays a row comes through here, so a width the backend corrected stays corrected.
2982        let native = self
2983            .trees
2984            .get(&node)
2985            .and_then(|s| s.cells.get(&key))
2986            .and_then(|c| c.native_width);
2987        let width = native.unwrap_or_else(|| {
2988            self.nodes
2989                .get(node)
2990                .and_then(|n| n.last_native_frame)
2991                .map_or(self.windows[0].size.width, |f| f.size.width)
2992        });
2993        self.layout_tree_cell_at(node, key, width);
2994    }
2995
2996    fn tree_layout_cell_width(&mut self, node: RNode, key: usize, width: f64) {
2997        // The backend's word on the cell's width (`TreeSource::layout_cell`), remembered so the
2998        // next first-approximation pass does not undo it.
2999        if let Some(cell) = self
3000            .trees
3001            .get_mut(&node)
3002            .and_then(|s| s.cells.get_mut(&key))
3003        {
3004            cell.native_width = Some(width);
3005        }
3006        self.layout_tree_cell_at(node, key, width);
3007    }
3008
3009    fn tree_cell_height(&self, node: RNode, key: usize) -> f64 {
3010        self.trees
3011            .get(&node)
3012            .and_then(|s| s.cells.get(&key))
3013            .and_then(|b| b.laid_height)
3014            .unwrap_or(0.0)
3015    }
3016
3017    fn tree_layout_cell_size(&mut self, node: RNode, key: usize, size: Size) {
3018        let changed = self
3019            .trees
3020            .get_mut(&node)
3021            .and_then(|s| s.cells.get_mut(&key))
3022            .and_then(|cell| {
3023                let changed = cell.native_height != Some(size.height);
3024                cell.native_height = Some(size.height);
3025                changed.then_some(cell.anchor)
3026            });
3027        if let Some(anchor) = changed {
3028            self.invalidate_subtree(anchor);
3029        }
3030        self.tree_layout_cell_width(node, key, size.width);
3031    }
3032
3033    fn tree_recycle_cell(&mut self, node: RNode, key: usize) {
3034        let Some(anchor) = self
3035            .trees
3036            .get(&node)
3037            .and_then(|s| s.cells.get(&key))
3038            .map(|b| b.anchor)
3039        else {
3040            return;
3041        };
3042        self.clear_subtree_ids(anchor);
3043    }
3044
3045    fn list_recycle_cell(&mut self, node: RNode, key: usize) {
3046        let Some(anchor) = self
3047            .lists
3048            .get_mut(&node)
3049            .and_then(|s| s.cells.get_mut(&key))
3050            .map(|b| {
3051                b.active = false;
3052                // The next row this cell shows is laid afresh by its `bind_row`, and the host
3053                // reads `cell_height` right after; a height left over from the previous row
3054                // would make that first layout look like a change and raise a spurious
3055                // `RowSizeInvalidated`.
3056                b.laid_height = None;
3057                b.anchor
3058            })
3059        else {
3060            return;
3061        };
3062        self.clear_subtree_ids(anchor);
3063    }
3064
3065    fn list_release_cell(&mut self, node: RNode, key: usize) {
3066        // Unknown cell (never bound, or released twice): nothing to do.
3067        let Some(cell) = self.lists.get_mut(&node).and_then(|s| s.cells.remove(&key)) else {
3068            return;
3069        };
3070        // The same teardown `collect_and_release` gives every cell when the list goes
3071        // (docs/list.md): the row's reactive graph, then its nodes. The anchor's own handle
3072        // is the host's cell and is only dropped, never queued for release (`LIST_CELL`);
3073        // the handles under it are Day's and go through the release queue as usual.
3074        cell.scope.dispose();
3075        self.remove_subtree_impl(cell.anchor);
3076    }
3077
3078    fn list_pin_cell(&mut self, node: RNode, key: usize) {
3079        let Some(anchor) = self
3080            .lists
3081            .get_mut(&node)
3082            .and_then(|s| s.cells.get_mut(&key))
3083            .map(|b| {
3084                b.pinned = true;
3085                b.anchor
3086            })
3087        else {
3088            return;
3089        };
3090        self.clear_subtree_ids(anchor);
3091    }
3092
3093    fn tree_reload(&mut self, node: RNode) {
3094        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
3095            self.toolkit.update(
3096                &handle,
3097                kinds::TREE,
3098                &day_spec::props::TreePatch::Reload as &dyn Any,
3099                None,
3100            );
3101        }
3102    }
3103
3104    fn tree_set_expanded(&mut self, node: RNode, token: u64, expanded: bool) {
3105        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
3106            self.toolkit.update(
3107                &handle,
3108                kinds::TREE,
3109                &day_spec::props::TreePatch::Expand(token, expanded) as &dyn Any,
3110                None,
3111            );
3112        }
3113    }
3114
3115    fn tree_set_selected(&mut self, node: RNode, tokens: Vec<u64>) {
3116        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
3117            self.toolkit.update(
3118                &handle,
3119                kinds::TREE,
3120                &day_spec::props::TreePatch::Selected(tokens) as &dyn Any,
3121                None,
3122            );
3123        }
3124    }
3125
3126    fn tree_reveal(&mut self, node: RNode, token: u64) {
3127        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
3128            self.toolkit.update(
3129                &handle,
3130                kinds::TREE,
3131                &day_spec::props::TreePatch::Reveal(token) as &dyn Any,
3132                None,
3133            );
3134        }
3135    }
3136
3137    fn tree_driver(&mut self, node: RNode) -> Option<std::rc::Rc<crate::tree_driver::TreeDriver>> {
3138        self.trees.get(&node).map(|s| s.driver.clone())
3139    }
3140
3141    fn set_drag_source(&mut self, node: RNode, source: day_spec::transfer::Source) {
3142        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
3143            self.toolkit.set_drag_source(&handle, source);
3144        }
3145    }
3146    fn set_drop_target(&mut self, node: RNode, target: day_spec::transfer::Target) {
3147        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
3148            self.toolkit.set_drop_target(&handle, target);
3149        }
3150    }
3151    fn set_context_menu_fn(&mut self, node: RNode, f: day_spec::ContextMenuFn) {
3152        // Match static menus: padding/frame decorators are layout-only, but the provider
3153        // must be installed on the native root beneath them, not silently discarded.
3154        let target = if self.nodes.get(node).is_some_and(|n| n.handle.is_some()) {
3155            Some(node)
3156        } else {
3157            let mut roots = Vec::new();
3158            self.native_descendants(node, &mut roots);
3159            roots.first().copied()
3160        };
3161        let Some(target) = target else {
3162            log::warn!("context_menu_fn on a subtree with no native view — menu dropped");
3163            return;
3164        };
3165        let model = ContextMenuModel::Provider(f.clone());
3166        self.context_menus.insert(node, model.clone());
3167        self.context_menus.insert(target, model);
3168        if let Some(handle) = self.nodes.get(target).and_then(|n| n.handle.clone()) {
3169            self.toolkit
3170                .set_context_menu_fn(&handle, rnode_to_id(target), f);
3171        }
3172    }
3173
3174    fn set_button_menu(&mut self, node: RNode, f: day_spec::ContextMenuFn) {
3175        self.button_menus.insert(node, f.clone());
3176        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
3177            self.toolkit.set_button_menu(&handle, rnode_to_id(node), f);
3178        }
3179    }
3180
3181    fn context_menu_of(&mut self, node: RNode) -> Option<day_spec::ContextMenuFn> {
3182        // The element a script names may sit above or below the node the menu landed on (an id
3183        // on a wrapper, a menu on the label inside it): the node itself, then its ancestors. A
3184        // menu button's own menu is the one its press opens, so it answers before any context
3185        // menu at the same node.
3186        let mut cur = node;
3187        loop {
3188            if let Some(f) = self.button_menus.get(&cur) {
3189                return Some(f.clone());
3190            }
3191            if let Some(model) = self.context_menus.get(&cur) {
3192                return Some(match model {
3193                    ContextMenuModel::Items(items) => {
3194                        let items = items.clone();
3195                        Rc::new(move |_| items.clone())
3196                    }
3197                    ContextMenuModel::Provider(f) => f.clone(),
3198                });
3199            }
3200            // The root (and a list cell's anchor) is its own parent, or has a null one,
3201            // which the lookup misses.
3202            let parent = self.nodes.get(cur)?.parent;
3203            if parent == cur {
3204                return None;
3205            }
3206            cur = parent;
3207        }
3208    }
3209}
3210
3211// ---------------------------------------------------------------------------
3212// Thread-local tree + event pump
3213// ---------------------------------------------------------------------------
3214
3215day_reactive::tls_slots! {
3216    tree;
3217    /// The installed tree. `ManuallyDrop` so the thread-local destructor never drops it: the
3218    /// tree owns the toolkit's native widgets, and dropping those at thread exit runs the
3219    /// toolkit's callbacks (a GtkListBox being emptied calls its header func) against
3220    /// thread-locals that may already be gone — Rust destroys them in an order nobody controls,
3221    /// and a panic inside a C trampoline cannot unwind, so the process aborted on the way out
3222    /// of a clean exit. At process exit the OS reclaims the widgets; nothing in their drop
3223    /// matters. [`uninstall_tree`] (tests, Android's remount) still drops the tree explicitly,
3224    /// while every thread-local is alive.
3225    static TREE: std::mem::ManuallyDrop<RefCell<Option<Box<dyn TreeOps>>>> =
3226        const { std::mem::ManuallyDrop::new(RefCell::new(None)) };
3227    static EVENTS: RefCell<VecDeque<(NodeId, Event)>> = const { RefCell::new(VecDeque::new()) };
3228    static PUMP_PENDING: Cell<bool> = const { Cell::new(false) };
3229    static PUMP_ACTIVE: Cell<bool> = const { Cell::new(false) };
3230    /// Posted main-thread closures that arrived while the tree was borrowed and so could
3231    /// not run (see [`run_posted_or_defer`]). Drained at the next safe point, in order.
3232    static DEFERRED: RefCell<Vec<Box<dyn FnOnce() + Send>>> = const { RefCell::new(Vec::new()) };
3233    /// The event observer installed by [`set_event_observer`] and consulted by [`enqueue_events`].
3234    /// `Rc`, not `Box`, so the handle can be cloned out and invoked with no borrow held (the
3235    /// observer may safely re-enter Day to read the tree or stop recording).
3236    static EVENT_OBSERVER: RefCell<Option<Rc<EventObserver>>> = const { RefCell::new(None) };
3237    /// Monotonic pump counter, bumped once per [`pump_events_inner`]. The recorder ages its
3238    /// coalescing candidate by it: a tap folds into a navigation caused in the same or the next
3239    /// pump (a signal-bound sidebar remount settles one pump late), but never a later, unrelated
3240    /// navigation.
3241    static PUMP_GEN: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
3242
3243    /// The node that last reported gaining focus, cleared when it reports losing it.
3244    static FOCUSED: std::cell::Cell<Option<RNode>> = const { std::cell::Cell::new(None) };
3245    /// The dispatch ids of the last share chooser's app actions, dropped when the next one
3246    /// opens: a chooser is modal, so at most one can still report a choice.
3247    static SHARE_ACTION_IDS: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
3248}
3249
3250pub fn install_tree(tree: Box<dyn TreeOps>) {
3251    // A fresh mount starts with no route hosts; nav()/tabs() re-register during build.
3252    crate::nav::clear_controllers();
3253    TREE.with(|t| *t.borrow_mut() = Some(tree));
3254    // Seed colors outside layout/draw callbacks, and refresh across activity recreation.
3255    crate::note_appearance_changed();
3256    let _ = crate::system_color(day_spec::SystemColor::Accent);
3257    // Read the export answers now, while the tree is free, so a context menu built inside a
3258    // later borrow finds them (`image::canvas_exports`).
3259    let _ = crate::image::canvas_exports();
3260}
3261
3262/// Tear the current mount down so the app can be built again in the same process
3263/// (docs/settings.md "Appearance on Android").
3264///
3265/// Android is the one platform that needs this: an activity recreation (the mechanism of a
3266/// light/dark switch, and the side effect of any configuration change the manifest does not
3267/// claim) destroys the window and calls the app's entry point a second time.
3268/// Everywhere else launch happens exactly once by construction.
3269///
3270/// What this resets is everything an app's `root()` registers, because `root()` is about to run
3271/// again and register it all a second time: the window registry and its content scopes, the
3272/// navigation controllers, the per-window ambient signals, the lifecycle handlers, the menu
3273/// actions. What it leaves alone is state that lives on the root reactive scope
3274/// (`Signal::global`, `Ambient::app()`), which is exactly the state an app expects to outlive a
3275/// window, and which is what makes a recreation cheap rather than a cold start (docs/state.md).
3276///
3277/// One thing it cannot reset is an app's own `std::sync::Once`: a one-time install guarded that
3278/// way will not re-run, so a `Once` in `root()` is the pattern to avoid on Android.
3279pub fn prepare_remount() {
3280    // Drop in-flight reactive work first. Anything already queued was scheduled by the mount
3281    // that is about to be disposed, and running it afterwards reads signals that no longer
3282    // exist ("read of disposed Signal"). This also re-roots the scope stack, which matters more
3283    // than it looks: left pointing at a disposed scope, every `Signal::new` in the rebuild is
3284    // born dead and the new tree panics on its own state.
3285    day_reactive::recover_from_panic();
3286    uninstall_tree();
3287    // Tearing the old tree down can schedule cleanup of its own; go back to idle before rebuilding.
3288    day_reactive::recover_from_panic();
3289    crate::lifecycle::reset_handlers();
3290    crate::menu::reset_menus();
3291}
3292
3293/// Whether a tree is installed on this thread, i.e. whether the app has already launched.
3294///
3295/// The one caller that is not a test is Android's `nativeStart`, which an activity recreation can
3296/// re-enter after the app is already up (docs/settings.md "Appearance on Android"). Everywhere
3297/// else launch happens exactly once by construction.
3298#[must_use]
3299pub fn is_mounted() -> bool {
3300    TREE.with(|t| t.borrow().is_some())
3301}
3302
3303/// Reset the thread-local tree + queues (tests).
3304pub fn uninstall_tree() {
3305    // A decode parked on the tree that is going away would wait forever (docs/images.md).
3306    crate::image::reset();
3307    crate::nav::clear_controllers();
3308    crate::windows::reset_windows();
3309    crate::status::reset_status();
3310    // Per-window signals are keyed by root node, and roots repeat across trees on this thread;
3311    // a stale entry would hand the next tree the previous one's size class.
3312    crate::reset_ambient();
3313    TREE.with(|t| *t.borrow_mut() = None);
3314    EVENTS.with(|e| e.borrow_mut().clear());
3315    PUMP_PENDING.with(|c| c.set(false));
3316    // The event observer (§14.6) is thread-local state too; a test that installed one must not
3317    // leak it into the next tree on this thread.
3318    EVENT_OBSERVER.with(|o| *o.borrow_mut() = None);
3319}
3320
3321/// Access the installed tree. Tree methods never run user code, so nesting cannot occur
3322/// while a borrow is held; if events were queued during the call, they are pumped after
3323/// the borrow is released (the "safe point" of §3.3).
3324///
3325/// # Panics
3326///
3327/// Panics when no tree is installed on the calling thread: before the app has started, or off
3328/// the UI thread.
3329pub fn with_tree<R>(f: impl FnOnce(&mut dyn TreeOps) -> R) -> R {
3330    let r = TREE.with(|t| {
3331        let mut opt = t.borrow_mut();
3332        let ops = opt.as_mut().expect("day: no tree installed on this thread");
3333        f(ops.as_mut())
3334    });
3335    if PUMP_PENDING.with(|c| c.replace(false)) {
3336        pump_events();
3337    }
3338    run_deferred();
3339    r
3340}
3341
3342/// Run a posted main-thread closure now, or hold it for the next safe point when the tree is
3343/// borrowed. Tree methods never run user code, but a backend may pump its native message
3344/// loop from inside one (XAML's `open_window` waits for the new root to load; a modal native
3345/// loop can nest anywhere), and a closure that loop dispatches would re-enter [`with_tree`]
3346/// on the borrowed tree and panic ("`RefCell` already borrowed"). Held closures run at the end
3347/// of the outermost `with_tree`, in arrival order, each contained like any posted task.
3348pub(crate) fn run_posted_or_defer(f: Box<dyn FnOnce() + Send>) {
3349    // A post that arrives while the thread's locals are being torn down (a future cancelled by
3350    // a dropping tree, at process or test-thread exit) has nothing left to run against.
3351    let Ok(borrowed) = TREE.try_with(|t| t.try_borrow_mut().is_err()) else {
3352        return;
3353    };
3354    if borrowed {
3355        DEFERRED.with(|d| d.borrow_mut().push(f));
3356    } else {
3357        crate::contain_posted_panic(f);
3358    }
3359}
3360
3361/// The safe-point drain for [`run_posted_or_defer`]: called once the borrow is released. A
3362/// drained closure may defer more (it can borrow the tree and nest a pump of its own), so
3363/// this loops until the queue stays empty; each batch is taken out before it runs.
3364fn run_deferred() {
3365    loop {
3366        let batch = DEFERRED.with(|d| std::mem::take(&mut *d.borrow_mut()));
3367        if batch.is_empty() {
3368            return;
3369        }
3370        for f in batch {
3371            crate::contain_posted_panic(f);
3372        }
3373    }
3374}
3375
3376/// Query the active toolkit's support for a capability (docs). Lets app/piece code adapt its
3377/// content to the backend, e.g. a page can skip a title the native nav already shows in a header
3378/// (`Cap::NavHeader`), or pick a presentation from `Cap::NavSplit`.
3379#[must_use]
3380pub fn capability(cap: day_spec::Cap) -> day_spec::Support {
3381    with_tree(|t| t.capability(cap))
3382}
3383
3384/// Open `url` in the platform's default handler (system browser for `http(s)`, mail client for
3385/// `mailto:`, …). The function behind the [`link`](/api/day_pieces/fn.link.html) piece; call it
3386/// directly from a tap handler for a custom affordance. Fire and forget: no result, unopenable
3387/// URLs are ignored by the backend.
3388pub fn open_url(url: &str) {
3389    // While `day test` runs the app's cases, a link is recorded for `assert_opened_url` and
3390    // nothing opens: a test run must not launch the machine's browser (docs/testing.md).
3391    if crate::conformance::intercept_open_url(url) {
3392        return;
3393    }
3394    with_tree(|t| t.open_url(url));
3395}
3396
3397/// Speak `text` through the screen reader without moving its focus (docs/accessibility.md):
3398/// the outcome of an action the user cannot otherwise learn about ("Saved", "3 results"). The
3399/// sentence waits for whatever is being read to finish; [`announce_urgent`] interrupts it.
3400/// Nothing happens when no screen reader is running, and nothing happens on a toolkit that
3401/// answers [`Cap::Announce`](day_spec::Cap::Announce) with `Unsupported`.
3402pub fn announce(text: &str) {
3403    crate::conformance::note_announcement(text);
3404    with_tree(|t| t.announce(text, false));
3405}
3406
3407/// [`announce`], interrupting what the screen reader is saying: an error, or a change that
3408/// cannot wait.
3409pub fn announce_urgent(text: &str) {
3410    crate::conformance::note_announcement(text);
3411    with_tree(|t| t.announce(text, true));
3412}
3413
3414/// Whether the current toolkit can present a native sharing chooser.
3415#[must_use]
3416pub fn share_support() -> Support {
3417    with_tree(|t| t.share_support())
3418}
3419/// One of the app's actions for [`present_share`]: its localized title, glyph and handler.
3420pub type ShareActionEntry = (String, Option<day_spec::Symbol>, Rc<dyn Fn()>);
3421
3422/// Present the native share chooser for `url` (docs/sharing.md), with the app's own `actions`
3423/// (title, glyph, handler) beside the system's targets where the chooser can carry them
3424/// (`Cap::ShareActions`). `anchor` names the control the chooser points at where it is a
3425/// popover, by its element id. Call directly from user activation (required on web).
3426///
3427/// Returns false if unavailable or presentation failed; cancellation is not an error and no
3428/// completion is implied. Apps use day-pieces' `Share` builder, which resolves localized titles.
3429#[must_use]
3430pub fn present_share(
3431    url: &str,
3432    title: &str,
3433    actions: Vec<ShareActionEntry>,
3434    anchor: Option<&str>,
3435) -> bool {
3436    for id in SHARE_ACTION_IDS.with(|ids| std::mem::take(&mut *ids.borrow_mut())) {
3437        crate::menu::forget_action(id);
3438    }
3439    let actions: Vec<day_spec::share::ShareAction> = actions
3440        .into_iter()
3441        .map(|(title, symbol, run)| {
3442            let id = crate::menu::register_menu_action(run);
3443            SHARE_ACTION_IDS.with(|ids| ids.borrow_mut().push(id));
3444            day_spec::share::ShareAction { id, title, symbol }
3445        })
3446        .collect();
3447    let spec = day_spec::share::ShareSpec {
3448        url: url.to_string(),
3449        title: title.to_string(),
3450        actions,
3451    };
3452    with_tree(|t| {
3453        let anchor = anchor.and_then(|id| t.find_by_id(id));
3454        t.share(&spec, anchor)
3455    })
3456}
3457
3458/// Query current system associations on the UI thread. macOS AppKit implements all query
3459/// kinds; other backends return `Unsupported`. No application is launched by discovery.
3460///
3461/// # Errors
3462///
3463/// Returns `ApplicationError::Unsupported` where the backend has no association query, or the
3464/// platform's own failure.
3465pub fn application_handlers(
3466    query: &day_spec::applications::HandlerQuery,
3467) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError> {
3468    with_tree(|t| t.application_handlers(query))
3469}
3470
3471/// The OS-chosen browser for HTTPS links, read afresh rather than cached by Day.
3472///
3473/// # Errors
3474///
3475/// Returns the errors of [`application_handlers`].
3476pub fn default_browser()
3477-> Result<Option<day_spec::applications::Application>, day_spec::applications::ApplicationError> {
3478    application_handlers(&day_spec::applications::HandlerQuery::Scheme(
3479        "https".into(),
3480    ))
3481    .map(|h| h.default)
3482}
3483
3484/// Open a URL or file URL in a chosen application. Await on the UI executor. Success means
3485/// the OS accepted the open request; tab/window presentation belongs to the receiving app.
3486///
3487/// # Errors
3488///
3489/// Returns the platform's `ApplicationError`, or `LaunchFailed` when the request was dropped
3490/// without an answer.
3491pub async fn open_url_with_application(
3492    url: &str,
3493    application: &str,
3494) -> Result<(), day_spec::applications::ApplicationError> {
3495    let (send, receive) = day_async::oneshot();
3496    with_tree(|t| {
3497        t.open_url_with_application(url, application, Box::new(move |result| send.send(result)));
3498    });
3499    receive
3500        .await
3501        .unwrap_or(Err(day_spec::applications::ApplicationError::LaunchFailed))
3502}
3503
3504/// Tell layout that a node's intrinsic size may have changed. For tweaks (docs/tweaks.md):
3505/// after a native call that alters a widget's preferred size (fonts, tick marks, bezel styles),
3506/// the measure cache along the node's path must be invalidated, since Day can't see native
3507/// mutations it didn't make. Relayout runs at the next turn boundary as usual. No-op on a
3508/// disposed node.
3509pub fn invalidate_size(node: RNode) {
3510    with_tree(|t| {
3511        t.mark_needs_measure(node);
3512        t.mark_layout_dirty();
3513    });
3514}
3515
3516/// Like `with_tree`, but returns `None` instead of panicking when the tree can't be entered:
3517/// already borrowed, or not installed yet. A snapshot (`TreeOps::snapshot`) holds the borrow
3518/// while the backend draws the window synchronously, and that draw can re-enter Day through a
3519/// native callback, e.g. a lazy list's `viewForRow`/`connect_bind`/`cellForRow` firing during
3520/// `cacheDisplayInRect`. And platform style callbacks can fire before `install_tree`, e.g.
3521/// GTK's `StyleManager` emits a `dark` notify while `startup` applies a forced `DAY_THEME`
3522/// scheme, before `activate` mounts the tree; a panic there unwinds into a C signal trampoline
3523/// and aborts the process. Such callbacks use this and skip their work; the next real
3524/// layout (or the signal's first post-mount read) catches up.
3525pub fn try_with_tree<R>(f: impl FnOnce(&mut dyn TreeOps) -> R) -> Option<R> {
3526    let r = TREE.with(|t| {
3527        let mut opt = t.try_borrow_mut().ok()?;
3528        let ops = opt.as_mut()?;
3529        Some(f(ops.as_mut()))
3530    });
3531    if r.is_some() {
3532        if PUMP_PENDING.with(|c| c.replace(false)) {
3533            pump_events();
3534        }
3535        run_deferred();
3536    }
3537    r
3538}
3539
3540/// [`try_with_tree`] without the pump on the way out, for work that is itself part of a pump,
3541/// or that raises no events (`release_image`), where a nested pump would be wrong or wasted.
3542pub(crate) fn with_tree_if_free<R>(f: impl FnOnce(&mut dyn TreeOps) -> R) -> Option<R> {
3543    TREE.with(|t| {
3544        let mut opt = t.try_borrow_mut().ok()?;
3545        let ops = opt.as_mut()?;
3546        Some(f(ops.as_mut()))
3547    })
3548}
3549
3550/// Whether no tree is installed, as distinct from one that is merely borrowed right now, which
3551/// this answers `false` for. [`is_mounted`] cannot tell the two apart without panicking.
3552pub(crate) fn tree_absent() -> bool {
3553    // Bitmap handles can outlive the entire core TLS root at process/thread exit.
3554    TREE.try_with(|t| t.try_borrow().is_ok_and(|o| o.is_none()))
3555        .unwrap_or(true)
3556}
3557
3558/// Ask for a pump at the next safe point (the end of the current `with_tree`), for work queued
3559/// while the tree was borrowed.
3560pub(crate) fn request_pump() {
3561    PUMP_PENDING.with(|c| c.set(true));
3562}
3563
3564#[must_use]
3565pub fn has_tree() -> bool {
3566    // Native resize/layout callbacks can ask while a Toolkit call already borrows the tree.
3567    // A busy tree is installed, not absent; this presence probe must not borrow it again.
3568    !tree_absent()
3569}
3570
3571/// The enqueue-only event sink installed into every backend (§8.3). May be invoked
3572/// re-entrantly from inside any Toolkit method; dispatch happens at the next safe point.
3573pub fn enqueue_event(id: NodeId, ev: Event) {
3574    enqueue_events([(id, ev)]);
3575}
3576
3577/// The toolkit's event sink: [`enqueue_event`], after a sectioned list's row events are
3578/// translated from the host's display rows to the app's items (docs/list.md "Sections").
3579/// Everything else (dayscript, probes, day-core's own reports) already speaks items and
3580/// enqueues directly.
3581pub(crate) fn enqueue_native_event(id: NodeId, ev: Event) {
3582    if let Some(ev) = crate::list::translate_native_event(id, ev) {
3583        enqueue_event(id, ev);
3584    }
3585}
3586
3587/// Enqueue several events into one drain before dispatching. Backends that observe a focus
3588/// move at a single point (Qt's `focusChanged(old, new)`, an AppKit first-responder change)
3589/// deliver the loss+gain pair through this so the pump can dispatch the gain first and a
3590/// shared group signal never passes through `None` (docs/focus.md).
3591pub fn enqueue_events(evs: impl IntoIterator<Item = (NodeId, Event)>) {
3592    // Recording/telemetry hook (§14.6): when an observer is installed, let it see every event in
3593    // the exact order and form the app is about to receive, before it is dispatched,
3594    // so it observes precisely what the app receives. This is the single point every backend
3595    // funnels native events through, so the observer needs no per-toolkit code. The handle is
3596    // cloned out first (a cheap `Rc` bump) so no thread-local borrow is held across the call: the
3597    // observer may re-enter Day (resolve an id via `id_of`, or even remove itself to stop
3598    // recording) without a borrow conflict. A `None` observer costs one `Option` check and takes
3599    // the original zero-copy `extend` path.
3600    let observer = EVENT_OBSERVER.with(|o| o.borrow().clone());
3601    match observer {
3602        Some(obs) => {
3603            let batch: Vec<(NodeId, Event)> = evs.into_iter().collect();
3604            for (id, ev) in &batch {
3605                obs(*id, ev);
3606            }
3607            EVENTS.with(|e| e.borrow_mut().extend(batch));
3608        }
3609        None => EVENTS.with(|e| e.borrow_mut().extend(evs)),
3610    }
3611    let tree_free = TREE.with(|t| t.try_borrow_mut().is_ok());
3612    if tree_free {
3613        pump_events();
3614    } else {
3615        PUMP_PENDING.with(|c| c.set(true));
3616    }
3617}
3618
3619/// The current pump generation (see `PUMP_GEN`). Read by the recorder's nav coalescing.
3620#[must_use]
3621pub fn pump_generation() -> u64 {
3622    PUMP_GEN.with(std::cell::Cell::get)
3623}
3624
3625/// Install (or clear, with `None`) an observer that sees every event day-core dispatches, in queue
3626/// order, at the one point every backend funnels native events through ([`enqueue_events`],
3627/// §8.3), before the event reaches the app, so it observes exactly what the app receives. This
3628/// is the recording/telemetry hook behind [`day::record`](../day_script/record/index.html)
3629/// (§14.6): a higher layer captures user actions into a replayable dayscript without touching
3630/// any of the backends. Main-thread only; a `None` observer adds no cost to the event path. The
3631/// boxed closure is adopted into an `Rc` internally so [`enqueue_events`] can call it with no
3632/// borrow held.
3633pub fn set_event_observer(observer: Option<Box<EventObserver>>) {
3634    EVENT_OBSERVER.with(|o| *o.borrow_mut() = observer.map(Rc::from));
3635}
3636
3637/// Resolve a dispatched [`NodeId`] back to the app-authored `.id()` string that named its node
3638/// (`find_by_id`'s inverse, §5.5), or `None` for an id-less node or one no longer in the tree. The
3639/// recorder ([`day::record`](../day_script/record/index.html), §14.6) calls this from inside its
3640/// event observer to label a tap/input with the id an app would target in a dayscript step.
3641/// Borrow-safe: returns `None` rather than panicking if the tree is momentarily borrowed by a
3642/// re-entrant backend call.
3643#[must_use]
3644pub fn id_of(node: NodeId) -> Option<String> {
3645    try_with_tree(|t| t.node_id(id_to_rnode(node))).flatten()
3646}
3647
3648/// A human-readable label for a node, for annotating a recorded script (§14.6): the accessibility
3649/// label if one is set (`.a11y(label = …)`, the localized string the screen reader speaks),
3650/// otherwise the control's own visible text. `None` when the node carries neither.
3651#[must_use]
3652pub fn label_of(node: NodeId) -> Option<String> {
3653    try_with_tree(|t| {
3654        let rnode = id_to_rnode(node);
3655        let a11y = t
3656            .node_a11y(rnode)
3657            .and_then(|a| a.label)
3658            .filter(|s| !s.is_empty());
3659        a11y.or_else(|| {
3660            t.node_probe(rnode)
3661                .map(|p| p.text)
3662                .filter(|s| !s.is_empty())
3663        })
3664    })
3665    .flatten()
3666}
3667
3668/// Dispatch queued native events from the backend queue, containing any panic. Native event
3669/// callbacks reach Day through `extern "C"` signal trampolines (GTK's `value_changed_trampoline`,
3670/// Qt's event filters, …) that abort the process on unwind (`panic_cannot_unwind`). A panic in a
3671/// Day event handler or its reactive drain (e.g. the reactive-cycle assertion firing during a
3672/// slider drag) would therefore `SIGABRT` the whole app instead of surfacing. Catch it at this
3673/// single backend-agnostic boundary, log it (the message carries the offending effect's source
3674/// location), and reset the runtime so the app keeps running (degraded) rather than crashing.
3675pub fn pump_events() {
3676    // Native mutations in a handler can enqueue focus, value, or dismissal
3677    // events. Finish that handler before dispatching them: nested dispatch can
3678    // dispose the signals still used by its remaining binding writes.
3679    if PUMP_ACTIVE.with(|active| active.replace(true)) {
3680        return;
3681    }
3682    let _guard = std::mem::DropGuard::new((), |()| PUMP_ACTIVE.with(|active| active.set(false)));
3683    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3684        loop {
3685            pump_events_inner();
3686            // flush_sync and route notifications may themselves enqueue events.
3687            // Drain these after their current reactions finish, before returning.
3688            if EVENTS.with(|events| events.borrow().is_empty()) {
3689                break;
3690            }
3691        }
3692    }));
3693    if let Err(payload) = result {
3694        let msg = payload
3695            .downcast_ref::<&str>()
3696            .map(|s| (*s).to_string())
3697            .or_else(|| payload.downcast_ref::<String>().cloned())
3698            .unwrap_or_else(|| "unknown panic".to_string());
3699        log::warn!(
3700            "a native event handler panicked and was contained — the app continues, but \
3701             reactive/UI state may be inconsistent until the next interaction. Cause: {msg}"
3702        );
3703        // Drop the in-flight event batch and reset drain state so the runtime isn't wedged.
3704        EVENTS.with(|e| e.borrow_mut().clear());
3705        PUMP_PENDING.with(|c| c.set(false));
3706        day_reactive::recover_from_panic();
3707        crate::notify_contained_panic();
3708    }
3709}
3710
3711fn pump_events_inner() {
3712    // The tree borrow has ended by now: run the image releases that arrived while it was held.
3713    crate::image::flush_deferred_releases();
3714    // A new pump: bump the generation, then record any route change that a previous pump left
3715    // pending (a signal-bound sidebar/stack remount settles into NAV_STACK a tick after the pump
3716    // that triggered it, so the tail check below reads a stale route; this start check catches it
3717    // at the next pump boundary, still fresh enough to fold its triggering select/tap). §14.6.
3718    PUMP_GEN.with(|g| g.set(g.get() + 1));
3719    crate::nav::maybe_notify_route_change();
3720    loop {
3721        let item = EVENTS.with(|e| e.borrow_mut().pop_front());
3722        let Some((id, ev)) = item else { break };
3723        // Presentation answers are keyed by request id, not by tree node (docs/dialogs.md).
3724        if let Event::PresentResult { req, result } = ev {
3725            crate::present::resolve_presentation(req, result);
3726            continue;
3727        }
3728        // Image decodes/encodes are keyed by request id too (docs/images.md), for the same
3729        // reason presentation is: the answer belongs to the caller that asked, not to a node.
3730        if let Event::ImageDecoded { req, result } = ev {
3731            crate::image::resolve_image_decode(req, result);
3732            continue;
3733        }
3734        if let Event::ImageEncoded { req, result } = ev {
3735            crate::image::resolve_image_encode(req, result);
3736            continue;
3737        }
3738        // Canvas exports answer the caller too (docs/canvas.md "Exporting").
3739        if let Event::BitmapRendered { req, result } = ev {
3740            crate::image::resolve_bitmap_render(req, result);
3741            continue;
3742        }
3743        if let Event::PdfRendered { req, result } = ev {
3744            crate::image::resolve_pdf_render(req, result);
3745            continue;
3746        }
3747        // Menu actions are keyed by action id, not by tree node (§ menus).
3748        if let Event::MenuAction(action) = ev {
3749            crate::menu::dispatch_menu_action(action);
3750            continue;
3751        }
3752        // Toolbar values are keyed by action id too (docs/toolbars.md); borrowed, because the
3753        // payload owns a String and the arms below still need `ev`.
3754        if let Event::ToolbarChanged { action, value } = &ev {
3755            crate::toolbar::dispatch_toolbar_value(*action, value);
3756            continue;
3757        }
3758        // The platform's system back that no native container consumed, taken for the app's
3759        // own handlers while they arm it (docs/navigation.md "Handling the system Back").
3760        if id == day_spec::WINDOW_NODE && matches!(ev, Event::NavBack { .. }) {
3761            crate::nav::system_back();
3762            continue;
3763        }
3764        // Lifecycle phases are app-global, not keyed by tree node (docs/lifecycle.md).
3765        if let Event::Lifecycle(phase) = ev {
3766            crate::lifecycle::dispatch_lifecycle(phase);
3767            continue;
3768        }
3769        // Focus loss/gain pairing (docs/focus.md): when focus moves between two Day controls,
3770        // the loss and gain arrive as separate events. Dispatching the queued gain first lets a
3771        // shared group signal transition `Some(A)` → `Some(B)` without an observable `None`
3772        // (the loss handler only clears the signal if it still names its own control).
3773        if ev == Event::FocusChanged(false) {
3774            let paired = EVENTS.with(|e| {
3775                let mut q = e.borrow_mut();
3776                let gain = q
3777                    .iter()
3778                    .position(|(gid, gev)| *gid != id && *gev == Event::FocusChanged(true));
3779                gain.map(|i| q.remove(i).expect("indexed event"))
3780            });
3781            if let Some((gid, gev)) = paired {
3782                dispatch_focus_probe(gid, &gev);
3783                dispatch_to_node(gid, &gev);
3784            }
3785        }
3786        if let Event::FocusChanged(_) = ev {
3787            dispatch_focus_probe(id, &ev);
3788        }
3789        dispatch_to_node(id, &ev);
3790    }
3791    day_reactive::flush_sync();
3792    // The route has settled now that every queued event is dispatched and reactive writes have
3793    // flushed. A sidebar click, a nav_link, a stack push, and a native back all change the route
3794    // by calling `navigate`/`pop` from an event handler, none of which pass back through
3795    // `enqueue_events`, so the event observer never sees them. Notifying here (deduped against
3796    // the last route) is how the recorder captures navigation regardless of what triggered it
3797    // (docs/navigation.md, §14.6).
3798    crate::nav::maybe_notify_route_change();
3799    // A handler re-arms as its `enabled` and its tabs' selections change; a gate no signal
3800    // reports (a document tab moved to its own window) is re-checked here, after every batch.
3801    crate::nav::sync_system_back();
3802}
3803
3804/// The node that currently has the keyboard, as the platform last reported it. Keys follow
3805/// focus (docs/menus.md), so this is where a synthetic key has to land for a scripted run to
3806/// exercise the same route a real one does. `None` when nothing focusable holds it.
3807#[must_use]
3808pub fn focused_node() -> Option<RNode> {
3809    FOCUSED.with(std::cell::Cell::get)
3810}
3811
3812/// Mirror a focus event into the node's dayscript probe (`assert_focused` reads it).
3813fn dispatch_focus_probe(id: NodeId, ev: &Event) {
3814    if let Event::FocusChanged(f) = ev {
3815        let node = id_to_rnode(id);
3816        with_tree(|t| t.set_probe_focused(node, *f));
3817    }
3818}
3819
3820/// Imperatively scroll a `scroll` piece (docs/scroll.md): `node` is the scroll node for edge
3821/// and offset targets (`ScrollTarget::Id` ignores it and reveals the named element in its own
3822/// nearest scroll). Animated on-screen; dayscript uses the unanimated variant for determinism.
3823/// Call with no tree borrow held.
3824#[expect(
3825    clippy::needless_pass_by_value,
3826    reason = "public signature; callers build the target at the call site"
3827)]
3828pub fn scroll_to(node: RNode, target: ScrollTarget) {
3829    with_tree(|t| {
3830        t.scroll_to_target(node, &target, true);
3831    });
3832}
3833
3834/// Run one already-routed event through its node's handlers (the tail of the pump loop).
3835fn dispatch_to_node(id: NodeId, ev: &Event) {
3836    let node = if id == day_spec::WINDOW_NODE {
3837        with_tree(|t| t.root_node())
3838    } else {
3839        id_to_rnode(id)
3840    };
3841    // A gesture addressed to a piece's own node (a dayscript step by id, which names that node
3842    // wherever `.id` sits in the chain; a probe's emit) is delivered to the node that enabled
3843    // the gesture: the node itself, or the wrapper above it where `.padding(..).on_tap(..)`
3844    // registered its handler, as a native gesture on the inner view reaches the recognizer on
3845    // its superview. A natively delivered gesture already names that node, so nothing moves.
3846    let gesture = match ev {
3847        Event::Tap(_) => Some(day_spec::GestureKind::Tap),
3848        Event::LongPress(_) => Some(day_spec::GestureKind::LongPress),
3849        Event::Drag { .. } => Some(day_spec::GestureKind::Drag),
3850        Event::Pan { .. } => Some(day_spec::GestureKind::Pan),
3851        Event::Pinch { .. } => Some(day_spec::GestureKind::Pinch),
3852        Event::Rotate { .. } => Some(day_spec::GestureKind::Rotate),
3853        Event::Hover { .. } => Some(day_spec::GestureKind::Hover),
3854        _ => None,
3855    };
3856    let node = match gesture.and_then(|k| with_tree(|t| t.gesture_target(node, k))) {
3857        Some(target) => target,
3858        None => node,
3859    };
3860    let mut handlers = with_tree(|t| t.handlers_for(node));
3861    // A key or a focus change the toolkit raised on a native view also reaches the layout-only
3862    // wrappers directly above it (the same element): `.frame(..).on_key(..)` listens on the
3863    // wrapper, while the platform delivers the key to the view. Only these two: a tap or a drag
3864    // already reaches the wrapper through `enable_gesture`'s descent, and would arrive twice.
3865    if matches!(ev, Event::Key(_) | Event::FocusChanged(_)) {
3866        with_tree(|t| {
3867            for w in t.wrappers_above(node) {
3868                handlers.extend(t.handlers_for(w));
3869            }
3870        });
3871    }
3872    if handlers.is_empty() {
3873        // A press routed to a node that no longer exists is a staleness bug somewhere
3874        // upstream (an element index, a native view outliving its node); surface it in
3875        // debug builds instead of dropping silently; alive-but-handlerless is normal.
3876        if cfg!(debug_assertions)
3877            && matches!(ev, Event::Pressed | Event::Tap(_))
3878            && !with_tree(|t| t.node_exists(node))
3879        {
3880            log::warn!("{ev:?} dropped — node {id:?} no longer exists (stale reference)");
3881        }
3882        return;
3883    }
3884    day_reactive::batch(|| {
3885        for h in &handlers {
3886            h(ev);
3887        }
3888    });
3889}
3890
3891fn collect_menu_families(
3892    items: &[day_spec::MenuItem],
3893    families: &mut std::collections::BTreeSet<String>,
3894) {
3895    for item in items {
3896        match item {
3897            day_spec::MenuItem::Action { id: Some(id), .. } => {
3898                families.insert(crate::element_id::family_of(id).to_owned());
3899            }
3900            day_spec::MenuItem::Submenu { items, .. } => collect_menu_families(items, families),
3901            _ => {}
3902        }
3903    }
3904}
3905
3906#[cfg(test)]
3907mod thread_exit_tests {
3908    use super::*;
3909    use std::sync::Arc;
3910    use std::sync::atomic::{AtomicBool, Ordering};
3911
3912    /// A toolkit that records being dropped: the tree owns it, so it goes when the tree does.
3913    struct Probe(Arc<AtomicBool>);
3914
3915    impl Drop for Probe {
3916        fn drop(&mut self) {
3917            self.0.store(true, Ordering::SeqCst);
3918        }
3919    }
3920
3921    impl Toolkit for Probe {
3922        type Handle = ();
3923        fn realize(&mut self, _: PieceKind, _: &dyn Any, _: NodeId) -> Self::Handle {}
3924        fn release(&mut self, (): Self::Handle) {}
3925        fn insert(&mut self, (): &Self::Handle, (): &Self::Handle, _: usize) {}
3926        fn remove(&mut self, (): &Self::Handle, (): &Self::Handle) {
3927            panic!("test probe has no attached children to remove");
3928        }
3929        fn move_child(&mut self, (): &Self::Handle, (): &Self::Handle, _: usize) {}
3930        fn measure(&mut self, (): &Self::Handle, _: PieceKind, _: Proposal) -> Size {
3931            Size::new(0.0, 0.0)
3932        }
3933        fn set_frame(&mut self, (): &Self::Handle, _: Rect, _: Option<&AnimSpec>) {}
3934        fn set_input_traits(&mut self, (): &Self::Handle, _: &InputTraits) -> Option<Self::Handle> {
3935            None
3936        }
3937        fn set_event_sink(&mut self, _: EventSink) {}
3938        fn update(
3939            &mut self,
3940            (): &Self::Handle,
3941            _: &'static str,
3942            _: &dyn Any,
3943            _: Option<&AnimSpec>,
3944        ) {
3945        }
3946    }
3947
3948    fn install_probe(dropped: &Arc<AtomicBool>) {
3949        let tree = Tree::new(Probe(dropped.clone()), (), Size::new(0.0, 0.0));
3950        install_tree(Box::new(tree));
3951    }
3952
3953    /// The tree owns the toolkit's native widgets, and dropping those at thread exit runs the
3954    /// toolkit's callbacks against thread-locals that are already gone (a `GtkListBox` being
3955    /// emptied calls its header func; a panic there cannot unwind through C and aborts the
3956    /// process on the way out of a clean exit). So a thread's end must leak the tree.
3957    #[test]
3958    fn the_tree_is_not_dropped_when_its_thread_ends() {
3959        let dropped = Arc::new(AtomicBool::new(false));
3960        let d = dropped.clone();
3961        std::thread::spawn(move || install_probe(&d))
3962            .join()
3963            .expect("thread");
3964        assert!(
3965            !dropped.load(Ordering::SeqCst),
3966            "the thread-local destructor dropped the tree, and with it the native widgets"
3967        );
3968    }
3969
3970    /// Explicit teardown is a different matter: tests and Android's remount take the tree down
3971    /// while every thread-local is alive, and that must still drop it.
3972    #[test]
3973    fn uninstall_still_drops_the_tree() {
3974        let dropped = Arc::new(AtomicBool::new(false));
3975        let d = dropped.clone();
3976        std::thread::spawn(move || {
3977            install_probe(&d);
3978            uninstall_tree();
3979            assert!(
3980                d.load(Ordering::SeqCst),
3981                "uninstall_tree must drop the tree"
3982            );
3983        })
3984        .join()
3985        .expect("thread");
3986    }
3987
3988    #[test]
3989    fn removing_an_unattached_node_releases_without_native_detach() {
3990        let dropped = Arc::new(AtomicBool::new(false));
3991        let mut tree = Tree::new(Probe(dropped), (), Size::new(0.0, 0.0));
3992        let scope = Scope::detached();
3993        let node = tree.create_node(
3994            "fixture.detached",
3995            &(),
3996            Rc::new(crate::LeafLayout),
3997            Flex::default(),
3998            true,
3999            false,
4000            scope,
4001        );
4002        tree.remove_subtree(node);
4003        assert!(!tree.node_exists(node));
4004        assert_eq!(
4005            tree.release_queue.len(),
4006            1,
4007            "the unattached native handle must still be released"
4008        );
4009        scope.dispose();
4010    }
4011
4012    /// A posted closure that arrives while the tree is borrowed (a backend pumping its native
4013    /// loop from inside a tree method) must wait for the safe point rather than re-enter
4014    /// `with_tree` on the borrowed tree: the "`RefCell` already borrowed" the web view demo hit
4015    /// opening Browser Settings on WinUI while a second tab's poll kept posts in flight.
4016    #[test]
4017    fn a_post_during_a_tree_borrow_runs_at_the_safe_point() {
4018        std::thread::spawn(|| {
4019            install_probe(&Arc::new(AtomicBool::new(false)));
4020            let ran = Arc::new(AtomicBool::new(false));
4021            let r = ran.clone();
4022            with_tree(|_| {
4023                run_posted_or_defer(Box::new(move || {
4024                    // The deferred closure borrows the tree itself, as a reactive flush or an
4025                    // eval reply does; running it inside the outer borrow would panic here.
4026                    with_tree(|_| r.store(true, Ordering::SeqCst));
4027                }));
4028                assert!(!ran.load(Ordering::SeqCst), "ran inside the borrow");
4029            });
4030            assert!(
4031                ran.load(Ordering::SeqCst),
4032                "never ran after the borrow was released"
4033            );
4034            // With the tree free, the same door runs the closure immediately.
4035            let now = Arc::new(AtomicBool::new(false));
4036            let n = now.clone();
4037            run_posted_or_defer(Box::new(move || n.store(true, Ordering::SeqCst)));
4038            assert!(
4039                now.load(Ordering::SeqCst),
4040                "a post with the tree free must run at once"
4041            );
4042            uninstall_tree();
4043        })
4044        .join()
4045        .expect("thread");
4046    }
4047}