abstracttui 0.2.3

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
//! Screen-text selection + copy acceptance (backlog 0270), driven
//! through the REAL pipeline: `app::Driver` frames against a
//! `CaptureTerm`, SGR mouse bytes in, VtScreen cells + OSC 52 capture
//! out. Also pins the tier-2 mouse-reporting suspend verb's byte pairs
//! and the damage containment of a drag.

use abstracttui::app::selection::{copy_to_clipboard, mouse_capture, selection};
use abstracttui::app::{current_theme, Driver, RunConfig};
use abstracttui::prelude::*;
use abstracttui::term::Capabilities;
use abstracttui::testing::CaptureTerm;
use abstracttui::ui::{text, Element};

/// RFC 4648 base64 of `s` — the test's own oracle for OSC 52 payloads
/// (the engine's encoder is deliberately not imported: two independent
/// implementations must agree).
fn b64(s: &str) -> String {
    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let d = s.as_bytes();
    let mut out = String::new();
    for c in d.chunks(3) {
        let n = (u32::from(c[0]) << 16)
            | (u32::from(*c.get(1).unwrap_or(&0)) << 8)
            | u32::from(*c.get(2).unwrap_or(&0));
        out.push(T[(n >> 18) as usize & 63] as char);
        out.push(T[(n >> 12) as usize & 63] as char);
        out.push(if c.len() > 1 {
            T[(n >> 6) as usize & 63] as char
        } else {
            '='
        });
        out.push(if c.len() > 2 {
            T[n as usize & 63] as char
        } else {
            '='
        });
    }
    out
}

fn caps() -> Capabilities {
    let mut c = Capabilities::default();
    c.truecolor = true;
    c.osc52_copy = true;
    c
}

/// Row `y` of the modeled screen (plain text, trailing blanks trimmed).
fn row(term: &CaptureTerm, y: usize) -> String {
    let dump = term.screen().to_text();
    dump.lines().nth(y).unwrap_or_default().to_string()
}

fn cfg() -> RunConfig {
    RunConfig {
        caps: Some(caps()),
        probe: false,
        ..RunConfig::default()
    }
}

/// Three known text rows in a plain column (no panes: the whole tree is
/// one pane, so multi-row drags flow across rows).
fn three_rows(size: Size) -> App {
    let mut app = App::new(size);
    app.mount(|_cx| {
        Element::new()
            .style(LayoutStyle::column())
            .child(text("alpha beta"))
            .child(text("gamma delta"))
            .child(text("third line"))
            .build()
    })
    .unwrap();
    app
}

#[test]
fn drag_paints_highlight_and_copy_key_emits_osc52() {
    let size = Size::new(30, 6);
    let mut app = three_rows(size);
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    selection().set_enabled(true);
    driver.turn(&mut app, &mut term).unwrap(); // first paint

    let sel_bg = current_theme().tokens.get(TokenId::SelectionBg);
    let before = term.screen().cell(0, 0).unwrap().paint.bg;
    assert_ne!(before, Some(sel_bg), "precondition: no highlight yet");

    // Left-down at cell (0,0), drag to cell (4,0): selects "alpha".
    term.push_input(b"\x1b[<0;1;1M");
    term.push_input(b"\x1b[<32;5;1M");
    driver.turn(&mut app, &mut term).unwrap();

    // The highlight is REAL frame content: VtScreen sees selection_bg on
    // every selected cell, and the glyphs are unchanged.
    for x in 0..=4 {
        let cell = term.screen().cell(x, 0).unwrap();
        assert_eq!(
            cell.paint.bg,
            Some(sel_bg),
            "cell {x} must carry the selection ink"
        );
    }
    assert_eq!(term.screen().cell(5, 0).unwrap().paint.bg, before);
    assert!(row(&term, 0).starts_with("alpha beta"));

    // Copy key: exactly the selected text rides OSC 52 (clipboard `c`).
    term.push_input(b"c");
    driver.turn(&mut app, &mut term).unwrap();
    assert_eq!(
        term.screen().clipboard(),
        Some(("c", b64("alpha").as_str()))
    );
    assert_eq!(term.screen().unknown_seq_count(), 0);
}

