abstracttui 0.5.0

A reactive, compositor-grade terminal UI engine: fine-grained signals, layered rendering with damage tracking, images (kitty/iTerm2/sixel/mosaic), software-rasterized 3D (GLB), themes and animation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Live instance tree: damage collection, layout mirroring, hit testing,
//! focus and event routing. Mounting/unmounting (including the `Dyn`
//! reactive-region lifecycle) lives in `ui::mount`.
//!
//! ## Borrow discipline
//!
//! The instance store (`TreeCore`) sits behind `Rc<RefCell>` shared with
//! Dyn effects. NO borrow is held across user code: mounts borrow in
//! short bursts; dispatch collects handler `Rc`s first, releases, then
//! invokes. A handler may set signals, which synchronously remounts some
//! `Dyn` — the routing path re-validates instance liveness (generational
//! ids) after every handler call.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use crate::base::{Point, Rect, Rgba, Size};
use crate::layout::{solve, LayoutId, LayoutTree};
use crate::reactive::{request_frame, GenArena, Key as ArenaKey, Scope, Signal};

use super::mount::{mount_view, remove_subtree};
use super::view::{DrawFn, Handler, Shortcut, View};

/// Generational handle to a mounted view instance.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ViewId(pub(crate) ArenaKey);

pub(super) enum InstPayload {
    Element {
        draw: Option<Rc<RefCell<DrawFn>>>,
        handlers: Rc<RefCell<Vec<Handler>>>,
        shortcuts: Rc<RefCell<Vec<Shortcut>>>,
    },
    Text {
        content: String,
    },
    /// Marker node owning a reactive subtree (its single child).
    Dyn,
}

pub(super) struct Inst {
    pub(super) parent: Option<ViewId>,
    pub(super) children: Vec<ViewId>,
    pub(super) layout: LayoutId,
    pub(super) focusable: bool,
    pub(super) focus_trap: bool,
    pub(super) focus_memory: bool,
    /// Run this node's own draw even when its rect is fully outside
    /// the clip (measurement-readback probes — see
    /// [`Element::probe_when_culled`](super::Element::probe_when_culled)).
    /// Children still cull individually.
    pub(super) probe_when_culled: bool,
    /// Sub-rect of this instance that owns pointer drags, so the
    /// screen-text selection layer stands down over it (see
    /// [`Element::drag_zone`](super::Element::drag_zone)). Consulted by
    /// `UiTree::press_probe_at` at mouse-down only.
    pub(super) drag_zone: Option<super::view::DragZoneFn>,
    pub(super) access: super::access::AccessProps,
    pub(super) payload: InstPayload,
}

