Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(tui): drag-selection copies text rows, never screen padding

Rach Pradhana4117819eebb
diff --git a/TUI/root.zig b/TUI/root.zig
index 3349e7a1..42bafa81 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -61,6 +61,7 @@ test {
_ = @import("welcome.zig");
_ = @import("scrollback.zig");
_ = @import("selection.zig");
+ _ = @import("selection_tests.zig");
_ = @import("chrome.zig");
_ = @import("models.zig");
_ = @import("markdown.zig");
diff --git a/TUI/selection.zig b/TUI/selection.zig
index 614eda20..7fe38765 100644
--- a/TUI/selection.zig
+++ b/TUI/selection.zig
@@ -9,6 +9,11 @@
//! with the rendered frame by construction — the band and the copied text come
//! out of the same pass over the same bytes.
//!
+//! What the band COVERS and what it CAPTURES differ on purpose: the band is a
+//! rectangle, but a screen row of nothing but layout padding is not text (see
+//! `Capture`), so a drag that overshoots into the empty screen below the
+//! transcript copies the transcript, not the emptiness.
+//!
//! Presentation state only. This renders the engine's transcript; it does not
//! fork engine behaviour, and nothing here reaches a provider.
@@ -41,6 +46,10 @@ pub const Sel = struct {
/// that read before rendering — copying at release time would then ship the
/// text of a frame the last motion never reached.
copy_pending: bool = false,
+ /// Rows of the last capture that actually carried text. The toast counts
+ /// these, not the newlines in `sel_text`: collapsed blank runs are spacing,
+ /// and calling them "lines copied" would inflate the number the user reads.
+ text_rows: usize = 0,
/// setToast BORROWS its slice — the copy toast has to outlive this call, so
/// it is formatted into model-owned storage.
toast_buf: [40]u8 = undefined,
@@ -99,7 +108,9 @@ fn finish(self: *Model) bool {
}
/// Runs inside the paint that captured the text, so the clipboard and the band
-/// can never disagree about which frame was selected.
+/// can never disagree about which frame was selected. A band over nothing but
+/// padding captures no text: the clipboard is left exactly as the user had it
+/// and no toast claims a copy that never happened.
fn commit(self: *Model) void {
self.sel.copy_pending = false;
const text = self.sel_text;
@@ -107,7 +118,7 @@ fn commit(self: *Model) void {
clear(self);
return;
}
- const lines = std.mem.count(u8, text, "\n") + 1;
+ const lines = self.sel.text_rows;
if (copyText(text)) {
const s = std.fmt.bufPrint(&self.sel.toast_buf, "{d} line{s} copied", .{
lines,
@@ -161,12 +172,43 @@ pub fn ordered(self: *const Model) ?Range {
};
}
+/// What the band COVERS and what it CAPTURES are deliberately different. The
+/// band is a rectangle over the frame, so it swallows the blank cells the
+/// layout uses for spacing; the capture is the text under it. A row with no
+/// glyphs contributes nothing, the blank rows at either end of the drag fall
+/// off, and a run of blank rows between two text rows collapses to a single
+/// empty line — paragraph separation survives, screens of padding do not.
+const Capture = struct {
+ text: *std.array_list.Managed(u8),
+ /// Rows that carried text. Blank rows, kept or dropped, never count.
+ rows: usize = 0,
+ /// A blank run is pending. It only becomes an empty line once a later row
+ /// proves it was INTERIOR, which is what drops the trailing blanks.
+ gap: bool = false,
+
+ fn push(self: *Capture, line: []const u8) !void {
+ if (line.len == 0) {
+ self.gap = self.rows > 0; // leading blanks never open the capture
+ return;
+ }
+ if (self.rows > 0) try self.text.append('\n');
+ if (self.gap) {
+ try self.text.append('\n');
+ self.gap = false;
+ }
+ try self.text.appendSlice(line);
+ self.rows += 1;
+ }
+};
+
/// Post-pass over the COMPOSED frame: the row builders in scrollback.zig stay
/// untouched, and the captured text is the same bytes the band covers.
pub fn paint(self: *Model, a: std.mem.Allocator, frame: []const u8, width: usize) ![]const u8 {
const r = ordered(self) orelse return frame;
var out = std.array_list.Managed(u8).init(a);
var text = std.array_list.Managed(u8).init(a);
+ var line = std.array_list.Managed(u8).init(a);
+ var cap: Capture = .{ .text = &text };
var row: usize = 0;
var it = std.mem.splitScalar(u8, frame, '\n');
while (it.next()) |ln| : (row += 1) {
@@ -177,10 +219,14 @@ pub fn paint(self: *Model, a: std.mem.Allocator, frame: []const u8, width: usize
try out.appendSlice(ln);
continue;
}
- if (row > r.r0) try text.append('\n');
- try band(&out, &text, ln, c0, c1);
+ line.clearRetainingCapacity();
+ try band(&out, &line, ln, c0, c1);
+ // Every row, column-bounded ends included, loses its trailing blanks —
+ // a row of nothing but them is then empty, and contributes nothing.
+ try cap.push(std.mem.trimEnd(u8, line.items, " \t"));
}
setText(self, text.items);
+ self.sel.text_rows = cap.rows;
if (self.sel.copy_pending) commit(self);
return out.items;
}
@@ -195,6 +241,9 @@ fn setText(self: *Model, s: []const u8) void {
/// SGR inside the band is dropped so the highlight is uniform (a stray `0m`
/// would otherwise cancel it mid-band) and re-emitted at the far edge, or the
/// rest of the row would paint in whatever style the band swallowed.
+///
+/// `text` is this ROW's capture buffer, emptied by the caller — the glyphs the
+/// band covers, and nothing the band merely pads over.
fn band(out: *std.array_list.Managed(u8), text: *std.array_list.Managed(u8), ln: []const u8, c0: usize, c1: usize) !void {
var sgr: theme_mod.Sgr = .{};
var i: usize = 0;
@@ -216,7 +265,6 @@ fn band(out: *std.array_list.Managed(u8), text: *std.array_list.Managed(u8), ln:
try pad(out, c0 -| col);
col = @max(col, c0);
try out.appendSlice("\x1b[7m");
- const mark = text.items.len;
while (i < ln.len and col < c1) {
if (ln[i] == 0x1b) {
const e = theme_mod.skipEsc(ln, i);
@@ -232,11 +280,8 @@ fn band(out: *std.array_list.Managed(u8), text: *std.array_list.Managed(u8), ln:
i += c.n;
}
// The band covers blank cells too, exactly like a terminal's own selection.
- // Those pad columns are not text: trim them back out of the capture.
+ // Those pad columns are painted, never captured.
try pad(out, c1 -| col);
- var end = text.items.len;
- while (end > mark and text.items[end - 1] == ' ') end -= 1;
- text.shrinkRetainingCapacity(end);
try out.appendSlice("\x1b[27m");
var buf: [theme_mod.Sgr.max_render]u8 = undefined;
try out.appendSlice(sgr.render(&buf));
@@ -348,6 +393,13 @@ test "a drag paints an inverse band and copies the covered rows (#529)" {
try std.testing.expect(std.mem.indexOf(u8, after, "\x1b[7m") != null);
try std.testing.expect(std.mem.indexOf(u8, copied[0..copied_len], "SELECTME alpha") != null);
try std.testing.expect(std.mem.indexOf(u8, m.toast, "copied") != null);
+ // The capture never opens or closes on the transcript's blank spacing rows,
+ // and the toast counts the rows that carried text.
+ try std.testing.expect(!std.mem.startsWith(u8, m.sel_text, "\n"));
+ try std.testing.expect(!std.mem.endsWith(u8, m.sel_text, "\n"));
+ var cnt: [8]u8 = undefined;
+ const head = try std.fmt.bufPrint(&cnt, "{d} line", .{m.sel.text_rows});
+ try std.testing.expect(std.mem.startsWith(u8, m.toast, head));
// ...and the next ordinary keystroke drops it.
_ = keys.handle(&m, .{ .char = 'x' });
try std.testing.expect(!m.sel.active);
@@ -441,71 +493,13 @@ test "the wheel scrolls and drops the band instead of extending it" {
try std.testing.expect(!m.follow);
}
-test "column bounds hold on the first and last row; middle rows are whole" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.last_term_width = 10;
- m.mid_origin = 0;
- m.prompt_origin = 5;
- m.sel = .{ .active = true, .a_row = 0, .a_col = 3, .h_row = 2, .h_col = 4 };
- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena.deinit();
- const out = try paint(&m, arena.allocator(), "abcdefghij\nklmnopqrst\nuvwxyz\nTAIL", 10);
- // First row starts at column 3, last row ends after column 4.
- try std.testing.expect(std.mem.indexOf(u8, out, "abc\x1b[7mdefghij") != null);
- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7muvwxy\x1b[27m") != null);
- try std.testing.expect(std.mem.indexOf(u8, out, "TAIL") != null);
- try std.testing.expectEqualStrings("defghij\nklmnopqrst\nuvwxy", m.sel_text);
- // A row shorter than the band is padded, and the pad is not text.
- m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 0, .h_col = 9 };
- const short = try paint(&m, arena.allocator(), "hi", 10);
- try std.testing.expect(std.mem.indexOf(u8, short, "\x1b[7mhi \x1b[27m") != null);
- try std.testing.expectEqualStrings("hi", m.sel_text);
-}
-
-test "the band drops SGR inside it and restores the style after it" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.last_term_width = 12;
- m.mid_origin = 0;
- m.prompt_origin = 4;
- m.sel = .{ .active = true, .a_row = 0, .a_col = 2, .h_row = 0, .h_col = 5 };
- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena.deinit();
- const out = try paint(&m, arena.allocator(), "ab\x1b[31mcdef\x1b[0mgh", 12);
- // No reset survives inside the band...
- const b0 = std.mem.indexOf(u8, out, "\x1b[7m").?;
- const b1 = std.mem.indexOf(u8, out, "\x1b[27m").?;
- try std.testing.expect(std.mem.indexOf(u8, out[b0..b1], "\x1b[") == 0);
- try std.testing.expect(std.mem.indexOf(u8, out[b0 + 4 .. b1], "\x1b[") == null);
- try std.testing.expectEqualStrings("cdef", m.sel_text);
-}
-
-test "a wide glyph never straddles a band edge" {
- var m: Model = undefined;
- m.setup(std.testing.allocator);
- defer m.deinit();
- m.last_term_width = 10;
- m.mid_origin = 0;
- m.prompt_origin = 4;
- // "a" + 世 (2 cols) + "b": a band ending mid-glyph must leave it out.
- m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 0, .h_col = 1 };
- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena.deinit();
- const out = try paint(&m, arena.allocator(), "a\u{4e16}b", 10);
- try std.testing.expectEqualStrings("a", m.sel_text);
- // The excluded glyph leaves a pad column so the band still measures 2, and
- // the glyph itself paints outside it, whole.
- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7ma \x1b[27m") != null);
- try std.testing.expect(std.mem.endsWith(u8, out, "\u{4e16}b"));
-}
-
-test "an empty drag copies nothing and leaves no band" {
+test "a drag over blank rows leaves the clipboard and the toast alone" {
engine.g_copy_fn = fakeCopy;
defer engine.g_copy_fn = null;
- copied_len = 0;
+ // Seeded, not zeroed: the contract is that the user's clipboard SURVIVES a
+ // drag that found no text, not merely that nothing new was appended.
+ copied_len = @min("KEEPME".len, copied.len);
+ @memcpy(copied[0..copied_len], "KEEPME");
var m: Model = undefined;
m.setup(std.testing.allocator);
defer m.deinit();
@@ -513,12 +507,13 @@ test "an empty drag copies nothing and leaves no band" {
m.mid_origin = 1;
m.prompt_origin = 20;
press(&m, 4, 5);
- drag(&m, 4, 5);
- release(&m, 4, 5);
+ drag(&m, 40, 8);
+ release(&m, 40, 8);
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
- _ = try paint(&m, arena.allocator(), "\n\n\n\n\n\n", 80);
- try std.testing.expectEqual(@as(usize, 0), copied_len);
+ _ = try paint(&m, arena.allocator(), "\n\n\n\n\n \n\n\n\n", 80);
+ try std.testing.expectEqualStrings("KEEPME", copied[0..copied_len]);
+ try std.testing.expectEqualStrings("", m.toast);
try std.testing.expect(!m.sel.active);
}
diff --git a/TUI/selection_tests.zig b/TUI/selection_tests.zig
new file mode 100644
index 00000000..7c4a5ad0
--- /dev/null
+++ b/TUI/selection_tests.zig
@@ -0,0 +1,151 @@
+//! Capture-contract tests for the drag band (#529). They drive `selection.paint`
+//! over a hand-written frame, so they hold what lands on the CLIPBOARD rather
+//! than any one helper's shape. Split out of selection.zig for the 600-line
+//! ceiling.
+//!
+//! The contract: the band is a rectangle over the frame, the capture is the
+//! text under it. Blank rows contribute nothing, the blanks at either end of
+//! the drag fall off, an interior run of them collapses to one empty line, and
+//! every row loses its trailing blanks.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const engine = @import("engine.zig");
+const selection = @import("selection.zig");
+const Model = app.Model;
+
+const paint = selection.paint;
+
+var copied: [4096]u8 = undefined;
+var copied_len: usize = 0;
+
+fn fakeCopy(_: ?*anyopaque, text: []const u8) bool {
+ copied_len = @min(text.len, copied.len);
+ @memcpy(copied[0..copied_len], text[0..copied_len]);
+ return true;
+}
+
+test "column bounds hold on the first and last row; middle rows are whole" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.last_term_width = 10;
+ m.mid_origin = 0;
+ m.prompt_origin = 5;
+ m.sel = .{ .active = true, .a_row = 0, .a_col = 3, .h_row = 2, .h_col = 4 };
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const out = try paint(&m, arena.allocator(), "abcdefghij\nklmnopqrst\nuvwxyz\nTAIL", 10);
+ // First row starts at column 3, last row ends after column 4.
+ try std.testing.expect(std.mem.indexOf(u8, out, "abc\x1b[7mdefghij") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7muvwxy\x1b[27m") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "TAIL") != null);
+ try std.testing.expectEqualStrings("defghij\nklmnopqrst\nuvwxy", m.sel_text);
+ try std.testing.expectEqual(@as(usize, 3), m.sel.text_rows);
+ // A row shorter than the band is padded, and the pad is not text.
+ m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 0, .h_col = 9 };
+ const short = try paint(&m, arena.allocator(), "hi", 10);
+ try std.testing.expect(std.mem.indexOf(u8, short, "\x1b[7mhi \x1b[27m") != null);
+ try std.testing.expectEqualStrings("hi", m.sel_text);
+}
+
+test "the band drops SGR inside it and restores the style after it" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.last_term_width = 12;
+ m.mid_origin = 0;
+ m.prompt_origin = 4;
+ m.sel = .{ .active = true, .a_row = 0, .a_col = 2, .h_row = 0, .h_col = 5 };
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const out = try paint(&m, arena.allocator(), "ab\x1b[31mcdef\x1b[0mgh", 12);
+ // No reset survives inside the band...
+ const b0 = std.mem.indexOf(u8, out, "\x1b[7m").?;
+ const b1 = std.mem.indexOf(u8, out, "\x1b[27m").?;
+ try std.testing.expect(std.mem.indexOf(u8, out[b0..b1], "\x1b[") == 0);
+ try std.testing.expect(std.mem.indexOf(u8, out[b0 + 4 .. b1], "\x1b[") == null);
+ try std.testing.expectEqualStrings("cdef", m.sel_text);
+}
+
+test "a wide glyph never straddles a band edge" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.last_term_width = 10;
+ m.mid_origin = 0;
+ m.prompt_origin = 4;
+ // "a" + 世 (2 cols) + "b": a band ending mid-glyph must leave it out.
+ m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 0, .h_col = 1 };
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const out = try paint(&m, arena.allocator(), "a\u{4e16}b", 10);
+ try std.testing.expectEqualStrings("a", m.sel_text);
+ // The excluded glyph leaves a pad column so the band still measures 2, and
+ // the glyph itself paints outside it, whole.
+ try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7ma \x1b[27m") != null);
+ try std.testing.expect(std.mem.endsWith(u8, out, "\u{4e16}b"));
+}
+
+test "blank rows at the ends drop and an interior run collapses to one line" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.last_term_width = 12;
+ m.mid_origin = 0;
+ m.prompt_origin = 9;
+ // The drag covers all eight rows: two of leading padding, a text row, a
+ // three-row gap, another text row, then the empty screen below.
+ m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 7, .h_col = 11 };
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const frame = "\n \nalpha one\n\n \n\nbeta two\n ";
+ const out = try paint(&m, arena.allocator(), frame, 12);
+ // The band still PAINTS every covered row — only the capture is text-only.
+ try std.testing.expectEqual(@as(usize, 8), std.mem.count(u8, out, "\x1b[7m"));
+ try std.testing.expectEqualStrings("alpha one\n\nbeta two", m.sel_text);
+ try std.testing.expectEqual(@as(usize, 2), m.sel.text_rows);
+}
+
+test "every captured row is trimmed, column-bounded first and last included" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.last_term_width = 16;
+ m.mid_origin = 0;
+ m.prompt_origin = 4;
+ // First row bounded at column 2, last row bounded after column 11 — both
+ // end inside a run of spaces, and neither may carry them out.
+ m.sel = .{ .active = true, .a_row = 0, .a_col = 2, .h_row = 2, .h_col = 11 };
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const out = try paint(&m, arena.allocator(), "xxfirst \nmid \nlast zzzz", 16);
+ try std.testing.expectEqualStrings("first\nmid\nlast", m.sel_text);
+ try std.testing.expectEqual(@as(usize, 3), m.sel.text_rows);
+ // The painted band keeps its full width; only the capture is trimmed.
+ try std.testing.expect(std.mem.indexOf(u8, out, "xx\x1b[7mfirst ") != null);
+ try std.testing.expect(std.mem.endsWith(u8, out, "zzzz"));
+}
+
+test "a band over nothing but padding copies nothing and shows no toast" {
+ engine.g_copy_fn = fakeCopy;
+ defer engine.g_copy_fn = null;
+ copied_len = @min("SENTINEL".len, copied.len);
+ @memcpy(copied[0..copied_len], "SENTINEL");
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ m.last_term_width = 12;
+ m.mid_origin = 0;
+ m.prompt_origin = 5;
+ m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 3, .h_col = 11, .copy_pending = true };
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ _ = try paint(&m, arena.allocator(), "\n \n\n \nTAIL", 12);
+ try std.testing.expectEqualStrings("SENTINEL", copied[0..copied_len]);
+ try std.testing.expectEqual(@as(usize, 0), m.sel_text.len);
+ try std.testing.expectEqual(@as(usize, 0), m.sel.text_rows);
+ try std.testing.expectEqualStrings("", m.toast);
+ try std.testing.expect(!m.sel.active);
+}
diff --git a/scripts/test-tui-selection.py b/scripts/test-tui-selection.py
index d59d321d..8edca080 100644
--- a/scripts/test-tui-selection.py
+++ b/scripts/test-tui-selection.py
@@ -9,8 +9,12 @@ own), the probe:
needed and the text on screen is known,
3. sends an SGR mouse drag over the transcript — press, motions, release,
4. asserts the frame that comes back carries inverse-video (SGR 7) spans,
- 5. asserts the system clipboard now holds the dragged text (pbpaste), and
- that a following keystroke clears the band again.
+ 5. asserts the system clipboard now holds exactly the dragged text (pbpaste),
+ 6. asserts the CAPTURE CONTRACT against the live screen: a drag that runs off
+ the last text row and down through the blank screen below the transcript
+ copies the same thing the tight drag did, and a drag that covers nothing
+ but blank rows leaves a pre-seeded clipboard sentinel untouched, and
+ 7. asserts a following keystroke clears the band again.
Usage: python3 scripts/test-tui-selection.py [path/to/graff] (default zig-out/bin/graff)
Exit 0 = pass. Skips (exit 0, notice) with no pty or no clipboard tool.
@@ -27,6 +31,8 @@ BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")
BOOT_MAX = 15.0
MARK = "SELECTME_ZULU"
SENTINEL = "CLIPBOARD_SENTINEL_BEFORE_DRAG"
+# Returned instead of an error when the environment, not the TUI, is at fault.
+SKIP = "skip: the clipboard is being written by another app"
def drain(fd, seconds):
@@ -112,6 +118,28 @@ def clipboard_get():
return subprocess.run(["pbpaste"], capture_output=True, check=True).stdout.decode()
+def clipboard_after_copy(prev, tries=10):
+ """The clipboard once a copy has landed. pbpaste can observe the pasteboard
+ mid-write and come back empty, which would read as "copied nothing"."""
+ got = prev
+ for _ in range(tries):
+ got = clipboard_get()
+ if got and got != prev:
+ return got
+ time.sleep(0.2)
+ return got
+
+
+def seed_clipboard():
+ """Plant the sentinel and confirm it stuck. A clipboard manager writing in
+ the background must read as a skip, never as a failure of the TUI."""
+ for _ in range(3):
+ clipboard_set(SENTINEL)
+ if clipboard_get() == SENTINEL:
+ return True
+ return False
+
+
def sgr(btn, col, row, press=True):
return f"\x1b[<{btn};{col};{row}{'M' if press else 'm'}".encode()
@@ -139,6 +167,33 @@ def full_frame(fd, rows, cols):
ROWS, COLS = 30, 100
+def drag_copy(fd, r0, r1):
+ """Press on row r0, drag through r1, release. Rows are 1-based, as SGR reports.
+
+ Returns (painted, after) — the stream while the button was down, and the
+ stream after the release, which is where the copy toast shows up.
+ """
+ os.write(fd, sgr(0, 1, r0))
+ drain(fd, 0.3)
+ os.write(fd, sgr(32, COLS, (r0 + r1) // 2))
+ drain(fd, 0.2)
+ os.write(fd, sgr(32, COLS, r1))
+ painted = drain(fd, 0.6)
+ os.write(fd, sgr(0, COLS, r1, press=False))
+ return painted, drain(fd, 1.0)
+
+
+def blank_run(rows, start):
+ """The contiguous run of blank screen rows at `start` — the empty screen
+ below the transcript, which a drag must be able to overshoot into."""
+ out = []
+ i = start
+ while i < len(rows) and rows[i].strip() == "":
+ out.append(i)
+ i += 1
+ return out
+
+
def run():
ws, env = fresh_ws()
pid, fd = spawn(ws, env, ROWS, COLS)
@@ -159,29 +214,61 @@ def run():
idle = drain(fd, 0.4)
if b"\x1b[7m" in idle:
return "the idle frame already carries an inverse-video band"
- clipboard_set(SENTINEL)
- # Press on the marked row, drag two rows down, release. SGR: button 0
- # press, 32 = motion with the button held, final 'm' = release.
- top = hit + 1 # screen rows are 1-based in the SGR report
- os.write(fd, sgr(0, 3, top))
- drain(fd, 0.3)
- os.write(fd, sgr(32, 40, top + 1))
- drain(fd, 0.3)
- os.write(fd, sgr(32, 60, top + 2))
- painted = drain(fd, 0.6)
+ # `hit` is the ECHOED command line — it carries the mark inside the
+ # printf argument. The output block is the rows after it, up to the last
+ # row still carrying the mark; the echo row is skipped because the TUI
+ # decorates it with a run marker that changes between frames.
+ first, last = hit + 1, max(i for i, ln in enumerate(rows) if MARK in ln)
+ if last <= first:
+ return "the printf output did not land on its own screen rows"
+ blanks = blank_run(rows, last + 1)
+ if len(blanks) < 4:
+ return "no blank screen region below the transcript to drag into"
+ if not seed_clipboard():
+ return SKIP
+ # A TIGHT drag: press on the marked row, release on the last text row.
+ # SGR: button 0 press, 32 = motion with the button held, final 'm'.
+ top = first + 1 # screen rows are 1-based in the SGR report
+ painted, _ = drag_copy(fd, top, last + 1)
if b"\x1b[7m" not in painted:
return "the drag painted no inverse-video band (no SGR 7 in the frame)"
if b"\x1b[27m" not in painted:
return "the band never emitted its SGR 27 terminator"
- os.write(fd, sgr(0, 60, top + 2, press=False))
- drain(fd, 1.0)
- got = clipboard_get()
- if got == SENTINEL:
+ tight = clipboard_after_copy(SENTINEL)
+ if tight == SENTINEL:
return "the release did not reach the clipboard (still the sentinel)"
- if f"{MARK}_ONE" not in got:
- return f"the clipboard got {got!r}, which does not contain {MARK}_ONE"
- if len(got.split("\n")) != 3:
- return f"a 3-row drag copied {len(got.split(chr(10)))} row(s): {got!r}"
+ # Row bytes are asserted by shape, not compared to the pre-drag frame:
+ # the press moves scrollback focus, which puts a `›` marker in column 0
+ # of the pressed row. That marker is real screen text and is copied.
+ lines = tight.split("\n")
+ if len(lines) != last - first + 1:
+ return f"a {last - first + 1}-text-row drag copied {len(lines)} line(s): {tight!r}"
+ if not lines[0].endswith(f"{MARK}_ONE") or not lines[-1].endswith(f"{MARK}_TWO"):
+ return f"the tight drag copied {tight!r}, not the two marked rows"
+ if any(ln.strip() == "" for ln in lines):
+ return f"the tight drag copied a blank line: {tight!r}"
+ if any(ln != ln.rstrip() for ln in lines):
+ return f"a copied row kept its trailing padding: {tight!r}"
+ # OVERSHOOT: the same first row, released far down in the blank screen
+ # below the transcript. Blank rows are padding, not content, so this
+ # must land exactly what the tight drag did — no trailing empty lines.
+ if not seed_clipboard():
+ return SKIP
+ drag_copy(fd, top, blanks[-1] + 1) # release deep in the blank screen
+ loose = clipboard_after_copy(SENTINEL)
+ if loose != tight:
+ return f"overshooting into the blank screen copied {loose!r}, wanted {tight!r}"
+ # BLANK-ONLY: a drag wholly inside the empty screen copies nothing at
+ # all — the clipboard keeps what the user had, and no toast claims a copy.
+ drain(fd, 2.0) # let the previous copy toast expire first
+ if not seed_clipboard():
+ return SKIP
+ _, after_blank = drag_copy(fd, blanks[1] + 1, blanks[-2] + 1)
+ empty = clipboard_get()
+ if empty != SENTINEL:
+ return f"a drag over blank rows overwrote the clipboard with {empty!r}"
+ if b"copied" in after_blank:
+ return "a drag over blank rows still showed a 'copied' toast"
# A following keystroke drops the band: the repaint that follows must
# rewrite those rows WITHOUT inverse video.
os.write(fd, b"z")
@@ -219,10 +306,13 @@ def main():
clipboard_set(saved)
except Exception:
pass
+ if err == SKIP:
+ print(f"tui-selection: {err[6:]} — skipping")
+ return 0
if err:
print(f" ✗ drag-select: {err}")
return 1
- print(" ✓ drag-select: inverse band painted, clipboard received the rows")
+ print(" ✓ drag-select: band painted, clipboard got the text rows and only those")
return 0