abstracttui 0.3.7

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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! Screen-text selection + clipboard copy (backlog 0270, tiers 2+3).
//!
//! Terminals in mouse-capture mode route drags to the APPLICATION, so
//! native text selection stops working the moment an app enables wheel
//! scrolling. This module ships the engine-side answers:
//!
//! - **Tier 2 — [`mouse_capture`]**: a cloneable handle that suspends and
//!   resumes mouse reporting at runtime (`set_mouse_reporting(bool)`
//!   shape). While suspended the terminal owns the pointer again — native
//!   drag-select works at native quality; keys still arrive, so apps
//!   typically resume on the next keypress.
//! - **Tier 3 — [`selection`]**: an opt-in engine selection layer. While
//!   enabled, a left-button drag paints a selection highlight (theme
//!   `selection_fg`/`selection_bg`) over the RENDERED screen; releasing
//!   the button — or pressing Enter / `c` / Ctrl+C mid-drag — copies the
//!   selected text to the system clipboard via OSC 52 through the
//!   presenter's byte custody. EVERY copy ends the gesture (backlog
//!   0290): the region clears with the copy, so the app's next
//!   Enter/`c` keystrokes route normally — a retained region used to
//!   silently eat them (the composer footgun). Esc cancels without
//!   copying; a fresh click re-anchors. Wheel scrolling is untouched.
//!
//! ## Click-through (backlog 0285)
//!
//! The layer owns the gesture only once it becomes a DRAG — a plain
//! click belongs to the widgets:
//!
//! - **Left Down with no visible region**: the anchor arms silently and
//!   the event PASSES — the widget under the pointer arms its own
//!   pressed state in parallel (a Button in select mode stays
//!   clickable; consuming every Down made every Button dead by mouse).
//! - **Left Down with a visible region**: the click DISMISSES the
//!   selection — clear and CONSUME (Esc parity: the user was clearing a
//!   highlight, not aiming at the widget beneath), and its paired Up is
//!   consumed too (a gesture is all-or-nothing to the tree).
//! - **First Drag that leaves the anchor cell**: the layer CLAIMS the
//!   gesture — from here Drag and the final Up are the layer's. The
//!   driver resolves the press the tree already saw (a release outside
//!   every rect through the pointer-capture routing), so the pressed
//!   widget un-presses WITHOUT firing and the capture drops. Drags that
//!   stay on the anchor cell remain potential clicks (terminal cell
//!   quantization is the drag slop) and keep passing.
//! - **Up with no drag (a plain click)**: passes — the widget fires.
//! - **[`copy_to_clipboard`]**: the app-reachable clipboard verb (backlog
//!   0150's clipboard leg) — queue any text for OSC 52 emission through
//!   the same custody path, from any component handler.
//!
//! ## A live selection freezes follow-tail (first-app/1300)
//!
//! The region is SCREEN space, so content that keeps scrolling under it
//! turns the copy into a lie: the highlight covers the rows the user
//! aimed at, and the release copies whatever those cells hold by then.
//! While a region is visible the layer therefore calls
//! [`widgets::scroll::freeze_follow_tail`](crate::widgets::scroll::freeze_follow_tail)
//! — every pinned `Scroll` holds its rows still, appends grow below the
//! viewport, and clearing the region (release-copy, Esc, a dismissing
//! click) re-pins to the live tail. Streaming apps need no wiring: what
//! you highlight is what you get, mid-run or idle.
//!
//! ## Honesty: this is SCREEN-text extraction
//!
//! The copied text is what the composed frame shows — glyphs from the
//! flattened cell grid, wide glyphs never split, trailing whitespace
//! trimmed per row, rows joined with `\n`. It is NOT logical widget
//! content: soft-wrapped lines copy as separate rows, and content
//! scrolled out of view cannot be selected. The logical text↔cells
//! mapping is backlog 0160's remaining scope.
//!
//! ## Selection semantics (v1)
//!
//! LINEAR row-flow over the rendered screen, like a terminal's own
//! selection: the first row runs from the anchor to the pane's right
//! edge, middle rows span the pane, the last row runs from the pane's
//! left edge to the head cell (inclusive). Both endpoints clamp to the
//! PANE under the drag anchor — the content box of the nearest clipping
//! or padded ancestor of the deepest view hit at mouse-down (a `Scroll`
//! viewport, a bordered `Block`), else the whole tree — so unrelated
//! panes and border glyphs never leak into a copy.
//!
//! ## Rendering: a post-flatten frame patch
//!
//! The highlight honors the damage contract without a dedicated layer:
//! when the region changes, the old and new row rects are damaged on the
//! root layer BEFORE compositing (the compositor recomposes truth there,
//! full z-stack), and the selection inks are patched into the composed
//! frame AFTER — glyphs kept, colors replaced — so the diff emits only
//! cells that actually changed. Zero idle cost: with no active selection
//! the per-frame hook is one borrow and two empty checks, and the event
//! hook is one `enabled` test.