pub(super) struct TreeCore {
    pub(super) insts: GenArena<Inst>,
    pub(super) layout: LayoutTree,
    pub(super) root: Option<ViewId>,
    pub(super) viewport: Size,
    pub(super) damage: Vec<Rect>,
    pub(super) needs_layout: bool,
    pub(super) focus: Option<ViewId>,
    /// Default color for text leaves; the app sets it from the active
    /// theme's `Text` token (widgets with opinions style themselves).
    pub(super) text_fg: Rgba,
    /// Root-to-deepest path of instances currently under the pointer.
    /// Membership = "hovered" (ancestors included, DOM mouseenter model).
    pub(super) hovered_path: Vec<ViewId>,
    /// Pointer capture: all mouse events route here until release.
    pub(super) capture: Option<ViewId>,
    /// The screen cell of the press that armed the capture — the HEAL
    /// anchor: a pressed widget's own visual re-render can dispose the
    /// captured instance (Button's pressed `dyn_view` regenerates its
    /// hit leaf on the very Down that captured it); the capture then
    /// re-points at this cell's current occupant instead of silently
    /// dying (which stranded the widget's pressed state whenever the
    /// release landed outside it).
    pub(super) capture_pos: Option<Point>,
    /// Hover memo: last pointer position + the layout epoch it was
    /// hit-tested against. Any-motion mouse streams (mode 1003) repeat
    /// positions heavily; skipping the hit-test walk when neither moved
    /// makes hover O(1) for repeats.
    pub(super) last_hover: Option<(Point, u64)>,
    /// Bumped every time layout actually re-solves (same-position hits
    /// can change when geometry did).
    pub(super) layout_epoch: u64,
    /// Incremental re-solve anchors (style_signal changes): each entry's
    /// SUBTREE re-solves within its current box — a scroll drag pays for
    /// its own container, not the screen. A full `needs_layout` solve
    /// supersedes them.
    pub(super) dirty_subtrees: Vec<LayoutId>,
    /// Last-focused descendant per memory container (focus restore).
    pub(super) focus_memory: std::collections::HashMap<ViewId, ViewId>,
    /// Autofocus node recorded during mount, consumed OUTSIDE every
    /// computation: by `UiTree::mount` after the initial mount returns,
    /// or by `UiTree::layout` (frame phase L) for nodes mounted inside a
    /// `Dyn` effect run. Focus delivery runs user handlers whose signal
    /// writes would re-enter a running computation if fired inline
    /// (the 0220 mount-time "dependency cycle" panic).
    pub(super) pending_autofocus: Option<ViewId>,
    /// Multi-click synthesis (`ui::click`): one chain per tree, folded
    /// on every dispatched mouse event; handlers read the result via
    /// `EventCtx::click_count`. Positional identity, deliberately not
    /// ViewId identity — selection-driven re-renders dispose and remount
    /// the very instance a click hit (List/Table regenerate their
    /// `dyn_view` on click 1), so instance comparison would reset the
    /// chain on exactly the presses that should chain.
    pub(super) click_chain: super::click::ClickChain,
    /// SCREEN origin of the layer this tree is mounted on
    /// (`Point::ZERO` for the root tree and bare trees). Overlay trees
    /// lay out LAYER-LOCAL — the compositor applies the origin at
    /// paint — so anchor captures that feed viewport-space APIs
    /// (`app::anchored::place_panel`) must translate by this. The
    /// overlay store maintains it (layer creation + every
    /// `LayerHandle::set_offset`: modal re-clamps and drawer slides
    /// move mounted trees).
    pub(super) layer_origin: Point,
    /// Elements publishing their own solved rect (`Element::rect_signal`,
    /// field-agora 0910). Read at the END of every solve, which is the
    /// only phase that knows a rect changed — paint cannot be the hook
    /// because the interesting child is the culled one.
    pub(super) rect_probes: Vec<RectProbe>,
}

/// A rect publish that the solve just made due, held OUTSIDE the tree
/// borrow so the timer it arms cannot re-enter the core.
pub(super) struct PendingRectPublish {
    sig: Signal<Option<Rect>>,
    seen: Rc<Cell<Option<Rect>>>,
    pending: Rc<Cell<bool>>,
    alive: Rc<Cell<bool>>,
}

impl PendingRectPublish {
    /// Deferred by one tick, exactly like `scroll::size_probe`: the
    /// value is read LATE (so a burst of solves publishes once, with the
    /// newest rect) and the write lands outside the layout pass that
    /// produced it.
    fn schedule(self) {
        let PendingRectPublish {
            sig,
            seen,
            pending,
            alive,
        } = self;
        crate::reactive::after(std::time::Duration::ZERO, move || {
            pending.set(false);
            // The ELEMENT decides whether this publishes at all. Its
            // signal being alive proves nothing here — the caller owns
            // it and re-binds it across rebuilds, so a disposed child
            // would happily write its rect over the live one's and the
            // consumer would read a corpse (field-agora 0910).
            if !alive.get() || sig.try_get_untracked().is_none() {
                return;
            }
            // A zero-area solve is CLEAN ABSENCE, not a position: it
            // falls through the paint cull and paints nothing, and a
            // clamp fed `0x0` scrolls to the origin. `None` says the
            // thing that is true.
            sig.set_if_changed(seen.get().filter(|r| !r.is_empty()));
        });
    }
}

/// Read every live rect binding against the solve that just finished,
/// arming a publish for each one whose rect actually moved.
fn collect_rect_publishes(core: &mut TreeCore) -> Vec<PendingRectPublish> {
    if core.rect_probes.is_empty() {
        return Vec::new();
    }
    core.rect_probes.retain(|p| p.alive.get());
    let mut out = Vec::new();
    for probe in &core.rect_probes {
        let Some(inst) = core.insts.get(probe.view.0) else {
            continue;
        };
        let rect = core.layout.rect(inst.layout);
        if probe.seen.get() == Some(rect) {
            continue; // steady frame: no timer, no write
        }
        probe.seen.set(Some(rect));
        if probe.pending.replace(true) {
            continue; // one in flight; it will read the newest value
        }
        out.push(PendingRectPublish {
            sig: probe.sig,
            seen: probe.seen.clone(),
            pending: probe.pending.clone(),
            alive: probe.alive.clone(),
        });
    }
    out
}

