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