Skip to main content

day_core/
tree.rs

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