/// One `rect_signal` binding: an element, the caller's signal, and the
/// state a deferred publish needs after the tree borrow is released.
pub(super) struct RectProbe {
    pub(super) view: ViewId,
    pub(super) sig: Signal<Option<Rect>>,
    /// Last rect the solver produced for this element, or `None` before
    /// the first solve. The deferred publish reads it LATE, so several
    /// solves inside one tick collapse to the newest value.
    pub(super) seen: Rc<Cell<Option<Rect>>>,
    /// One publish in flight at a time.
    pub(super) pending: Rc<Cell<bool>>,
    /// Liveness of the ELEMENT — deliberately not of the signal. The
    /// signal is the CALLER's and outlives every element it is re-bound
    /// to, so "the signal is alive" is a question that says nothing
    /// about whether this element still exists.
    pub(super) alive: Rc<Cell<bool>>,
}

impl TreeCore {
    /// Push a damage rect, deduplicating containment both ways (RT2-4:
    /// one Dyn remount used to feed three identical rects — dispose
    /// damage, remount damage and the new leaf's geometry damage all
    /// cover the same region). The list is small between takes, so the
    /// linear scan costs less than the triple translation it saves.
    pub(super) fn damage_rect(&mut self, rect: Rect) {
        if rect.is_empty() {
            return;
        }
        if self.damage.iter().any(|r| r.intersect(rect) == rect) {
            return; // already covered
        }
        self.damage.retain(|r| rect.intersect(*r) != *r); // drop swallowed
        self.damage.push(rect);
    }

    pub(super) fn damage_all(&mut self) {
        let full = Rect::from_size(self.viewport);
        self.damage.push(full);
    }
}

/// The mounted UI. One per app window/screen.
pub struct UiTree {
    /// Shared with Dyn effects and the `ui::focus` split (same type,
    /// second file) — never borrowed across user code.
    pub(super) core: Rc<RefCell<TreeCore>>,
}

impl UiTree {
    pub fn new(viewport: Size) -> UiTree {
        UiTree {
            core: Rc::new(RefCell::new(TreeCore {
                insts: GenArena::new(),
                layout: LayoutTree::new(),
                root: None,
                viewport,
                damage: Vec::new(),
                needs_layout: false,
                focus: None,
                text_fg: Rgba::WHITE,
                hovered_path: Vec::new(),
                capture: None,
                capture_pos: None,
                last_hover: None,
                layout_epoch: 0,
                dirty_subtrees: Vec::new(),
                focus_memory: std::collections::HashMap::new(),
                pending_autofocus: None,
                click_chain: super::click::ClickChain::new(),
                layer_origin: Point::ZERO,
                rect_probes: Vec::new(),
            })),
        }
    }

    /// Default text color (theme `Text` token). The app re-sets this when
    /// the theme signal changes and damages the whole tree.
    pub fn set_text_fg(&mut self, fg: Rgba) {
        self.core.borrow_mut().text_fg = fg;
    }

    /// A second handle onto the SAME tree (shared core) — the overlay
    /// store keeps trees while the driver drives them without moving
    /// ownership around. Not a copy: both handles see every mutation.
    pub fn handle(&self) -> UiTree {
        UiTree {
            core: self.core.clone(),
        }
    }

    /// Viewport size (accessibility hook + diagnostics).
    pub fn viewport_size(&self) -> Size {
        self.core.borrow().viewport
    }

