diff --git a/.gitattributes b/.gitattributes index 51e2afe6..d3f5369c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -10,3 +10,8 @@ # checks them out as CRLF on Windows and cargo then fails with # "the listed checksum of vendor/... has changed". Disable all conversion. vendor/** -text + +# Терминальные фикстуры — сырые байтовые потоки вывода (ESC-последовательности, +# CRLF от консоли/PTY). Нормализация EOL изменила бы смысл фикстуры, поэтому +# байты хранятся как есть (как vendor/**). +rust-apps/pagh-terminal/tests/fixtures/** -text diff --git a/rust-apps/pagh-terminal/TERMINAL.md b/rust-apps/pagh-terminal/TERMINAL.md index 5358aa73..b153a7fa 100644 --- a/rust-apps/pagh-terminal/TERMINAL.md +++ b/rust-apps/pagh-terminal/TERMINAL.md @@ -342,7 +342,12 @@ client server будущего расширения; IME не поддержан); * wheel без mouse-reporting листает scrollback; drag левой кнопкой создаёт selection. Выделенный текст доступен `Screen::selection_text()`; запись в - системный clipboard в v1 не выполняется. + системный clipboard в v1 не выполняется. Selection меняет **только фон**: + это полупрозрачная подсветка поверх исходного фона + (`render::SELECTION_BG_MIX`), поэтому foreground и ANSI-цвета остаются + байт-в-байт прежними. Перекрашивать текст в один `selection_fg` нельзя: + на выводе `fastfetch` это стирает цветной логотип и полосу цветовых фонов + (регрессия — `tests/selection_live.rs` и `tests/render_png.rs`). Resize — только серверный: клиент не просит размер, а принимает `configure`. Декорации и заголовок принадлежат композитору, поэтому `set_title` в PDP/1 diff --git a/rust-apps/pagh-terminal/screenshots/03-scrollback.png b/rust-apps/pagh-terminal/screenshots/03-scrollback.png index 2e21fe0f..012e4f41 100644 Binary files a/rust-apps/pagh-terminal/screenshots/03-scrollback.png and b/rust-apps/pagh-terminal/screenshots/03-scrollback.png differ diff --git a/rust-apps/pagh-terminal/src/render.rs b/rust-apps/pagh-terminal/src/render.rs index 9354f12e..11642bc2 100644 --- a/rust-apps/pagh-terminal/src/render.rs +++ b/rust-apps/pagh-terminal/src/render.rs @@ -17,6 +17,14 @@ use crate::screen::Screen; /// Padding around the text grid inside a client surface. pub const VIEWPORT_PADDING: usize = 2; +/// Share of [`Theme::selection`] mixed into a selected cell's background. +/// +/// Selection is a *wash over the existing background*, not an opaque repaint: +/// background art (ANSI `48;*` cells, colour swatches) stays readable and the +/// foreground is never touched, while 60 % accent is still unmistakably a +/// highlight on the dark theme. 100 % would erase the background; a much lower +/// value makes the selection hard to see. +pub const SELECTION_BG_MIX: f32 = 0.6; /// Height of the screenshot-only title strip. pub const TITLE_H: usize = 22; /// Window border thickness. @@ -405,7 +413,6 @@ pub struct Theme { pub cursor_text: Rgb, pub cursor_unfocused: Rgb, pub selection: Rgb, - pub selection_fg: Rgb, pub palette: [Rgb; 256], pub window_bg: Rgb, pub border: Rgb, @@ -424,7 +431,6 @@ impl Default for Theme { cursor_text: Rgb(0x23, 0x26, 0x27), cursor_unfocused: Rgb(0x7f, 0x8c, 0x8d), selection: Rgb(0x3d, 0xae, 0xe9), - selection_fg: Rgb(0x23, 0x26, 0x27), palette: default_palette(), window_bg: Rgb(0x23, 0x26, 0x27), border: Rgb(0x1b, 0x1e, 0x1f), @@ -684,18 +690,28 @@ fn resolve_style( if cell.attrs.contains(Attrs::DIM) { fg = fg.scale(0.62); } - if cell.attrs.contains(Attrs::HIDDEN) { - fg = bg; - } - if cell.attrs.contains(Attrs::BLINK) && !blink_on { - fg = bg; - } + // HIDDEN and a dark blink phase paint the foreground in the background + // colour. Defer that decision until after the selection wash: it has to + // track the *current* background, or selection would make hidden text show + // up (fg keeps the pre-selection colour while bg moved). + let blank = + cell.attrs.contains(Attrs::HIDDEN) || (cell.attrs.contains(Attrs::BLINK) && !blink_on); if screen.reverse_video { std::mem::swap(&mut fg, &mut bg); } if selected { - bg = theme.selection; - fg = theme.selection_fg; + // Selection changes the background only. Overwriting the foreground + // with one dark colour (the old `selection_fg`) erased exactly what a + // selection must preserve: a fastfetch logo is coloured `#` glyphs and + // its palette strip is ANSI *backgrounds*, so a flat fill turned the + // logo into dark blocks and the strip into one blue bar, while every + // coloured key/value went grey. A wash keeps the glyph colour + // byte-identical and lets background art show through, and the mixed + // contrast still makes the highlight obvious. + bg = bg.lerp(theme.selection, SELECTION_BG_MIX); + } + if blank { + fg = bg; } let focused_cursor = cursor_block; if cursor_block { @@ -1201,7 +1217,126 @@ mod tests { let theme = Theme::default(); let canvas = render_screen(&t.screen, &theme, &RenderOptions::default()); let px = canvas.pixel(VIEWPORT_PADDING + CELL_W + 2, VIEWPORT_PADDING + 2); - assert_eq!(&px[..3], &theme.selection.to_array()); + assert_eq!( + &px[..3], + &theme.bg.lerp(theme.selection, SELECTION_BG_MIX).to_array() + ); + } + + /// Собрать цвета всех пикселей клетки `(row, col)`. + fn cell_pixels(canvas: &Canvas, row: usize, col: usize) -> Vec<[u8; 3]> { + let mut out = Vec::with_capacity(CELL_W * CELL_H); + for y in 0..CELL_H { + for x in 0..CELL_W { + let px = canvas.pixel( + VIEWPORT_PADDING + col * CELL_W + x, + VIEWPORT_PADDING + row * CELL_H + y, + ); + out.push([px[0], px[1], px[2]]); + } + } + out + } + + /// Репро бага: выделение fastfetch (цветной `#`-логотип + ANSI-текст) + /// раньше перекрашивало foreground в один серый (`selection_fg`), поэтому + /// логотип и цветные ключи пропадали. Выделение обязано менять только фон: + /// каждый пиксель глифа сохраняет свой цвет, а фон уходит в подсветку. + #[test] + fn selection_preserves_glyph_colours() { + let mut t = Terminal::new(12, 2); + t.feed_str("\x1b[1m\x1b[33m##\x1b[0m\x1b[1m\x1b[37mPagh\x1b[0m"); + let theme = Theme::default(); + let opts = RenderOptions::default(); + let plain = render_screen(&t.screen, &theme, &opts); + + let mut selected = Terminal::new(12, 2); + selected.feed_str("\x1b[1m\x1b[33m##\x1b[0m\x1b[1m\x1b[37mPagh\x1b[0m"); + selected + .screen + .begin_selection_abs(0, 0, crate::screen::SelectionMode::Char); + selected.screen.extend_selection_abs(0, 5); + let after = render_screen(&selected.screen, &theme, &opts); + + let highlight = theme.bg.lerp(theme.selection, SELECTION_BG_MIX); + let yellow = theme.palette[11].lerp(Rgb::WHITE, 0.12); + let white = theme.palette[15].lerp(Rgb::WHITE, 0.12); + let mut glyph_pixels = 0usize; + for col in 0..6 { + let before = cell_pixels(&plain, 0, col); + let now = cell_pixels(&after, 0, col); + for (b, a) in before.iter().zip(now.iter()) { + if *b == yellow.to_array() || *b == white.to_array() { + glyph_pixels += 1; + assert_eq!(b, a, "foreground pixel at cell {col} changed colour"); + } else if *b == theme.bg.to_array() { + assert_eq!(a, &highlight.to_array(), "selection background mismatch"); + } + } + } + assert!(glyph_pixels > 40, "too few glyph pixels: {glyph_pixels}"); + } + + /// Full-block art (the `█`-style logo) is pure foreground in the cell: the + /// old opaque `selection_fg` fill turned the whole cell into the theme + /// background, i.e. the logo visibly disappeared. Its pixels must stay + /// byte-identical under selection. + #[test] + fn selection_does_not_erase_full_block_glyphs() { + let mut t = Terminal::new(4, 1); + t.screen.pen.fg = Color::Rgb(255, 0, 0); + t.feed_str("█"); + t.screen + .begin_selection_abs(0, 0, crate::screen::SelectionMode::Char); + t.screen.extend_selection_abs(0, 0); + let canvas = render_screen(&t.screen, &Theme::default(), &RenderOptions::default()); + for px in cell_pixels(&canvas, 0, 0) { + assert_eq!(px, [255, 0, 0], "selected block glyph was repainted"); + } + } + + /// ANSI-background art (`48;*`) is part of the picture too: the wash must + /// keep it distinguishable instead of replacing it with a solid bar. + #[test] + fn selection_keeps_ansi_background_art() { + let mut t = Terminal::new(4, 1); + t.feed_str("\x1b[41m \x1b[0m"); + let theme = Theme::default(); + let opts = RenderOptions::default(); + let plain = render_screen(&t.screen, &theme, &opts); + t.screen + .begin_selection_abs(0, 0, crate::screen::SelectionMode::Char); + t.screen.extend_selection_abs(0, 1); + let after = render_screen(&t.screen, &theme, &opts); + let red = theme.palette[1]; + let washed = red.lerp(theme.selection, SELECTION_BG_MIX); + for col in 0..2 { + assert_eq!(cell_pixels(&plain, 0, col)[0], red.to_array()); + let px = cell_pixels(&after, 0, col)[0]; + assert_eq!(px, washed.to_array()); + assert_ne!(px, theme.selection.to_array(), "background art was erased"); + assert_ne!(px, red.to_array(), "selection is invisible"); + } + } + + /// Hidden text must stay hidden: now that the foreground is preserved, the + /// "paint fg in the background colour" decision has to follow the *washed* + /// background, not the pre-selection one. + #[test] + fn selection_keeps_hidden_text_hidden() { + let mut t = Terminal::new(8, 1); + t.feed_str("\x1b[8msecret"); + let theme = Theme::default(); + t.screen + .begin_selection_abs(0, 0, crate::screen::SelectionMode::Char); + t.screen.extend_selection_abs(0, 5); + let canvas = render_screen(&t.screen, &theme, &RenderOptions::default()); + let washed = theme.bg.lerp(theme.selection, SELECTION_BG_MIX); + for col in 0..6 { + for px in cell_pixels(&canvas, 0, col) { + assert_eq!(px, washed.to_array(), "hidden glyph appeared on selection"); + } + } } #[test] diff --git a/rust-apps/pagh-terminal/tests/fixtures/fastfetch-guest.script b/rust-apps/pagh-terminal/tests/fixtures/fastfetch-guest.script new file mode 100644 index 00000000..80909bd9 --- /dev/null +++ b/rust-apps/pagh-terminal/tests/fixtures/fastfetch-guest.script @@ -0,0 +1,26 @@ + ##### + ####### + ##O#O## + ####### + ########### + ############# + ############### + ################ + ################# +##################### +##################### + #################root@pagh +--------- +Kernel: Linux 6.1.0-pagh +Uptime: 8 seconds +Shell: sh +Terminal: xterm +Terminal Font: fixed (8.0pt) +CPU: QEMU TCG version 2.5+ +Memory: 571.67 MiB / 992.84 MiB (58%) +Swap: Disabled +Disk (]8;;file:///\/]8;;\): 571.67 MiB / 992.84 MiB (58%) - rootfs +Locale: C + +         +         diff --git a/rust-apps/pagh-terminal/tests/render_png.rs b/rust-apps/pagh-terminal/tests/render_png.rs index f185763f..bf010b45 100644 --- a/rust-apps/pagh-terminal/tests/render_png.rs +++ b/rust-apps/pagh-terminal/tests/render_png.rs @@ -5,7 +5,7 @@ use pagh_terminal::demo; use pagh_terminal::png; use pagh_terminal::render::{ render_screen, render_screen_into, render_screen_into_cleared, render_window, Canvas, - RenderOptions, Theme, BORDER, TITLE_H, VIEWPORT_PADDING, + RenderOptions, Theme, BORDER, SELECTION_BG_MIX, TITLE_H, VIEWPORT_PADDING, }; use pagh_terminal::screen::{Screen, SelectionMode}; use pagh_terminal::Terminal; @@ -55,10 +55,11 @@ fn text_cursor_and_selection_paint_expected_pixels() { let theme = theme(); let canvas = render_screen(&terminal.screen, &theme, &RenderOptions::default()); - // Selected cell background. + // Selected cell background: a wash over the cell background, not an + // opaque fill (see render::SELECTION_BG_MIX). assert_eq!( &canvas.pixel(VIEWPORT_PADDING + 8 + 2, VIEWPORT_PADDING + 2)[..3], - &theme.selection.to_array() + &theme.bg.lerp(theme.selection, SELECTION_BG_MIX).to_array() ); // Cursor block at cell 5. assert_eq!( @@ -402,3 +403,139 @@ fn bulk_fills_match_the_per_pixel_reference() { "mapped fill diverges (wire order or stride)" ); } + +/// Репро бага на настоящем выводе `fastfetch`, снятом с гостя (serial-лог +/// сессии qbug3): цветной `#`-логотип слева, ANSI-текст справа и полоса +/// цветовых фонов внизу. +/// +/// Оракул: кадр с выделением обязан быть пиксель-в-пиксель равен кадру без +/// выделения, отрисованному с `theme.bg == подсветка`, во всех клетках с +/// дефолтным фоном. Это ровно утверждение «выделение меняет только фон»: +/// foreground, сглаживание и ANSI-цвета совпадают по построению, а не по +/// переписанной в тесте формуле. +/// +/// Прежний `resolve_style` подменял foreground на один тёмный `selection_fg`, +/// поэтому логотип и цветные пары ключ/значение становились серыми, а +/// ANSI-фоны — сплошной синей полосой. +#[test] +fn selection_over_real_fastfetch_output_keeps_logo_text_and_colours() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let raw = std::fs::read(dir.join("tests/fixtures/fastfetch-guest.script")) + .expect("fastfetch guest fixture"); + let theme = theme(); + let opts = RenderOptions::default(); + let mut plain = Terminal::new(100, 30); + plain.feed(&raw); + let before = render_screen(&plain.screen, &theme, &opts); + + // Весь блок fastfetch: 12 строк логотипа/информации + две строки + // цветовых фонов (ANSI 40..47 и 100..107). + let mut selected = Terminal::new(100, 30); + selected.feed(&raw); + selected + .screen + .begin_selection_abs(0, 0, SelectionMode::Char); + selected.screen.extend_selection_abs(13, 99); + let after = render_screen(&selected.screen, &theme, &opts); + + let highlight = theme.bg.lerp(theme.selection, SELECTION_BG_MIX); + let mut washed = theme.clone(); + washed.bg = highlight; + let oracle = render_screen(&plain.screen, &washed, &opts); + assert_ne!( + highlight.to_array(), + theme.selection.to_array(), + "selection wash must not be the opaque accent" + ); + + let rgb = |px: [u8; 4]| [px[0], px[1], px[2]]; + let mut background = 0usize; + let mut glyph = 0usize; + let mut swatches = 0usize; + for row in 0..14 { + let line = plain.screen.view_line(row); + for col in 0..100 { + let cell = line.get(col).copied().unwrap_or_default(); + for y in 0..18 { + for x in 0..8 { + let px = ( + VIEWPORT_PADDING + col * 8 + x, + VIEWPORT_PADDING + row * 18 + y, + ); + let b = rgb(before.pixel(px.0, px.1)); + let a = after.pixel(px.0, px.1); + if !cell.bg.is_default() { + // ANSI-фон (полоса цветов внизу): подсветка — смесь, а + // не сплошная заливка, поэтому арт остаётся различимым. + let bg = cell.bg.resolve(&theme.palette, theme.bg); + assert_eq!( + rgb(a), + bg.lerp(theme.selection, SELECTION_BG_MIX).to_array(), + "ANSI background art was erased at ({row},{col})" + ); + assert_ne!(rgb(a), theme.selection.to_array()); + swatches += 1; + continue; + } + assert_eq!( + a, + oracle.pixel(px.0, px.1), + "selected cell ({row},{col}) differs from `theme.bg = highlight`" + ); + if b == theme.bg.to_array() { + assert_eq!(rgb(a), highlight.to_array()); + background += 1; + } else { + glyph += 1; + } + } + } + } + } + assert!( + background > 10_000, + "selection painted too little: {background}" + ); + assert!( + swatches > 100, + "no ANSI colour swatches covered: {swatches}" + ); + + // Регрессия «foreground посерел»: ядра глифов (полное покрытие) — это + // пиксели, которые в оракуле остались прежними; старый код перекрашивал + // их все, поэтому счётчик обнулялся бы. Края сглаживания законно + // смешиваются с новым фоном, поэтому их сюда не относим. + let mut preserved = 0usize; + for row in 0..14 { + let line = plain.screen.view_line(row); + for col in 0..100 { + let cell = line.get(col).copied().unwrap_or_default(); + if !cell.bg.is_default() { + continue; + } + for y in 0..18 { + for x in 0..8 { + let px = ( + VIEWPORT_PADDING + col * 8 + x, + VIEWPORT_PADDING + row * 18 + y, + ); + let b = before.pixel(px.0, px.1); + let a = after.pixel(px.0, px.1); + if b[..3] != theme.bg.to_array()[..] && b == a { + preserved += 1; + } + } + } + } + } + assert!( + preserved > 1_000, + "foreground colours were not preserved: {preserved}" + ); + // И сам кадр не должен быть «залит» подсветкой: глифовые пиксели заведомо + // есть внутри выделения. + assert!( + glyph > 1_000, + "no glyph pixels inside the selection: {glyph}" + ); +} diff --git a/rust-apps/pagh-terminal/tests/selection_live.rs b/rust-apps/pagh-terminal/tests/selection_live.rs new file mode 100644 index 00000000..537728f5 --- /dev/null +++ b/rust-apps/pagh-terminal/tests/selection_live.rs @@ -0,0 +1,298 @@ +//! Живое репро бага «выделение fastfetch стирает картинку/текст». +//! +//! Настоящий композитор `pagh-desktop` (host build), настоящий бинарник +//! `pagh-terminal` по AF_UNIX/PDP/1, настоящий вывод `fastfetch`, снятый с +//! гостя, и настоящая мышь: композитор получает press/motion/release и шлёт их +//! клиенту, клиент сам строит selection и перерисовывает кадр. +//! +//! Проверка пиксельная и сравнивает кадр композитора *до* и *после* протяжки: +//! внутри выделенных клеток фон обязан уйти в подсветку, а каждый глиф — +//! остаться байт-в-байт прежним (старый `selection_fg` перекрашивал весь +//! foreground в один серый и стирал логотип). +//! +//! Скриншоты можно сохранить в каталог из `PAGH_TERMINAL_EVIDENCE` — evidence +//! для ревью; без переменной тест работает во временном каталоге. + +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +use pagh_desktop::panel::PANEL_HEIGHT; +use pagh_desktop::png::{decode_png, DecodedPng}; +use pagh_desktop::server::{unique_socket_path, Server, ServerOptions}; +use pagh_desktop::window::{BORDER, TITLEBAR_HEIGHT}; +use pagh_terminal::demo::DemoShell; +use pagh_terminal::font::{CELL_H, CELL_W}; +use pagh_terminal::render::{Theme, SELECTION_BG_MIX, VIEWPORT_PADDING}; + +const SCREEN: (u32, u32) = (1280, 800); +const CONTENT: (u32, u32) = (760, 520); + +fn layout(width: u32, height: u32) -> (usize, usize) { + let pad = VIEWPORT_PADDING * 2; + let cols = ((width as usize).saturating_sub(pad) / CELL_W).max(2); + let rows = ((height as usize).saturating_sub(pad) / CELL_H).max(2); + (cols, rows) +} + +fn wait_for bool>(timeout: Duration, mut predicate: F) -> bool { + let deadline = Instant::now() + timeout; + while Instant::now() < deadline { + if predicate() { + return true; + } + std::thread::sleep(Duration::from_millis(20)); + } + false +} + +fn temp_dir(tag: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!( + "pagh-terminal-live-{tag}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&path).unwrap(); + path +} + +fn evidence_dir() -> Option { + let dir = std::env::var_os("PAGH_TERMINAL_EVIDENCE").map(PathBuf::from)?; + std::fs::create_dir_all(&dir).unwrap(); + Some(dir) +} + +fn capture(control: &pagh_desktop::server::ServerControl, dir: &Path, name: &str) -> Vec { + let path = dir.join(name); + let _ = std::fs::remove_file(&path); + control.screenshot(&path); + assert!( + wait_for(Duration::from_secs(5), || path.exists()), + "кадр {name} не появился" + ); + std::thread::sleep(Duration::from_millis(60)); + std::fs::read(&path).unwrap() +} + +/// Точка в координатах экрана композитора для центра клетки клиента. +fn cell_point(col: usize, row: usize) -> (i32, i32) { + // Первое окно: cascade (96,64), затем clamp в пределах экрана. Кадр окна = + // контент + рамка + заголовок; контент начинается на BORDER/TITLEBAR. + let frame_w = CONTENT.0 as i32 + 2 * BORDER; + let frame_h = CONTENT.1 as i32 + 2 * BORDER + TITLEBAR_HEIGHT; + let max_x = (SCREEN.0 as i32 - frame_w - 24).max(16); + let max_y = (SCREEN.1 as i32 - PANEL_HEIGHT - frame_h - 24).max(16); + let left = 96.min(max_x) + BORDER; + let top = 64.min(max_y) + BORDER + TITLEBAR_HEIGHT; + ( + left + (VIEWPORT_PADDING + col * CELL_W + CELL_W / 2) as i32, + top + (VIEWPORT_PADDING + row * CELL_H + CELL_H / 2) as i32, + ) +} + +fn decode(bytes: &[u8]) -> DecodedPng { + decode_png(bytes).expect("композитор отдал PNG, который декодируется") +} + +fn pixel(img: &DecodedPng, x: usize, y: usize) -> [u8; 4] { + let i = (y * img.width as usize + x) * 4; + [ + img.rgba[i], + img.rgba[i + 1], + img.rgba[i + 2], + img.rgba[i + 3], + ] +} + +#[test] +fn live_pointer_selection_keeps_fastfetch_glyphs_and_colours() { + let fixture = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fastfetch-guest.script"); + let raw = std::fs::read(&fixture).expect("fastfetch guest fixture"); + + // Та же сетка, что у клиента: — по ней вычисляем клетки логотипа, чтобы + // протяжка шла именно по выводу fastfetch. + let (cols, rows) = layout(CONTENT.0, CONTENT.1); + let mut shell = DemoShell::new(cols, rows); + shell.write(&raw); + let mut logo_first = None; + let mut logo_last = 0usize; + let mut logo_right = 0usize; + for row in 0..rows { + let line = shell.terminal.screen.view_line(row); + for col in 0..cols { + if line.get(col).is_some_and(|cell| cell.ch == '#') { + logo_first.get_or_insert(row); + logo_last = logo_last.max(row); + logo_right = logo_right.max(col); + } + } + } + let first = logo_first.expect("в выводе fastfetch нет '#'-логотипа"); + assert!(logo_right > 10, "логотип подозрительно узкий: {logo_right}"); + + let shots = temp_dir("shots"); + let socket = unique_socket_path("terminal-selection-live"); + let server = Server::spawn(ServerOptions { + socket: socket.clone(), + width: SCREEN.0, + height: SCREEN.1, + quiet: std::env::var("PAGH_E2E_VERBOSE").is_err(), + screenshot_dir: Some(shots.clone()), + ..ServerOptions::default() + }) + .expect("композитор стартует"); + + let empty = capture(&server.control, &shots, "00-empty.png"); + let mut child: Child = Command::new(env!("CARGO_BIN_EXE_pagh-terminal")) + .args([ + "--socket", + socket.to_str().unwrap(), + "--size", + &format!("{}x{}", CONTENT.0, CONTENT.1), + "--feed", + fixture.to_str().unwrap(), + "--title", + "fastfetch — selection", + ]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("pagh-terminal стартует"); + + let mut drawn = None; + assert!( + wait_for(Duration::from_secs(20), || { + let frame = capture(&server.control, &shots, "01-terminal.png"); + if frame != empty { + drawn = Some(frame); + true + } else { + false + } + }), + "окно терминала не появилось на экране композитора" + ); + let before_bytes = drawn.unwrap(); + let before = decode(&before_bytes); + let theme = Theme::default(); + + // Протяжка мышью: от логотипа вправо-вниз по info-колонке. Нажатие в + // контенте (не в заголовке) — композитор фокусирует окно и доставляет + // pointer-события клиенту. + let (sx, sy) = cell_point(1, first); + let (ex, ey) = cell_point(logo_right.min(cols - 1), logo_last); + server.control.mouse_move(sx, sy); + std::thread::sleep(Duration::from_millis(120)); + server.control.mouse_button(1, true); + std::thread::sleep(Duration::from_millis(80)); + let steps = 6; + for step in 1..=steps { + let x = sx + (ex - sx) * step / steps; + let y = sy + (ey - sy) * step / steps; + server.control.mouse_move(x, y); + std::thread::sleep(Duration::from_millis(90)); + } + server.control.mouse_button(1, false); + // Увести указатель из выделения: композитор рисует стрелку поверх кадра, + // и пиксель под ней не даёт сравнить фон/глиф. Motion без нажатой кнопки + // selection не двигает (клиент проверяет held). + server.control.mouse_move(30, 770); + // Все Motion/Button команды обрабатываются по очереди; кадр, снятый в + // середине протяжки, показал бы недорисованное выделение. Даём клиенту + // доработать события и только потом снимаем итоговый кадр. + std::thread::sleep(Duration::from_millis(700)); + + // Подсветка: в кадре композитора те же цвета, что в клиентском канвасе. + let highlight = theme.bg.lerp(theme.selection, SELECTION_BG_MIX); + let x0 = (cell_point(1, first).0 as usize) - 4; + let y0 = (cell_point(1, first).1 as usize) - CELL_H / 2; + let x1 = (cell_point(logo_right.min(cols - 1), logo_last).0 as usize) + 4; + let y1 = (cell_point(logo_right.min(cols - 1), logo_last).1 as usize) + CELL_H / 2; + + // Дождаться устойчивого кадра: два подряд одинаковых снимка *выделенной + // области* (мигающий курсор вне её не должен считаться изменением). + let region = |bytes: &[u8]| -> Vec { + let img = decode(bytes); + let mut out = Vec::with_capacity((x1 - x0) * (y1 - y0) * 4); + for y in y0..y1.min(img.height as usize) { + for x in x0..x1.min(img.width as usize) { + out.extend_from_slice(&pixel(&img, x, y)); + } + } + out + }; + let mut after_bytes = capture(&server.control, &shots, "02-selected-a.png"); + let mut after_region = region(&after_bytes); + let mut stable = false; + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(150)); + let next = capture(&server.control, &shots, "02-selected.png"); + let next_region = region(&next); + if next_region == after_region { + stable = true; + after_bytes = next; + break; + } + after_bytes = next; + after_region = next_region; + } + assert!(stable, "кадр терминала не стабилизировался после выделения"); + assert_ne!( + after_region, + region(&before_bytes), + "выделение не изменило выделенную область кадра" + ); + let after = decode(&after_bytes); + + let mut background = 0usize; + let mut glyph = 0usize; + for y in y0..y1.min(before.height as usize) { + for x in x0..x1.min(before.width as usize) { + let b = pixel(&before, x, y); + let a = pixel(&after, x, y); + if b[..3] == theme.bg.to_array()[..] { + background += 1; + assert_eq!( + a[..3], + highlight.to_array()[..], + "фон выделенной клетки не стал подсветкой в ({x},{y})" + ); + } else if a == b { + // Ядро глифа (полное покрытие): цвет обязан остаться прежним. + glyph += 1; + } + // Остальные не-фоновые пиксели — сглаженные края: они законно + // смешиваются с новым фоном, поэтому их изменение не проверяем. + } + } + assert!( + background > 5_000, + "выделение почти не попало в кадр: фоновых пикселей {background}" + ); + assert!(glyph > 1_000, "в выделении не осталось глифов: {glyph}"); + + server.control.close_window(101); + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + if child.try_wait().expect("try_wait").is_some() { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + let _ = child.kill(); + let _ = child.wait(); + server.control.shutdown(); + server.join().expect("композитор завершился"); + + if let Some(dir) = evidence_dir() { + std::fs::copy(shots.join("01-terminal.png"), dir.join("live-before.png")).unwrap(); + std::fs::copy(shots.join("02-selected.png"), dir.join("live-after.png")).unwrap(); + } + + let _ = std::fs::remove_dir_all(&shots); +}