use std::cell::RefCell;
use std::rc::Rc;

use crate::base::{Point, Rect, Rgba};
use crate::input::{Event, KeyCode, KeyEventKind, Mods, MouseButton, MouseKind};
use crate::reactive::request_frame;
use crate::render::{Cell, Surface};

// ---------------------------------------------------------------------------
// Thread-local stores (house pattern: app::theme / app::viewport — the app
// runs on one thread; handles are cheap Rc clones of the same state).
// ---------------------------------------------------------------------------

thread_local! {
    static SELECTION: Rc<RefCell<SelectionState>> =
        Rc::new(RefCell::new(SelectionState::default()));
    static CAPTURE: Rc<RefCell<CaptureState>> =
        Rc::new(RefCell::new(CaptureState::default()));
}

/// The app-thread [`Selection`] handle (same state the driver renders).
pub fn selection() -> Selection {
    Selection {
        state: SELECTION.with(Rc::clone),
    }
}

/// The app-thread [`MouseCapture`] handle (tier-2 suspend verb).
pub fn mouse_capture() -> MouseCapture {
    MouseCapture {
        state: CAPTURE.with(Rc::clone),
    }
}

/// Queue `text` for an OSC 52 clipboard write through the presenter's
/// byte custody — reachable from any component handler (backlog 0150's
/// clipboard leg). The driver emits it with the next frame. Empty or
/// all-whitespace text is refused (an empty OSC 52 payload CLEARS the
/// clipboard — a surprise, never a copy). Capability honesty: terminals
/// that do not advertise OSC 52 get the bytes anyway (harmless — they
/// ignore the frame) plus a one-time labeled startup notice.
pub fn copy_to_clipboard(text: impl Into<String>) {
    let text = text.into();
    if text.trim().is_empty() {
        return;
    }
    SELECTION.with(|s| s.borrow_mut().pending_copies.push(text));
    request_frame();
}

// ---------------------------------------------------------------------------
// Selection (tier 3)
// ---------------------------------------------------------------------------

/// Publish the region's liveness DOWN to the widgets layer (1300): a
/// visible region freezes every follow-tail `Scroll`, so a streaming
/// transcript holds still for the length of the drag. Screen-space
/// selection over auto-scrolling content is otherwise a copy of
/// whatever landed on those cells at release — the highlight says one
/// thing and the clipboard gets another. Called from EVERY state
/// transition that can change `region.is_some()`; the setter is
/// idempotent (`set_if_changed`), so the steady state costs nothing.
fn publish_freeze(st: &SelectionState) {
    crate::widgets::scroll::freeze_follow_tail(st.region.is_some());
}

/// One selection region: anchor + head (screen cells, both inclusive),
/// row-flowed within `clamp` (the pane rect resolved at drag start).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) struct Region {
    anchor: Point,
    head: Point,
    clamp: Rect,
}

