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