#[test]
fn release_copies_multi_row_and_clears_highlight() {
    let size = Size::new(30, 6);
    let mut app = three_rows(size);
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    selection().set_enabled(true);
    driver.turn(&mut app, &mut term).unwrap();

    // Drag from "gamma"'s g (0,1) down to (4,2): highlight paints.
    term.push_input(b"\x1b[<0;1;2M");
    term.push_input(b"\x1b[<32;5;3M");
    driver.turn(&mut app, &mut term).unwrap();
    let sel_bg = current_theme().tokens.get(TokenId::SelectionBg);
    assert_eq!(term.screen().cell(2, 1).unwrap().paint.bg, Some(sel_bg));

    // Release: row-flow copy — row 1 from the anchor to the pane's right
    // edge (trailing blanks trim), row 2 from the pane's left edge to
    // the head inclusive.
    term.push_input(b"\x1b[<0;5;3m"); // release copies
    driver.turn(&mut app, &mut term).unwrap();
    driver.turn(&mut app, &mut term).unwrap(); // custody emission frame
    let expected = b64("gamma delta\nthird");
    assert_eq!(term.screen().clipboard(), Some(("c", expected.as_str())));

    // The copy ENDS the gesture (0290): the highlight clears itself and
    // the cells recompose from truth (original inks restored) — no
    // click/Esc needed, and no region lingers to swallow keys.
    assert_ne!(
        term.screen().cell(2, 1).unwrap().paint.bg,
        Some(sel_bg),
        "the release-copy must clear the highlight"
    );
    assert!(row(&term, 1).starts_with("gamma delta"));
}

#[test]
fn ctrl_c_copies_with_selection_and_quits_without() {
    let size = Size::new(20, 4);
    let mut app = three_rows(size);
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    selection().set_enabled(true);
    driver.turn(&mut app, &mut term).unwrap();

    // Mid-drag selection: Ctrl+C is COPY (terminal muscle memory), not
    // quit — and the copy ends the gesture (0290).
    term.push_input(b"\x1b[<0;1;1M");
    term.push_input(b"\x1b[<32;5;1M");
    driver.turn(&mut app, &mut term).unwrap();
    term.push_input(b"\x03");
    let turn = driver.turn(&mut app, &mut term).unwrap();
    assert!(!turn.quit, "Ctrl+C with a visible selection copies");
    assert_eq!(
        term.screen().clipboard(),
        Some(("c", b64("alpha").as_str()))
    );
    assert!(
        !selection().is_active(),
        "the Ctrl+C copy cleared the region (0290)"
    );

    // Region gone: the NEXT Ctrl+C is the default quit again — no
    // click/Esc dance in between (the 0290 footgun, inverted).
    term.push_input(b"\x03");
    let turn = driver.turn(&mut app, &mut term).unwrap();
    assert!(turn.quit, "no selection: default quit restored");
}

/// Backlog 0290 regression: after a release-copy the app owns its keys
/// again IMMEDIATELY. The field failure: the retained region swallowed
/// every `c`/Enter (typing "cargo check" into a composer lost both
/// `c`s; Enter submitted nothing) until a click/Esc — with no effective
/// app-side workaround, because the selection layer consumes those keys
/// before tree dispatch.
#[test]
fn release_copy_frees_enter_and_c_for_the_app() {
    let size = Size::new(30, 6);
    let mut app = App::new(size);
    // Composer-shaped fixture: the root counts the Key/Wheel events
    // that actually REACH tree dispatch.
    let keys: std::rc::Rc<std::cell::RefCell<Vec<char>>> =
        std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
    let wheels: std::rc::Rc<std::cell::RefCell<u32>> = std::rc::Rc::new(std::cell::RefCell::new(0));
    let (k, w) = (keys.clone(), wheels.clone());
    app.mount(move |_cx| {
        Element::new()
            .on(abstracttui::ui::Phase::Bubble, move |_c, e| match e {
                abstracttui::ui::UiEvent::Key(key) => {
                    let ch = match key.key {
                        abstracttui::ui::Key::Char(c) => c,
                        abstracttui::ui::Key::Enter => '\n',
                        _ => '?',
                    };
                    k.borrow_mut().push(ch);
                }
                abstracttui::ui::UiEvent::Mouse(m) => {
                    if matches!(
                        m.kind,
                        abstracttui::ui::MouseKind::ScrollUp
                            | abstracttui::ui::MouseKind::ScrollDown
                    ) {
                        *w.borrow_mut() += 1;
                    }
                }
                _ => {}
            })
            .child(text("alpha beta"))
            .child(text("gamma delta"))
            .build()
    })
    .unwrap();
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    selection().set_enabled(true);
    driver.turn(&mut app, &mut term).unwrap();

    // Drag "alpha", release: the copy fires and the gesture ends.
    term.push_input(b"\x1b[<0;1;1M");
    term.push_input(b"\x1b[<32;5;1M");
    term.push_input(b"\x1b[<0;5;1m");
    driver.turn(&mut app, &mut term).unwrap();
    driver.turn(&mut app, &mut term).unwrap(); // custody emission
    assert_eq!(
        term.screen().clipboard(),
        Some(("c", b64("alpha").as_str()))
    );
    assert!(!selection().is_active(), "release-copy clears the region");

    // Typing "c" then Enter goes to the APP — the exact keystrokes the
    // retained region used to eat. The clipboard must NOT change (no
    // silent re-copy).
    term.push_input(b"c");
    term.push_input(b"\r");
    driver.turn(&mut app, &mut term).unwrap();
    assert_eq!(
        keys.borrow().as_slice(),
        &['c', '\n'],
        "post-copy keys must reach tree dispatch"
    );
    assert_eq!(
        term.screen().clipboard(),
        Some(("c", b64("alpha").as_str())),
        "no re-copy: the clipboard still holds the release copy"
    );

    // Wheel routing is untouched by any of this.
    term.push_input(b"\x1b[<65;2;2M");
    driver.turn(&mut app, &mut term).unwrap();
    assert_eq!(*wheels.borrow(), 1, "wheel still reaches the tree");
}