impl Region {
    /// Endpoints in reading order (by row, then column).
    fn ordered(&self) -> (Point, Point) {
        if (self.anchor.y, self.anchor.x) <= (self.head.y, self.head.x) {
            (self.anchor, self.head)
        } else {
            (self.head, self.anchor)
        }
    }

    /// Per-row screen rects of the linear flow: first row start→pane
    /// right, middle rows the full pane span, last row pane left→end
    /// (end cell inclusive). A single-row region spans min..=max.
    pub(crate) fn row_spans(&self, out: &mut Vec<Rect>) {
        let (s, e) = self.ordered();
        for y in s.y..=e.y {
            let x0 = if y == s.y { s.x } else { self.clamp.x };
            let x1 = if y == e.y {
                e.x + 1
            } else {
                self.clamp.right()
            };
            let rect = Rect::new(x0, y, x1 - x0, 1).intersect(self.clamp);
            if !rect.is_empty() {
                out.push(rect);
            }
        }
    }
}

/// What the driver should do with an intercepted event.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum SelectionAct {
    /// Not ours: route normally.
    Pass,
    /// Consumed by the selection layer (state may have changed).
    Consumed,
    /// Consumed — and this drag just CLAIMED a gesture whose Down had
    /// passed through to the widgets (click-through, backlog 0285). The
    /// driver must resolve the trees' pointer state: deliver a release
    /// outside every rect so the pressed widget un-presses WITHOUT
    /// firing (release-inside-decides) and the pointer capture drops —
    /// otherwise the capture would wedge and route the NEXT click
    /// anywhere to the stale captured widget.
    Claim,
    /// Consumed; copy this region's screen text. The act CARRIES the
    /// region because a copy ENDS the gesture (backlog 0290): the layer
    /// cleared its own state before answering, so no region lingers to
    /// swallow the app's next Enter/`c` keystrokes.
    Copy(Region),
}

/// An armed left press: the anchor cell + the pane clamp resolved at
/// Down, and whether the Down PASSED through to the widget trees
/// (click-through, 0285). A dismissal click's Down was consumed, so its
/// whole gesture stays consumed — all-or-nothing to the tree — and a
/// claim over it releases nothing (nothing was pressed).
#[derive(Copy, Clone, Debug)]
struct DragArm {
    anchor: Point,
    clamp: Rect,
    press_routed: bool,
}

#[derive(Default)]
struct SelectionState {
    enabled: bool,
    /// Left button is down (anchor armed). No region until a drag
    /// leaves the anchor cell — a plain click never paints.
    drag: Option<DragArm>,
    region: Option<Region>,
    /// Row rects patched into the last composed frame (the repair-damage
    /// source when the region changes or clears).
    painted: Vec<Rect>,
    /// Region changed since the last paint: pre-flatten damage owed.
    dirty: bool,
    /// App-queued clipboard texts ([`copy_to_clipboard`]), drained by the
    /// driver into presenter-custody OSC 52 emission.
    pending_copies: Vec<String>,
}

/// Cloneable handle to the engine selection layer. Enabling is the
/// opt-in: apps bind a key to [`Selection::toggle`] for a "select mode",
/// or call [`Selection::set_enabled`] once for always-on drag select.
/// While enabled the layer owns left DRAGS (and the gesture-ending Up);
/// plain clicks pass through to the widgets (click-through, 0285), so
/// buttons and other clickables keep working with select mode on.
#[derive(Clone)]
pub struct Selection {
    state: Rc<RefCell<SelectionState>>,
}

impl Selection {
    /// Turn select mode on or off. Disabling clears any visible
    /// selection (its cells repaint from truth on the next frame).
    pub fn set_enabled(&self, on: bool) {
        let mut st = self.state.borrow_mut();
        if st.enabled == on {
            return;
        }
        st.enabled = on;
        if !on {
            Self::clear_locked(&mut st);
        }
    }

