From 12a6b8df84c84261f54b701e442efef453652f96 Mon Sep 17 00:00:00 2001 From: Mikko Perttunen Date: Thu, 23 Feb 2023 17:35:51 +0200 Subject: [PATCH] termwiz: surface: Fix cursor movement in DiffState DiffState keeps track of a virtual cursor in order to skip emitting cursor location changes when a previous text change has already moved the cursor to the desired position. However, currently the code always advances the cursor by 1 column for each added text change regardless of the width of the text. Fix behavior by advancing the cursor by the width of the text. To avoid having to add a new variable, make 'self.cursor' contain the cursor position for the next cell instead of the current cell. In addition, add a test verifying the behavior. --- termwiz/src/surface/mod.rs | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/termwiz/src/surface/mod.rs b/termwiz/src/surface/mod.rs index f05d2f415..585f1711d 100644 --- a/termwiz/src/surface/mod.rs +++ b/termwiz/src/surface/mod.rs @@ -144,13 +144,11 @@ impl DiffState { #[inline] fn set_cell(&mut self, col_num: usize, row_num: usize, other_cell: CellRef) { self.cursor = match self.cursor.take() { - Some((cursor_row, cursor_col)) - if cursor_row == row_num && cursor_col == col_num - 1 => - { - // It is on the column prior, so we don't need - // to explicitly move it. Record the effective - // position for next time. - Some((row_num, col_num)) + Some((cursor_row, cursor_col)) if cursor_row == row_num && cursor_col == col_num => { + // It is on the current column, so we don't need + // to explicitly move it. Move the cursor by the + // width of the text we're about to add. + Some((row_num, col_num + other_cell.width())) } _ => { // Need to explicitly move the cursor @@ -158,8 +156,8 @@ impl DiffState { y: Position::Absolute(row_num), x: Position::Absolute(col_num), }); - // and remember the position for next time - Some((row_num, col_num)) + // and update the position for next time + Some((row_num, col_num + other_cell.width())) } }; @@ -1612,6 +1610,23 @@ mod test { assert_eq!(s.screen_chars_to_string(), "abcd\n"); } + #[test] + fn diff_cursor_double_width() { + let mut s = Surface::new(3, 1); + s.add_change("かa"); + + let s2 = Surface::new(3, 1); + let changes = s2.diff_region(0, 0, 3, 1, &s, 0, 0); + + assert_eq!( + changes + .iter() + .filter(|change| matches!(change, Change::CursorPosition { .. })) + .count(), + 1 + ); + } + #[test] fn zero_width() { let mut s = Surface::new(4, 1);