#[test]
fn wheel_scrolling_keeps_working_while_selection_is_enabled() {
    let size = Size::new(20, 3);
    let mut app = App::new(size);
    app.mount(|cx| {
        let content = Element::new()
            .style(LayoutStyle::column())
            .child(text("line 0"))
            .child(text("line 1"))
            .child(text("line 2"))
            .child(text("line 3"))
            .child(text("line 4"))
            .child(text("line 5"))
            .build();
        Scroll::new(content).view(cx)
    })
    .unwrap();
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    selection().set_enabled(true);
    driver.turn(&mut app, &mut term).unwrap();
    assert!(term.screen().to_text().contains("line 0"));

    // Wheel-down over the scroll: selection must NOT claim it.
    term.push_input(b"\x1b[<65;2;2M");
    driver.turn(&mut app, &mut term).unwrap();
    let after = term.screen().to_text();
    assert!(
        !after.contains("line 0") && after.contains("line 3"),
        "wheel must still scroll: {after}"
    );
}

#[test]
fn drag_damage_stays_bounded() {
    let size = Size::new(80, 24);
    let mut app = three_rows(size);
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    selection().set_enabled(true);
    driver.turn(&mut app, &mut term).unwrap();
    let full_paint = term.take_bytes().len();

    // One-row drag: the emitted bytes must be a small fraction of a full
    // repaint (damage containment — only the selected span recomposes).
    term.push_input(b"\x1b[<0;1;1M");
    term.push_input(b"\x1b[<32;10;1M");
    driver.turn(&mut app, &mut term).unwrap();
    let drag_bytes = term.take_bytes().len();
    assert!(
        drag_bytes * 4 < full_paint,
        "drag repaint must stay bounded: {drag_bytes} vs full {full_paint}"
    );

    // Extending the drag by a few cells is smaller still.
    term.push_input(b"\x1b[<32;14;1M");
    driver.turn(&mut app, &mut term).unwrap();
    let extend_bytes = term.take_bytes().len();
    assert!(
        extend_bytes <= drag_bytes,
        "extension repaints at most the delta rows: {extend_bytes} vs {drag_bytes}"
    );
}

#[test]
fn suspend_verb_emits_exact_disarm_and_rearm_pairs() {
    let size = Size::new(20, 4);
    let mut app = three_rows(size);
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    driver.turn(&mut app, &mut term).unwrap();
    let _ = term.take_bytes();

    // Handle path: request applies on the next turn.
    mouse_capture().suspend();
    driver.turn(&mut app, &mut term).unwrap();
    let bytes = term.take_bytes();
    let disarm = b"\x1b[?1006l\x1b[?1002l";
    assert!(
        bytes.windows(disarm.len()).any(|w| w == disarm),
        "suspend must disarm SGR encoding then tracking: {:?}",
        String::from_utf8_lossy(&bytes)
    );
    assert!(!term.screen().modes().is_set(1002), "tracking mode off");
    assert!(!term.screen().modes().sgr_mouse(), "SGR encoding off");
    assert!(mouse_capture().is_suspended());

    mouse_capture().resume();
    driver.turn(&mut app, &mut term).unwrap();
    let bytes = term.take_bytes();
    let arm = b"\x1b[?1002h\x1b[?1006h";
    assert!(
        bytes.windows(arm.len()).any(|w| w == arm),
        "resume must re-arm tracking then SGR encoding: {:?}",
        String::from_utf8_lossy(&bytes)
    );
    assert!(term.screen().modes().is_set(1002));
    assert!(term.screen().modes().sgr_mouse());
    assert!(!mouse_capture().is_suspended());

    // Immediate form for embedders (no turn needed).
    driver.set_mouse_reporting(&mut term, false).unwrap();
    let bytes = term.take_bytes();
    assert!(bytes.windows(disarm.len()).any(|w| w == disarm));

    // Leave still restores unconditionally (disarm rides leave_bytes).
    driver.finish(&mut term).unwrap();
    assert!(!term.screen().modes().is_set(1002));
}