    /// Whether select mode is on.
    pub fn enabled(&self) -> bool {
        self.state.borrow().enabled
    }

    /// Flip select mode; returns the new state.
    pub fn toggle(&self) -> bool {
        let on = !self.enabled();
        self.set_enabled(on);
        on
    }

    /// Whether a selection region is currently visible. Since every
    /// copy ends the gesture (0290), this is true only mid-drag (and
    /// only once the drag actually painted a region — a plain click
    /// never does).
    pub fn is_active(&self) -> bool {
        self.state.borrow().region.is_some()
    }

    /// Clear the visible selection (keeps select mode on).
    pub fn clear(&self) {
        Self::clear_locked(&mut self.state.borrow_mut());
    }

    fn clear_locked(st: &mut SelectionState) {
        st.drag = None;
        if st.region.take().is_some() || !st.painted.is_empty() {
            st.dirty = true;
            request_frame();
        }
        publish_freeze(st);
    }

    // ---- driver plumbing (crate-internal) --------------------------------

    /// Route one kernel event through the selection layer. `clamp_at`
    /// resolves the pane rect under a fresh drag anchor (called at most
    /// once, on left-down). See the module docs for the claim rules —
    /// wheel, motion, and non-left buttons always pass.
    pub(crate) fn on_input(
        &self,
        ev: &Event,
        clamp_at: &mut dyn FnMut(Point) -> Rect,
    ) -> SelectionAct {
        let mut st = self.state.borrow_mut();
        match ev {
            Event::Mouse(m) => {
                if !st.enabled {
                    return SelectionAct::Pass;
                }
                match (m.kind, m.button) {
                    (MouseKind::Down, MouseButton::Left) => {
                        let dismissed = st.region.take().is_some();
                        if dismissed {
                            st.dirty = true;
                            request_frame();
                            publish_freeze(&st); // dismissal thaws the tail
                        }
                        let clamp = clamp_at(m.pos);
                        st.drag = Some(DragArm {
                            anchor: clamp_point(m.pos, clamp),
                            clamp,
                            press_routed: !dismissed,
                        });
                        if dismissed {
                            // A click on a VISIBLE selection dismisses it
                            // (Esc parity: the user was clearing the
                            // highlight, not aiming at the widget
                            // beneath): clear + CONSUME. The fresh anchor
                            // still arms — dragging from here selects.
                            SelectionAct::Consumed
                        } else {
                            // Click-through (0285): a plain click belongs
                            // to the widgets — the anchor arms silently
                            // and the Down routes on, so the widget under
                            // the pointer arms its own pressed state. The
                            // layer claims only if a drag follows.
                            SelectionAct::Pass
                        }
                    }
                    (MouseKind::Drag, MouseButton::Left) => {
                        let Some(arm) = st.drag else {
                            // Drag whose Down predates select mode: not ours.
                            return SelectionAct::Pass;
                        };
                        let head = clamp_point(m.pos, arm.clamp);
                        if st.region.is_none() && head == arm.anchor {
                            // Sub-cell wiggle: the pointer never left the
                            // anchor cell, so this is still a potential
                            // click (cell quantization is the drag slop).
                            // The gesture keeps following its Down.
                            return if arm.press_routed {
                                SelectionAct::Pass
                            } else {
                                SelectionAct::Consumed
                            };
                        }
                        let claiming = st.region.is_none();
                        let next = Region {
                            anchor: arm.anchor,
                            head,
                            clamp: arm.clamp,
                        };
                        if st.region != Some(next) {
                            st.region = Some(next);
                            st.dirty = true;
                            request_frame();
                            // The first drag off the anchor cell is the
                            // edge that freezes the tail (1300).
                            publish_freeze(&st);
                        }
                        if claiming && arm.press_routed {
                            // First drag off the anchor cell: the layer
                            // claims a gesture the tree already saw the
                            // Down of — the driver must resolve that
                            // press without a click (see `Claim`).
                            SelectionAct::Claim
                        } else {
                            SelectionAct::Consumed
                        }
                    }
                    (MouseKind::Up, MouseButton::Left) => {
                        let Some(arm) = st.drag.take() else {
                            return SelectionAct::Pass; // orphan release
                        };
                        match st.region.take() {
                            // Release copies AND ends the gesture (0290):
                            // a retained region's only remaining power
                            // was eating the app's next Enter/`c` — the
                            // copy already happened, so nothing of value
                            // is lost by clearing here. The highlight
                            // cells recompose from truth next frame.
                            Some(region) => {
                                Self::clear_locked(&mut st);
                                SelectionAct::Copy(region)
                            }
                            // A drag-less click: the gesture follows its
                            // Down — pass (the widget fires, 0285) when
                            // the Down passed; stay consumed for a
                            // dismissal click's paired release.
                            None => {
                                if arm.press_routed {
                                    SelectionAct::Pass
                                } else {
                                    SelectionAct::Consumed
                                }
                            }
                        }
                    }
                    _ => SelectionAct::Pass, // wheel / motion / other buttons
                }
            }
            Event::Key(k) => {
                // Copy/clear keys exist only while a selection is VISIBLE
                // — i.e. mid-drag now that every copy clears (Ctrl+C
                // stays the default quit otherwise).
                let Some(region) = st.region else {
                    return SelectionAct::Pass;
                };
                if k.kind == KeyEventKind::Release {
                    return SelectionAct::Pass;
                }
                let mods = k.mods.without_locks();
                match k.code {
                    KeyCode::Esc if mods == Mods::NONE => {
                        Self::clear_locked(&mut st);
                        SelectionAct::Consumed
                    }
                    // Key-copy is one-shot (0290): copy AND clear — the
                    // deliberate second act ends the gesture exactly
                    // like the release-copy does.
                    KeyCode::Enter if mods == Mods::NONE => {
                        Self::clear_locked(&mut st);
                        SelectionAct::Copy(region)
                    }
                    KeyCode::Char('c') if mods == Mods::NONE || mods == Mods::CTRL => {
                        Self::clear_locked(&mut st);
                        SelectionAct::Copy(region)
                    }
                    _ => SelectionAct::Pass,
                }
            }
            _ => SelectionAct::Pass,
        }
    }