    /// Snapshot the SEMANTIC tree: annotated nodes (role/label/value)
    /// and text leaves, preorder, with focus and solved bounds. This is
    /// the accessibility model — see `ui::access` for the honesty
    /// contract (in-engine substrate; no platform bridge yet).
    pub fn accessibility_tree(&mut self) -> super::access::AccessSnapshot {
        self.layout(); // bounds must be truthful
        let core = self.core.borrow();
        let mut snapshot = super::access::AccessSnapshot::default();
        let Some(root) = core.root else {
            return snapshot;
        };
        // The focused node's ANNOTATED self-or-ancestor carries the
        // focus mark (a focused inner leaf announces as its widget).
        let focus_carrier = core.focus.map(|f| {
            let mut cur = f;
            loop {
                let Some(inst) = core.insts.get(cur.0) else {
                    break cur;
                };
                let annotated =
                    !inst.access.is_empty() || matches!(inst.payload, InstPayload::Text { .. });
                if annotated {
                    break cur;
                }
                match inst.parent {
                    Some(p) => cur = p,
                    None => break cur,
                }
            }
        });
        // Iterative preorder with annotated-only depth.
        let mut stack: Vec<(ViewId, usize)> = vec![(root, 0)];
        while let Some((id, depth)) = stack.pop() {
            let Some(inst) = core.insts.get(id.0) else {
                continue;
            };
            let mut child_depth = depth;
            let entry = match &inst.payload {
                InstPayload::Text { content } if !content.is_empty() => {
                    Some(super::access::AccessEntry {
                        role: super::access::Role::Text,
                        label: content.clone(),
                        value: None,
                        focused: focus_carrier == Some(id),
                        bounds: core.layout.rect(inst.layout),
                        depth,
                    })
                }
                _ if !inst.access.is_empty() => {
                    let a = &inst.access;
                    // Value closures are app code over live signals; a
                    // closure whose data was disposed must not kill the
                    // snapshot (RT6 risk 11). `try_get_untracked` is the
                    // endorsed read; the unwind guard is the backstop
                    // for closures that panicked anyway.
                    let value = a.value.as_ref().map(|f| {
                        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f()))
                            .unwrap_or_else(|_| "<stale>".into())
                    });
                    Some(super::access::AccessEntry {
                        role: a.role.unwrap_or(super::access::Role::Region),
                        label: a.label.clone().unwrap_or_default(),
                        value,
                        focused: focus_carrier == Some(id),
                        bounds: core.layout.rect(inst.layout),
                        depth,
                    })
                }
                _ => None,
            };
            if let Some(e) = entry {
                snapshot.entries.push(e);
                child_depth += 1;
            }
            // Reverse push keeps document order under the pop.
            for &child in inst.children.iter().rev() {
                stack.push((child, child_depth));
            }
        }
        snapshot
    }

    /// Text serialization of [`UiTree::accessibility_tree`] — the
    /// assertable/debug-dump form (`--a11y`-style dumps print this).
    pub fn accessibility_tree_text(&mut self) -> String {
        self.accessibility_tree().to_text()
    }

    /// Short alias of [`UiTree::accessibility_tree`].
    pub fn a11y_tree(&mut self) -> super::access::AccessSnapshot {
        self.accessibility_tree()
    }

    /// What a focus change should ANNOUNCE: the focused entry's role +
    /// label + value ("button \"Save\"", "input \"Search\" = \"foo\"").
    /// None when nothing is focused or the focused subtree carries no
    /// semantics (which the a11y audit should treat as a finding).
    pub fn focus_announcement(&mut self) -> Option<String> {
        let snapshot = self.accessibility_tree();
        let e = snapshot.focused()?;
        let mut out = e.role.as_str().to_string();
        if !e.label.is_empty() {
            out.push_str(&format!(" \"{}\"", e.label));
        }
        if let Some(v) = &e.value {
            out.push_str(&format!(" = \"{v}\""));
        }
        Some(out)
    }

    /// Shortcuts reachable from the CURRENT focus: the focused node's
    /// own, then each ancestor's, up to the root (the keymap-resolution
    /// order, §12a). No focus = the root's shortcuts. Feed for
    /// keymap-help overlays; unlabeled entries render as bare chords.
    pub fn keymap_of_focus_path(&self) -> Vec<(super::event::KeyChord, Option<String>)> {
        let core = self.core.borrow();
        let start = core.focus.or(core.root);
        let mut out = Vec::new();
        let mut cur = start;
        while let Some(id) = cur {
            let Some(inst) = core.insts.get(id.0) else {
                break;
            };
            if let InstPayload::Element { shortcuts, .. } = &inst.payload {
                for s in shortcuts.borrow().iter() {
                    out.push((s.chord, s.label.clone()));
                }
            }
            cur = inst.parent;
        }
        out
    }

    /// A standalone "repaint everything" handle for effects (the app's
    /// theme watcher). Captures the shared core, not `&mut self`, so it
    /// can live inside a reactive closure.
    pub fn invalidator(&self) -> impl Fn() + 'static {
        let core = Rc::downgrade(&self.core);
        move || {
            if let Some(core) = core.upgrade() {
                let mut c = core.borrow_mut();
                c.damage_all();
                c.needs_layout = true;
                drop(c);
                request_frame();
            }
        }
    }

    /// Mount `view` as the root, owned by `cx`. Disposing `cx` unmounts
    /// everything — the root subtree via the cleanup registered here,
    /// `Dyn` subtrees via their own generation cleanups. There is no
    /// separate unmount API: lifecycle is single-sourced in scopes.
    pub fn mount(&mut self, cx: Scope, view: View) -> ViewId {
        let id = mount_view(&self.core, cx, view, None);
        let core_for_cleanup = self.core.clone();
        cx.on_cleanup(move || remove_subtree(&core_for_cleanup, id));
        {
            let mut core = self.core.borrow_mut();
            core.root = Some(id);
            core.needs_layout = true;
            core.damage_all();
        }
        // Initial-focus policy: an autofocus node wins (even one mounted
        // by a nested Dyn effect — its request parked; this is the safe
        // consume point, outside every computation); apps without one
        // call focus_first() explicitly.
        self.deliver_pending_autofocus();
        request_frame();
        id
    }

    pub fn set_viewport(&mut self, size: Size) {
        let mut core = self.core.borrow_mut();
        core.viewport = size;
        core.needs_layout = true;
        core.damage_all();
        drop(core);
        request_frame();
    }

    /// Solve layout if anything changed since last solve. Structural
    /// changes (mount/viewport/theme) re-solve the whole tree; a
    /// style_signal change re-solves only its anchor SUBTREE (the
    /// nearest ancestor whose own size cannot be affected — see
    /// `mount.rs`), which is what makes a 60fps scroll drag pay for its
    /// container instead of the screen. Cheap when clean.
    ///
    /// Also the delivery point for autofocus nodes mounted inside `Dyn`
    /// Drain the layout solver's zero-collapse diagnostics (debug
    /// builds; empty in release). The driver forwards these into the
    /// startup-notices lane each frame — the solver itself never
    /// touches stderr while a session may own the terminal.
    pub(crate) fn take_collapse_notices(&mut self) -> Vec<String> {
        self.core.borrow_mut().layout.take_collapse_notices()
    }

    /// effect runs: layout is called outside every computation (frame
    /// phase L, dispatch entry, draw), so the parked focus request can
    /// run its FocusIn handlers — and any re-render those trigger folds
    /// into this very solve.
    pub fn layout(&mut self) {
        self.deliver_pending_autofocus();
        let mut core = self.core.borrow_mut();
        let full = core.needs_layout;
        let dirty: Vec<LayoutId> = std::mem::take(&mut core.dirty_subtrees);
        if !full && dirty.is_empty() {
            return;
        }
        core.layout_epoch += 1; // same-position hover memos invalidate
        core.needs_layout = false;
        let Some(root) = core.root else { return };
        let root_layout = match core.insts.get(root.0) {
            Some(inst) => inst.layout,
            None => return,
        };
        let viewport = Rect::from_size(core.viewport);
        if full {
            // A full solve covers every dirty subtree too.
            solve(&mut core.layout, root_layout, viewport);
        } else {
            for anchor in dirty {
                if core.layout.is_alive(anchor) {
                    crate::layout::resolve_subtree(&mut core.layout, anchor);
                }
            }
        }
        // Nodes the solver actually moved/resized are damage even though
        // their own content never changed (a sibling growing pushes them).
        for rect in core.layout.take_geometry_damage() {
            core.damage_rect(rect);
        }
        // Rect bindings read the solve that just happened. Scheduling
        // happens OUTSIDE the borrow: a publish runs caller effects.
        let scheduled = collect_rect_publishes(&mut core);
        drop(core);
        for probe in scheduled {
            probe.schedule();
        }
    }

    /// Damage accumulated since last take (deduplicated coarsely by the
    /// caller/compositor; we keep raw rects here).
    pub fn take_damage(&mut self) -> Vec<Rect> {
        std::mem::take(&mut self.core.borrow_mut().damage)
    }

    /// True when a frame has work: pending damage or an unsolved layout.
    pub fn has_pending_work(&self) -> bool {
        let core = self.core.borrow();
        !core.damage.is_empty() || core.needs_layout
    }

    pub fn needs_layout(&self) -> bool {
        self.core.borrow().needs_layout
    }

    pub fn instance_count(&self) -> usize {
        self.core.borrow().insts.live()
    }

    pub fn rect_of(&self, id: ViewId) -> Rect {
        let core = self.core.borrow();
        core.insts
            .get(id.0)
            .map(|i| core.layout.rect(i.layout))
            .unwrap_or(Rect::ZERO)
    }

    /// The SCREEN origin of the layer this tree is mounted on —
    /// `Point::ZERO` for the root tree and bare trees. Every rect this
    /// tree solves or reports (`rect_of`, `EventCtx::current_rect`,
    /// draw closure rects) is LAYER-LOCAL; translating by this yields
    /// screen cells. See [`UiTree::set_layer_origin`].
    pub fn layer_origin(&self) -> Point {
        self.core.borrow().layer_origin
    }

    /// Declare the SCREEN origin of the layer this tree is mounted on.
    /// The engine's overlay store maintains this automatically (at
    /// layer creation and on every `LayerHandle::set_offset` — modal
    /// re-clamps and drawer slides move whole mounted worlds); apps
    /// embedding a `UiTree` on a custom positioned surface set it so
    /// screen-space anchor captures (`EventCtx::current_rect_screen`,
    /// the ambient [`layer_origin`]) stay truthful. Pure bookkeeping:
    /// no damage, no layout, no frame request.
    pub fn set_layer_origin(&mut self, origin: Point) {
        self.core.borrow_mut().layer_origin = origin;
    }

    pub fn focused(&self) -> Option<ViewId> {
        self.core.borrow().focus
    }

    // Hit testing, hover, pointer capture, and event dispatch live in
    // a `#[path]` sibling (file-size split): see tree_dispatch.rs —
    // same impl, different file.
}

