1use ratatui::buffer::Cell;
7use ratatui::style::{Color, Modifier};
8
9use super::state::{CursorState, PaneBuffer, ScrollOp};
10
11#[derive(Debug, Clone)]
17pub struct CellDelta {
18 pub x: u16,
19 pub y: u16,
20 pub symbol: String,
21 pub fg: Color,
22 pub bg: Color,
23 pub modifiers: Modifier,
24}
25
26#[derive(Debug)]
28pub struct FrameDiff {
29 pub is_full: bool,
31 pub cols: u16,
33 pub rows: u16,
34 pub scrolls: Vec<ScrollOp>,
36 pub deltas: Vec<CellDelta>,
38 pub cursor: CursorState,
40 pub generation: u64,
42}
43
44pub fn compute_diff(
53 pane: &PaneBuffer,
54 prev: Option<&[Cell]>,
55 generation: u64,
56 cursor: CursorState,
57) -> FrameDiff {
58 let area = pane.buffer.area();
59 let cols = area.width;
60 let rows = area.height;
61
62 let is_full = pane.force_full_frame || prev.is_none() || pane.dirty_count() > (rows as u32) / 2;
63
64 if is_full {
65 let mut deltas = Vec::with_capacity(cols as usize * rows as usize);
67 for y in 0..rows {
68 for x in 0..cols {
69 let cell = &pane.buffer[(x, y)];
70 deltas.push(CellDelta {
71 x,
72 y,
73 symbol: cell.symbol().to_owned(),
74 fg: cell.fg,
75 bg: cell.bg,
76 modifiers: cell.modifier,
77 });
78 }
79 }
80 FrameDiff {
81 is_full: true,
82 cols,
83 rows,
84 scrolls: Vec::new(),
85 deltas,
86 cursor,
87 generation,
88 }
89 } else {
90 let scrolls = pane.scroll_log.clone();
92 let mut deltas = Vec::new();
93
94 if let Some(prev_cells) = prev {
95 for y in 0..rows {
96 if !pane.is_row_dirty(y) {
97 continue;
98 }
99 for x in 0..cols {
100 let cell = &pane.buffer[(x, y)];
101 let prev_idx = y as usize * cols as usize + x as usize;
102 let changed = if prev_idx < prev_cells.len() {
103 let pc = &prev_cells[prev_idx];
104 cell.symbol() != pc.symbol()
105 || cell.fg != pc.fg
106 || cell.bg != pc.bg
107 || cell.modifier != pc.modifier
108 } else {
109 true
110 };
111 if changed {
112 deltas.push(CellDelta {
113 x,
114 y,
115 symbol: cell.symbol().to_owned(),
116 fg: cell.fg,
117 bg: cell.bg,
118 modifiers: cell.modifier,
119 });
120 }
121 }
122 }
123 }
124
125 FrameDiff {
126 is_full: false,
127 cols,
128 rows,
129 scrolls,
130 deltas,
131 cursor,
132 generation,
133 }
134 }
135}
136
137pub fn encode_ansi(diff: &FrameDiff) -> Vec<u8> {
147 let mut out = Vec::with_capacity(diff.deltas.len() * 20);
148
149 for scroll in &diff.scrolls {
151 write_ansi!(out, "\x1b[{};{}r", scroll.top + 1, scroll.bottom + 1);
153 if scroll.amount > 0 {
154 write_ansi!(out, "\x1b[{}S", scroll.amount);
156 } else if scroll.amount < 0 {
157 write_ansi!(out, "\x1b[{}T", -scroll.amount);
159 }
160 write_ansi!(out, "\x1b[r");
162 }
163
164 let mut last_x: Option<u16> = None;
166 let mut last_y: Option<u16> = None;
167 let mut last_fg: Option<Color> = None;
168 let mut last_bg: Option<Color> = None;
169 let mut last_mods: Option<Modifier> = None;
170
171 for delta in &diff.deltas {
172 let need_move = match (last_x, last_y) {
174 (Some(lx), Some(ly)) => !(ly == delta.y && lx == delta.x),
175 _ => true,
176 };
177 if need_move {
178 write_ansi!(out, "\x1b[{};{}H", delta.y + 1, delta.x + 1);
179 }
180
181 let fg_changed = last_fg != Some(delta.fg);
183 let bg_changed = last_bg != Some(delta.bg);
184 let mods_changed = last_mods != Some(delta.modifiers);
185
186 if fg_changed || bg_changed || mods_changed {
187 waxterm::sgr::write_combined_sgr(&mut out, delta.fg, delta.bg, delta.modifiers)
188 .unwrap_or(());
189 last_fg = Some(delta.fg);
190 last_bg = Some(delta.bg);
191 last_mods = Some(delta.modifiers);
192 }
193
194 out.extend_from_slice(delta.symbol.as_bytes());
196
197 let char_width = if delta.symbol.len() > 1 {
199 unicode_width(&delta.symbol)
201 } else {
202 1
203 };
204 last_x = Some(delta.x + char_width as u16);
205 last_y = Some(delta.y);
206 }
207
208 out.extend_from_slice(b"\x1b[0m");
210
211 if diff.cursor.visible {
213 write_ansi!(out, "\x1b[?25h");
214 write_ansi!(out, "\x1b[{};{}H", diff.cursor.y + 1, diff.cursor.x + 1);
215 } else {
216 write_ansi!(out, "\x1b[?25l");
217 }
218
219 out
220}
221
222fn unicode_width(s: &str) -> usize {
224 s.chars().next().map_or(1, |c| {
225 if c.is_ascii() {
226 1
227 } else {
228 let cp = c as u32;
230 if (0x1100..=0x115F).contains(&cp)
231 || (0x2E80..=0x303E).contains(&cp)
232 || (0x3040..=0x9FFF).contains(&cp)
233 || (0xAC00..=0xD7AF).contains(&cp)
234 || (0xF900..=0xFAFF).contains(&cp)
235 || (0xFE10..=0xFE6F).contains(&cp)
236 || (0xFF01..=0xFF60).contains(&cp)
237 || (0xFFE0..=0xFFE6).contains(&cp)
238 || (0x20000..=0x2FA1F).contains(&cp)
239 {
240 2
241 } else {
242 1
243 }
244 }
245 })
246}
247
248macro_rules! write_ansi {
250 ($buf:expr, $fmt:expr $(, $arg:expr)*) => {
251 {
252 use std::io::Write;
253 let _ = write!($buf, $fmt $(, $arg)*);
254 }
255 };
256}
257use write_ansi;
258
259pub fn encode_capnp(diff: &FrameDiff, pane_id: u32) -> Vec<u8> {
269 use capnp::message::Builder;
270 use capnp::serialize;
271
272 let mut message = Builder::new_default();
273 {
274 let mut frame =
275 message.init_root::<hyprstream_rpc_std::tui_capnp::tui_frame::Builder<'_>>();
276 frame.set_generation(diff.generation);
277 frame.set_timestamp_ms(
278 std::time::SystemTime::now()
279 .duration_since(std::time::UNIX_EPOCH)
280 .unwrap_or_default()
281 .as_millis() as u64,
282 );
283 frame.set_pane_id(pane_id);
284
285 let mut cursor = frame.reborrow().init_cursor();
287 cursor.set_x(diff.cursor.x);
288 cursor.set_y(diff.cursor.y);
289 cursor.set_visible(diff.cursor.visible);
290
291 if diff.is_full {
292 let mut full = frame.init_full();
293 full.set_cols(diff.cols);
294 full.set_rows(diff.rows);
295 let mut cells = full.init_cells(diff.deltas.len() as u32);
296 for (i, delta) in diff.deltas.iter().enumerate() {
297 let mut cell = cells.reborrow().get(i as u32);
298 cell.set_x(delta.x);
299 cell.set_y(delta.y);
300 cell.set_symbol(&delta.symbol);
301 cell.set_fg(pack_color(delta.fg));
302 cell.set_bg(pack_color(delta.bg));
303 cell.set_modifiers(delta.modifiers.bits());
304 }
305 } else {
306 let mut incr = frame.init_incremental();
307 let mut scrolls = incr.reborrow().init_scrolls(diff.scrolls.len() as u32);
308 for (i, scroll) in diff.scrolls.iter().enumerate() {
309 let mut s = scrolls.reborrow().get(i as u32);
310 s.set_top(scroll.top);
311 s.set_bottom(scroll.bottom);
312 s.set_amount(scroll.amount);
313 }
314 let mut deltas = incr.init_deltas(diff.deltas.len() as u32);
315 for (i, delta) in diff.deltas.iter().enumerate() {
316 let mut cell = deltas.reborrow().get(i as u32);
317 cell.set_x(delta.x);
318 cell.set_y(delta.y);
319 cell.set_symbol(&delta.symbol);
320 cell.set_fg(pack_color(delta.fg));
321 cell.set_bg(pack_color(delta.bg));
322 cell.set_modifiers(delta.modifiers.bits());
323 }
324 }
325 }
326
327 let mut buf = Vec::new();
328 serialize::write_message(&mut buf, &message).unwrap_or(());
329 buf
330}
331
332pub(crate) fn pack_color(color: Color) -> u32 {
336 match color {
337 Color::Reset => 0,
338 Color::Black => 1,
339 Color::Red => 2,
340 Color::Green => 3,
341 Color::Yellow => 4,
342 Color::Blue => 5,
343 Color::Magenta => 6,
344 Color::Cyan => 7,
345 Color::Gray => 8,
346 Color::DarkGray => 9,
347 Color::LightRed => 10,
348 Color::LightGreen => 11,
349 Color::LightYellow => 12,
350 Color::LightBlue => 13,
351 Color::LightMagenta => 14,
352 Color::LightCyan => 15,
353 Color::White => 16,
354 Color::Rgb(r, g, b) => ((r as u32) << 16) | ((g as u32) << 8) | (b as u32) | 0x0100_0000,
355 Color::Indexed(i) => 0x0200_0000 | (i as u32),
356 }
357}
358
359pub fn unpack_color(packed: u32) -> Color {
361 if packed & 0x0200_0000 != 0 {
362 Color::Indexed((packed & 0xFF) as u8)
363 } else if packed & 0x0100_0000 != 0 {
364 Color::Rgb(
365 ((packed >> 16) & 0xFF) as u8,
366 ((packed >> 8) & 0xFF) as u8,
367 (packed & 0xFF) as u8,
368 )
369 } else {
370 match packed {
371 1 => Color::Black,
372 2 => Color::Red,
373 3 => Color::Green,
374 4 => Color::Yellow,
375 5 => Color::Blue,
376 6 => Color::Magenta,
377 7 => Color::Cyan,
378 8 => Color::Gray,
379 9 => Color::DarkGray,
380 10 => Color::LightRed,
381 11 => Color::LightGreen,
382 12 => Color::LightYellow,
383 13 => Color::LightBlue,
384 14 => Color::LightMagenta,
385 15 => Color::LightCyan,
386 16 => Color::White,
387 _ => Color::Reset,
388 }
389 }
390}
391
392#[cfg(test)]
397mod tests {
398 use super::*;
399
400 #[test]
401 fn test_empty_diff() {
402 let buf = PaneBuffer::new(80, 24);
403 let diff = compute_diff(&buf, None, 1, CursorState::default());
404 assert!(diff.is_full);
405 assert_eq!(diff.deltas.len(), 80 * 24);
406 }
407
408 #[test]
409 fn test_color_roundtrip() {
410 let colors = [
411 Color::Reset,
412 Color::Black,
413 Color::Red,
414 Color::White,
415 Color::Rgb(255, 128, 0),
416 Color::Indexed(42),
417 ];
418 for c in &colors {
419 assert_eq!(
420 unpack_color(pack_color(*c)),
421 *c,
422 "roundtrip failed for {:?}",
423 c
424 );
425 }
426 }
427
428 #[test]
429 fn test_incremental_single_cell() {
430 let mut buf = PaneBuffer::new(10, 5);
431 buf.clear_damage();
432
433 buf.buffer[(3, 2)].set_symbol("X");
435 buf.mark_dirty(2);
436
437 let prev: Vec<Cell> = (0..50).map(|_| Cell::default()).collect();
439 let diff = compute_diff(&buf, Some(&prev), 2, CursorState::default());
440
441 assert!(!diff.is_full);
442 assert!(!diff.deltas.is_empty());
443 }
444
445 #[test]
446 fn test_full_frame_threshold() {
447 let mut buf = PaneBuffer::new(10, 4);
448 buf.clear_damage();
449
450 buf.mark_dirty(0);
452 buf.mark_dirty(1);
453 buf.mark_dirty(2);
454
455 let prev: Vec<Cell> = (0..40).map(|_| Cell::default()).collect();
456 let diff = compute_diff(&buf, Some(&prev), 3, CursorState::default());
457
458 assert!(diff.is_full);
459 }
460
461 #[test]
462 fn test_encode_ansi_gap_cursor_position() {
463 let deltas = vec![
471 CellDelta {
472 x: 0,
473 y: 0,
474 symbol: "A".to_owned(),
475 fg: Color::Reset,
476 bg: Color::Reset,
477 modifiers: Modifier::empty(),
478 },
479 CellDelta {
480 x: 2,
481 y: 0,
482 symbol: "B".to_owned(),
483 fg: Color::Reset,
484 bg: Color::Reset,
485 modifiers: Modifier::empty(),
486 },
487 ];
488 let diff = FrameDiff {
489 is_full: false,
490 cols: 10,
491 rows: 1,
492 scrolls: vec![],
493 deltas,
494 cursor: CursorState::default(),
495 generation: 1,
496 };
497 let ansi = encode_ansi(&diff);
498 let s = String::from_utf8_lossy(&ansi);
499 assert!(s.contains("\x1b[1;3H"), "Missing CUP for x=2: {:?}", s);
501 }
502}