    /// Pre-flatten hook: when the region changed since the last paint,
    /// damage the OLD painted rects (their cells must recompose from
    /// truth) and the NEW row spans (fresh truth to patch over) on the
    /// root layer surface. Root layer origin is `Point::ZERO`, so screen
    /// and layer-local coordinates coincide.
    pub(crate) fn add_flatten_damage(&self, root: &mut Surface) {
        let mut st = self.state.borrow_mut();
        if !st.dirty {
            return;
        }
        st.dirty = false;
        for &r in &st.painted {
            root.add_damage(r);
        }
        let mut spans = Vec::new();
        if let Some(region) = st.region {
            region.row_spans(&mut spans);
        }
        for r in spans {
            root.add_damage(r);
        }
    }

    /// Post-flatten hook: patch the selection inks over the composed
    /// frame — glyphs kept, `fg`/`bg` replaced — and record what was
    /// painted. Runs every rendered frame while a selection is visible;
    /// cells the compositor did not touch receive byte-identical
    /// rewrites, so the diff emits nothing for them.
    pub(crate) fn paint_into(&self, frame: &mut Surface, fg: Rgba, bg: Rgba) {
        let mut st = self.state.borrow_mut();
        let Some(region) = st.region else {
            st.painted.clear();
            return;
        };
        st.painted.clear();
        let mut spans = Vec::new();
        region.row_spans(&mut spans);
        for span in spans {
            let Some((x0, x1)) = expand_to_glyphs(frame, span) else {
                continue;
            };
            for x in x0..x1 {
                let Some(&cell) = frame.get(x, span.y) else {
                    continue;
                };
                if cell.is_continuation() {
                    continue; // the leader's inks mirror over (pair repair)
                }
                frame.put_composed(x, span.y, Cell { fg, bg, ..cell });
            }
            frame.repair_wide_pairs(span.y, x0, x1);
            st.painted.push(Rect::new(x0, span.y, x1 - x0, 1));
        }
    }

