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