#[path = "tree_dispatch.rs"]
mod dispatch;

pub use dispatch::PressProbe;

// ---------------------------------------------------------------------------
// Ambient layer origin (the event-time pattern, `ui::click`): draw
// closures have a fixed signature and cannot receive the origin as a
// parameter, so the tree PUBLISHES it around its draw walk (and around
// dispatch, so effects flushed at the batch close see it too). Widgets
// capturing anchor rects at draw time read it to store SCREEN cells —
// the select family's programmatic-open anchors ride this.
// ---------------------------------------------------------------------------

thread_local! {
    /// The publishing tree's layer origin; `Point::ZERO` when no tree
    /// is drawing/dispatching (bare direct-driven trees ARE at origin).
    static AMBIENT_LAYER_ORIGIN: std::cell::Cell<Point> = const { std::cell::Cell::new(Point::ZERO) };
}

/// The SCREEN origin of the layer whose tree is currently drawing or
/// dispatching — `Point::ZERO` on the root layer and outside those
/// windows. Draw closures capturing anchor rects translate by this to
/// store screen cells (`rect.translate(o.x, o.y)`); event handlers
/// should prefer [`EventCtx::layer_origin`](super::EventCtx::layer_origin)
/// / [`EventCtx::current_rect_screen`](super::EventCtx::current_rect_screen),
/// which carry the same truth on the context.
pub fn layer_origin() -> Point {
    AMBIENT_LAYER_ORIGIN.with(|c| c.get())
}

/// Publish `origin` for the duration of the returned guard (draw walk /
/// dispatch of one tree); restores the previous value on drop, so
/// nested publications (a draw-closure overlay painted while another
/// tree's value is live) stay balanced.
pub(crate) fn publish_layer_origin(origin: Point) -> LayerOriginGuard {
    AMBIENT_LAYER_ORIGIN.with(|c| LayerOriginGuard {
        prev: c.replace(origin),
    })
}

pub(crate) struct LayerOriginGuard {
    prev: Point,
}

impl Drop for LayerOriginGuard {
    fn drop(&mut self) {
        AMBIENT_LAYER_ORIGIN.with(|c| c.set(self.prev));
    }
}