    /// App-queued clipboard texts (drained once per turn by the driver).
    pub(crate) fn take_pending_copies(&self) -> Vec<String> {
        std::mem::take(&mut self.state.borrow_mut().pending_copies)
    }

    /// Fresh-driver reset: a new session starts with no visible
    /// selection and no paint bookkeeping (the new frame is blank), but
    /// the app's mode choice (`enabled`) survives.
    pub(crate) fn reset_session(&self) {
        let mut st = self.state.borrow_mut();
        st.drag = None;
        st.region = None;
        st.painted.clear();
        st.dirty = false;
        publish_freeze(&st);
    }

    /// Resize invalidates screen-space geometry wholesale: clear the
    /// selection (the driver's prev-poison repaints everything anyway).
    pub(crate) fn on_resize(&self) {
        let mut st = self.state.borrow_mut();
        st.drag = None;
        st.region = None;
        st.painted.clear();
        st.dirty = false;
        publish_freeze(&st);
    }
}

/// Clamp `p` into `rect` (inclusive cell coordinates). An empty rect
/// clamps to its origin — callers never produce one (pane rects come
/// from solved layout, the viewport fallback is never empty).
fn clamp_point(p: Point, rect: Rect) -> Point {
    Point::new(
        p.x.clamp(rect.x, (rect.right() - 1).max(rect.x)),
        p.y.clamp(rect.y, (rect.bottom() - 1).max(rect.y)),
    )
}

/// Snap a row span outward so it never splits a wide glyph: a span
/// starting ON a continuation pulls in its leader; a span whose first
/// excluded cell is a continuation pulls it in (its leader is inside).
/// Returns the clamped `x0..x1` walk range, `None` when off-surface.
fn expand_to_glyphs(frame: &Surface, span: Rect) -> Option<(i32, i32)> {
    if span.y < 0 || span.y >= frame.height() {
        return None;
    }
    let mut x0 = span.x.max(0);
    let mut x1 = span.right().min(frame.width());
    if x1 <= x0 {
        return None;
    }
    if frame.get(x0, span.y).is_some_and(Cell::is_continuation) {
        x0 = (x0 - 1).max(0);
    }
    if x1 < frame.width() && frame.get(x1, span.y).is_some_and(Cell::is_continuation) {
        x1 += 1;
    }
    Some((x0, x1))
}

/// What-you-see text of `region` over the composed frame: glyphs resolve
/// through the frame's pool, wide glyphs render once (leader), never
/// split; blank cells read as spaces; trailing whitespace trims per row;
/// rows join with `\n`. Colors are irrelevant — the selection patch only
/// recolors, so extraction after painting reads the same glyphs.
pub(crate) fn extract_text(frame: &Surface, region: &Region) -> String {
    let mut spans = Vec::new();
    region.row_spans(&mut spans);
    let mut out = String::new();
    for (i, span) in spans.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        let row_start = out.len();
        let Some((x0, x1)) = expand_to_glyphs(frame, *span) else {
            continue;
        };
        for x in x0..x1 {
            let Some(cell) = frame.get(x, span.y) else {
                continue;
            };
            if cell.is_continuation() {
                continue; // the leader already rendered both columns
            }
            let g = frame.glyph_str(cell);
            out.push_str(if g.is_empty() { " " } else { g });
        }
        let kept = out[row_start..].trim_end().len();
        out.truncate(row_start + kept);
    }
    out
}