#[test]
fn app_reachable_clipboard_copy_rides_custody() {
    let size = Size::new(20, 4);
    let mut app = three_rows(size);
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    driver.turn(&mut app, &mut term).unwrap();

    // Any component code can queue a copy; the driver emits it through
    // presenter custody on the next frame (0150's clipboard leg).
    copy_to_clipboard("from a handler");
    driver.turn(&mut app, &mut term).unwrap();
    assert_eq!(
        term.screen().clipboard(),
        Some(("c", b64("from a handler").as_str()))
    );
    // Whitespace-only refuses (empty OSC 52 would CLEAR the clipboard).
    copy_to_clipboard("   ");
    driver.turn(&mut app, &mut term).unwrap();
    assert_eq!(
        term.screen().clipboard(),
        Some(("c", b64("from a handler").as_str()))
    );
}

#[test]
fn unadvertised_osc52_still_copies_but_notices_once() {
    let size = Size::new(20, 4);
    let mut app = three_rows(size);
    let mut term = CaptureTerm::new(size);
    let mut plain = caps();
    plain.osc52_copy = false;
    let cfg = RunConfig {
        caps: Some(plain),
        probe: false,
        ..RunConfig::default()
    };
    let mut driver = Driver::new(&mut app, &mut term, cfg).unwrap();
    driver.turn(&mut app, &mut term).unwrap();

    copy_to_clipboard("hello");
    copy_to_clipboard("again");
    driver.turn(&mut app, &mut term).unwrap();
    // The bytes still go out (fire-and-forget; unsupporting terminals
    // ignore the frame)...
    assert_eq!(
        term.screen().clipboard(),
        Some(("c", b64("again").as_str()))
    );
    // ...and the degradation is labeled exactly once.
    let notices: Vec<_> = app
        .startup_notices()
        .iter()
        .filter(|n| n.contains("OSC 52"))
        .collect();
    assert_eq!(notices.len(), 1, "one labeled notice: {notices:?}");
}

#[test]
fn selection_idles_at_zero_cost_when_inactive() {
    let size = Size::new(20, 4);
    let mut app = three_rows(size);
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    selection().set_enabled(true);
    driver.turn(&mut app, &mut term).unwrap();
    let _ = term.take_bytes();

    // Select mode ON but nothing selected: turns are idle, zero bytes.
    for _ in 0..3 {
        let turn = driver.turn(&mut app, &mut term).unwrap();
        assert!(turn.idle, "select mode alone must not wake frames");
    }
    assert!(term.take_bytes().is_empty(), "idle means zero bytes");

    // A parked selection (drag finished, region visible) is idle too.
    term.push_input(b"\x1b[<0;1;1M");
    term.push_input(b"\x1b[<32;4;1M");
    driver.turn(&mut app, &mut term).unwrap();
    driver.turn(&mut app, &mut term).unwrap(); // release copy emission
    let _ = term.take_bytes();
    for _ in 0..3 {
        let turn = driver.turn(&mut app, &mut term).unwrap();
        assert!(turn.idle, "a parked selection costs nothing");
    }
    assert!(term.take_bytes().is_empty());
}

#[test]
fn pane_clamp_keeps_sibling_panes_out_of_the_copy() {
    let size = Size::new(40, 6);
    let mut app = App::new(size);
    app.mount(|_cx| {
        Element::new()
            .style(LayoutStyle::row())
            .child(
                Element::new()
                    .style(LayoutStyle::column().width(Dimension::Cells(20)).clip())
                    .child(text("left aaa"))
                    .child(text("left bbb"))
                    .build(),
            )
            .child(
                Element::new()
                    .style(LayoutStyle::column().grow(1.0).clip())
                    .child(text("right xxx"))
                    .child(text("right yyy"))
                    .build(),
            )
            .build()
    })
    .unwrap();
    let mut term = CaptureTerm::new(size);
    let mut driver = Driver::new(&mut app, &mut term, cfg()).unwrap();
    selection().set_enabled(true);
    driver.turn(&mut app, &mut term).unwrap();

    // Anchor in the LEFT pane, drag the head deep into the RIGHT pane:
    // the clamp pins the selection to the anchor's pane — no cross-pane
    // leak, no right-pane glyphs in the copy.
    term.push_input(b"\x1b[<0;1;1M"); // down at (0,0)
    term.push_input(b"\x1b[<32;35;2M"); // drag to (34,1) — right pane
    driver.turn(&mut app, &mut term).unwrap();
    term.push_input(b"c");
    driver.turn(&mut app, &mut term).unwrap();
    let expected = b64("left aaa\nleft bbb");
    assert_eq!(term.screen().clipboard(), Some(("c", expected.as_str())));
}