/// Resolve the selection PANE under a fresh drag anchor: the topmost
/// visible overlay TREE layer containing the point answers with its own
/// pane (layer-local walk, mapped back to screen) — mirrors input
/// routing, so dragging over a modal clamps to the modal — else the root
/// tree answers, else the viewport. Always clipped to the viewport;
/// degenerate (empty) panes fall back to the viewport rather than
/// producing an unselectable region.
pub(super) fn selection_pane(
    app: &mut super::App,
    overlays: &super::overlays::Overlays,
    viewport: crate::base::Size,
    p: Point,
) -> Rect {
    use super::overlays::{OverlayContent, ROOT_LAYER_ID};
    let vp = Rect::from_size(viewport);
    let mut candidates: Vec<(crate::ui::UiTree, Rect, i32)> = {
        let store = overlays.store().borrow();
        store
            .meta
            .iter()
            .zip(&store.layers)
            .filter(|(m, l)| m.id != ROOT_LAYER_ID && l.visible())
            .filter_map(|(m, l)| match &m.content {
                OverlayContent::Tree { tree, .. } => Some((tree.handle(), l.bounds(), l.z())),
                _ => None,
            })
            .collect()
    };
    candidates.sort_by_key(|(_, _, z)| std::cmp::Reverse(*z));
    for (tree, bounds, _) in candidates {
        if bounds.contains(p) {
            let local = Point::new(p.x - bounds.x, p.y - bounds.y);
            let pane = tree
                .pane_rect_at(local)
                .map(|r| r.translate(bounds.x, bounds.y))
                .unwrap_or(bounds)
                .intersect(vp);
            return if pane.is_empty() { vp } else { pane };
        }
    }
    let pane = app.tree().pane_rect_at(p).unwrap_or(vp).intersect(vp);
    if pane.is_empty() {
        vp
    } else {
        pane
    }
}

// ---------------------------------------------------------------------------
// MouseCapture (tier 2)
// ---------------------------------------------------------------------------

#[derive(Default)]
struct CaptureState {
    /// Pending request (latest wins), drained by the driver's next turn.
    requested: Option<bool>,
    /// The last requested posture (for `is_suspended`).
    suspended: bool,
}

/// Cloneable handle suspending/resuming mouse reporting at runtime — the
/// tier-2 "native selection mode" verb. While suspended, the terminal
/// owns the pointer: native drag-select (and its clipboard) works at
/// native quality, and NO mouse events reach the app; keys still arrive,
/// so the conventional shape is suspend-on-keybinding, resume on the
/// next keypress. Requests apply at the driver's next turn (embedders
/// driving their own turns can call `Driver::set_mouse_reporting`
/// directly). Platform note: a job-control `Terminal::suspend` re-enters
/// with the original options, re-arming reporting — suspend again after
/// resume if you keep it off.
#[derive(Clone)]
pub struct MouseCapture {
    state: Rc<RefCell<CaptureState>>,
}

impl MouseCapture {
    /// Request mouse reporting on (`true`, the entered posture) or off
    /// (`false`, terminal-native selection). Latest request wins.
    pub fn set_reporting(&self, on: bool) {
        let mut st = self.state.borrow_mut();
        st.requested = Some(on);
        st.suspended = !on;
        drop(st);
        // A request from a posted job must wake an idle loop; from a key
        // handler this is a no-op frame the turn was running anyway.
        request_frame();
    }

    /// `set_reporting(false)`: hand the pointer back to the terminal.
    pub fn suspend(&self) {
        self.set_reporting(false);
    }

    /// `set_reporting(true)`: re-arm the entered mouse mode.
    pub fn resume(&self) {
        self.set_reporting(true);
    }

    /// The requested posture (applied by the driver's next turn).
    pub fn is_suspended(&self) -> bool {
        self.state.borrow().suspended
    }

    /// Driver drain: the pending request, if any (latest wins).
    pub(crate) fn take_request(&self) -> Option<bool> {
        self.state.borrow_mut().requested.take()
    }
}

#[cfg(test)]
#[path = "selection_tests.rs"]
mod tests;