From fe890827647e96d480149949cfa5740c7ad9bea4 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 5 Apr 2020 11:08:25 -0700 Subject: [PATCH] termwiz: remove Position::NoChange, fixup multiline line editing and moar! This is unfortunately a bit of a muddy commit and I'm too lazy to split it up. * Removed `Position::NoChange`; use `Position::Relative(0)` instead * Added missing cursor positioning cases in the terminfo renderer * Taught line editor about the cursor position when the line spans multiple physical lines * Taught the Windows input layer to process escape sequences for eg: the arrow keys when running with virtual terminal enabled. * Removed the hack that under-reported the terminal width; the hack was present to make some aspects of rendering with the native windows console logic easier, but it was getting in the way of the line editor. This may well break something, but it fixed up the line editor :-/ cc: @markbt --- src/connui.rs | 4 +- termwiz/src/input.rs | 16 +- termwiz/src/lineedit/mod.rs | 34 +++- termwiz/src/render/terminfo.rs | 301 +++++++++++++++++--------------- termwiz/src/render/windows.rs | 3 +- termwiz/src/surface/mod.rs | 19 +- termwiz/src/terminal/windows.rs | 14 +- 7 files changed, 214 insertions(+), 177 deletions(-) diff --git a/src/connui.rs b/src/connui.rs index a21e58564..aebdc7a79 100644 --- a/src/connui.rs +++ b/src/connui.rs @@ -154,7 +154,7 @@ impl ConnectionUIImpl { self.term.render(&[ Change::CursorPosition { x: Position::Absolute(0), - y: Position::NoChange, + y: Position::Relative(0), }, Change::AllAttributes(CellAttributes::default().set_reverse(true).clone()), Change::Text(reversed_string), @@ -176,7 +176,7 @@ impl ConnectionUIImpl { self.term.render(&[ Change::CursorPosition { x: Position::Absolute(0), - y: Position::NoChange, + y: Position::Relative(0), }, Change::Text(message), ])?; diff --git a/termwiz/src/input.rs b/termwiz/src/input.rs index 676c977ad..61abfe0f2 100644 --- a/termwiz/src/input.rs +++ b/termwiz/src/input.rs @@ -253,7 +253,7 @@ mod windows { } impl InputParser { fn decode_key_record( - &self, + &mut self, event: &KEY_EVENT_RECORD, callback: &mut F, ) { @@ -265,14 +265,10 @@ mod windows { let key_code = match std::char::from_u32(*unsafe { event.uChar.UnicodeChar() } as u32) { Some(unicode) if unicode > '\x00' => { let mut buf = [0u8; 4]; - - match self.key_map.lookup(unicode.encode_utf8(&mut buf)) { - Found::Exact(_, event) | Found::Ambiguous(_, event) => { - callback(event.clone()); - return; - } - _ => KeyCode::Char(unicode), - } + self.buf + .extend_with(unicode.encode_utf8(&mut buf).as_bytes()); + self.process_bytes(callback, true); + return; } _ => match event.wVirtualKeyCode as i32 { winuser::VK_CANCEL => KeyCode::Cancel, @@ -445,7 +441,7 @@ mod windows { } pub fn decode_input_records( - &self, + &mut self, records: &[INPUT_RECORD], callback: &mut F, ) { diff --git a/termwiz/src/lineedit/mod.rs b/termwiz/src/lineedit/mod.rs index 8de200607..fecf51c50 100644 --- a/termwiz/src/lineedit/mod.rs +++ b/termwiz/src/lineedit/mod.rs @@ -75,6 +75,11 @@ pub struct LineEditor { bottom_line: Option, completion: Option, + + /// How many rows of text we last output + last_render_height: usize, + /// on which row of the last render we think the cursor is + last_render_cursor_y: usize, } struct CompletionState { @@ -136,20 +141,25 @@ impl LineEditor { history_pos: None, bottom_line: None, completion: None, + last_render_height: 1, + last_render_cursor_y: 0, } } fn render(&mut self, host: &mut dyn LineEditorHost) -> anyhow::Result<()> { + let screen_size = self.terminal.get_screen_size()?; + let mut changes = vec![ Change::CursorPosition { x: Position::Absolute(0), - y: Position::NoChange, + y: Position::Relative(-1 * self.last_render_cursor_y as isize), }, Change::ClearToEndOfScreen(Default::default()), Change::AllAttributes(Default::default()), ]; let mut prompt_width = 0; + for ele in host.render_prompt(&self.prompt) { if let OutputElement::Text(ref t) = ele { prompt_width += unicode_column_width(t.as_str()); @@ -159,12 +169,27 @@ impl LineEditor { changes.push(Change::AllAttributes(Default::default())); let (elements, cursor_x_pos) = host.highlight_line(&self.line, self.cursor); + let mut output_width = 0; for ele in elements { + if let OutputElement::Text(ref t) = ele { + output_width += unicode_column_width(t.as_str()); + } changes.push(ele.into()); } + + let visible_cursor_column = (prompt_width + cursor_x_pos) % screen_size.cols; + if visible_cursor_column == 0 { + changes.push("\r\n".into()); + } + + self.last_render_height = 1 + ((prompt_width + output_width) / screen_size.cols); + self.last_render_cursor_y = (prompt_width + cursor_x_pos) / screen_size.cols; + changes.push(Change::CursorPosition { - x: Position::Absolute(prompt_width + cursor_x_pos), - y: Position::NoChange, + x: Position::Absolute(visible_cursor_column), + y: Position::Relative( + (1 + self.last_render_cursor_y as isize) - (self.last_render_height as isize), + ), }); self.terminal.render(&changes)?; @@ -409,7 +434,8 @@ impl LineEditor { } Movement::StartOfLine => 0, Movement::EndOfLine => { - let mut cursor = GraphemeCursor::new(self.line.len() - 1, self.line.len(), false); + let mut cursor = + GraphemeCursor::new(self.line.len().saturating_sub(1), self.line.len(), false); if let Ok(Some(pos)) = cursor.next_boundary(&self.line, 0) { pos } else { diff --git a/termwiz/src/render/terminfo.rs b/termwiz/src/render/terminfo.rs index de34d1b17..52d20aafe 100644 --- a/termwiz/src/render/terminfo.rs +++ b/termwiz/src/render/terminfo.rs @@ -8,7 +8,6 @@ use crate::escape::OneBased; use crate::image::TextureCoordinate; use crate::render::RenderTty; use crate::surface::{Change, CursorShape, Position}; -use log::error; use std::io::Write; use terminfo::{capability as cap, Capability as TermInfoCapability}; @@ -206,41 +205,105 @@ impl TerminfoRenderer { } fn cursor_up(&mut self, n: u32, out: &mut W) -> anyhow::Result<()> { - if let Some(attr) = self.get_capability::() { - attr.expand().count(n).to(out.by_ref())?; - } else { - write!(out, "{}", CSI::Cursor(Cursor::Up(n)))?; + if n > 0 { + if let Some(attr) = self.get_capability::() { + attr.expand().count(n).to(out.by_ref())?; + } else { + write!(out, "{}", CSI::Cursor(Cursor::Up(n)))?; + } } Ok(()) } + fn cursor_down(&mut self, n: u32, out: &mut W) -> anyhow::Result<()> { - if let Some(attr) = self.get_capability::() { - attr.expand().count(n).to(out.by_ref())?; - } else { - write!(out, "{}", CSI::Cursor(Cursor::Down(n)))?; + if n > 0 { + if let Some(attr) = self.get_capability::() { + attr.expand().count(n).to(out.by_ref())?; + } else { + write!(out, "{}", CSI::Cursor(Cursor::Down(n)))?; + } } Ok(()) } + fn cursor_y_relative( + &mut self, + y: isize, + out: &mut W, + ) -> anyhow::Result<()> { + if y > 0 { + self.cursor_down(y as u32, out) + } else { + self.cursor_up(-y as u32, out) + } + } + fn cursor_left(&mut self, n: u32, out: &mut W) -> anyhow::Result<()> { - if let Some(attr) = self.get_capability::() { - attr.expand().count(n).to(out.by_ref())?; + if n > 0 { + if let Some(attr) = self.get_capability::() { + attr.expand().count(n).to(out.by_ref())?; + } else { + write!(out, "{}", CSI::Cursor(Cursor::Left(n)))?; + } + } + Ok(()) + } + + fn cursor_right(&mut self, n: u32, out: &mut W) -> anyhow::Result<()> { + if n > 0 { + if let Some(attr) = self.get_capability::() { + attr.expand().count(n).to(out.by_ref())?; + } else { + write!(out, "{}", CSI::Cursor(Cursor::Right(n)))?; + } + } + Ok(()) + } + + fn cursor_x_relative( + &mut self, + x: isize, + out: &mut W, + ) -> anyhow::Result<()> { + if x > 0 { + self.cursor_right(x as u32, out) } else { - write!(out, "{}", CSI::Cursor(Cursor::Left(n)))?; + self.cursor_left(-x as u32, out) + } + } + + fn move_cursor_absolute( + &mut self, + x: u32, + y: u32, + out: &mut W, + ) -> anyhow::Result<()> { + if x == 0 && y == 0 { + if let Some(attr) = self.get_capability::() { + attr.expand().to(out.by_ref())?; + return Ok(()); + } + } + + if let Some(attr) = self.get_capability::() { + // terminfo expansion automatically converts coordinates to 1-based, + // so we can pass in the 0-based coordinates as-is + attr.expand().x(x).y(y).to(out.by_ref())?; + } else { + // We need to manually convert to 1-based as the CSI representation + // requires it and there's no automatic conversion. + write!( + out, + "{}", + CSI::Cursor(Cursor::Position { + line: OneBased::from_zero_based(x), + col: OneBased::from_zero_based(y), + }) + )?; } Ok(()) } - fn cursor_right(&mut self, n: u32, out: &mut W) -> anyhow::Result<()> { - if let Some(attr) = self.get_capability::() { - attr.expand().count(n).to(out.by_ref())?; - } else { - write!(out, "{}", CSI::Cursor(Cursor::Right(n)))?; - } - Ok(()) - } -} -impl TerminfoRenderer { #[cfg_attr( feature = "cargo-clippy", allow(clippy::cyclomatic_complexity, clippy::cognitive_complexity) @@ -278,19 +341,7 @@ impl TerminfoRenderer { if let Some(clr) = self.get_capability::() { clr.expand().to(out.by_ref())?; } else { - if let Some(attr) = self.get_capability::() { - attr.expand().to(out.by_ref())?; - } else { - write!( - out, - "{}", - CSI::Cursor(Cursor::Position { - line: OneBased::new(1), - col: OneBased::new(1) - }) - )?; - } - + self.move_cursor_absolute(0, 0, out)?; write!( out, "{}", @@ -300,19 +351,7 @@ impl TerminfoRenderer { } else { // We're setting the background to a specific color, so we get to // paint the whole thing. - - if let Some(attr) = self.get_capability::() { - attr.expand().to(out.by_ref())?; - } else { - write!( - out, - "{}", - CSI::Cursor(Cursor::Position { - line: OneBased::new(1), - col: OneBased::new(1) - }) - )?; - } + self.move_cursor_absolute(0, 0, out)?; let (cols, rows) = out.get_size_in_cells()?; let num_spaces = cols * rows; @@ -406,101 +445,81 @@ impl TerminfoRenderer { self.flush_pending_attr(out)?; out.by_ref().write_all(text.as_bytes())?; } - Change::CursorPosition { - x: Position::Absolute(0), - y: Position::Relative(1), - } => { - out.by_ref().write_all(b"\r\n")?; - } - Change::CursorPosition { - x: Position::Absolute(0), - y: Position::NoChange, - } - | Change::CursorPosition { - x: Position::Absolute(0), - y: Position::Relative(0), - } => { - out.by_ref().write_all(b"\r")?; - } - Change::CursorPosition { - x: Position::Absolute(0), - y: Position::Absolute(0), - } => { - if let Some(attr) = self.get_capability::() { - attr.expand().to(out.by_ref())?; - } else { - write!( - out, - "{}", - CSI::Cursor(Cursor::Position { - line: OneBased::new(1), - col: OneBased::new(1) - }) - )?; + + Change::CursorPosition { x, y } => { + // Note: we use `cursor_up(screen_height)` to move the cursor all the way to + // the top of the screen when we need to absolutely position only y. + + match (x, y) { + (Position::Relative(0), Position::Relative(0)) => {} + (Position::Absolute(0), Position::Relative(1)) => { + out.by_ref().write_all(b"\r\n")?; + } + (Position::Absolute(0), Position::Relative(0)) => { + out.by_ref().write_all(b"\r")?; + } + + (Position::Relative(x), Position::EndRelative(y)) => { + let (_cols, rows) = out.get_size_in_cells()?; + self.cursor_up(rows as u32, out)?; + self.cursor_down(rows.saturating_sub(y + 1) as u32, out)?; + self.cursor_x_relative(*x, out)?; + } + (Position::Relative(x), Position::Relative(y)) => { + self.cursor_y_relative(*y, out)?; + self.cursor_x_relative(*x, out)?; + } + (Position::EndRelative(x), Position::Relative(y)) => { + self.cursor_y_relative(*y, out)?; + let (cols, _rows) = out.get_size_in_cells()?; + out.by_ref().write_all(b"\r")?; + self.cursor_right(cols.saturating_sub(x + 1) as u32, out)?; + } + + (Position::Absolute(x), Position::Absolute(y)) => { + self.move_cursor_absolute(*x as u32, *y as u32, out)?; + } + (Position::Absolute(x), Position::EndRelative(y)) => { + let (_cols, rows) = out.get_size_in_cells()?; + self.move_cursor_absolute( + *x as u32, + rows.saturating_sub(y + 1) as u32, + out, + )?; + } + (Position::EndRelative(x), Position::EndRelative(y)) => { + let (cols, rows) = out.get_size_in_cells()?; + self.move_cursor_absolute( + cols.saturating_sub(x + 1) as u32, + rows.saturating_sub(y + 1) as u32, + out, + )?; + } + + (Position::Relative(x), Position::Absolute(y)) => { + let (_cols, rows) = out.get_size_in_cells()?; + self.cursor_up(rows as u32, out)?; + self.cursor_down(*y as u32, out)?; + self.cursor_x_relative(*x, out)?; + } + + (Position::Absolute(x), Position::Relative(y)) => { + self.cursor_y_relative(*y, out)?; + out.by_ref().write_all(b"\r")?; + self.cursor_right(*x as u32, out)?; + } + + (Position::EndRelative(x), Position::Absolute(y)) => { + let (cols, _rows) = out.get_size_in_cells()?; + self.move_cursor_absolute( + cols.saturating_sub(x + 1) as u32, + *y as u32, + out, + )?; + } } } - Change::CursorPosition { - x: Position::NoChange, - y: Position::Relative(n), - } if *n > 0 => { - self.cursor_down(*n as u32, out)?; - } - Change::CursorPosition { - x: Position::NoChange, - y: Position::Relative(n), - } if *n < 0 => { - self.cursor_up(-*n as u32, out)?; - } - Change::CursorPosition { - x: Position::Relative(n), - y: Position::NoChange, - } if *n < 0 => { - self.cursor_left(-*n as u32, out)?; - } - Change::CursorPosition { - x: Position::Relative(n), - y: Position::NoChange, - } if *n > 0 => { - self.cursor_right(*n as u32, out)?; - } - Change::CursorPosition { - x: Position::Absolute(n), - y: Position::NoChange, - } => { - out.by_ref().write_all(b"\r")?; - if *n > 0 { - self.cursor_right(*n as u32, out)?; - } - } - Change::CursorPosition { - x: Position::Absolute(x), - y: Position::Absolute(y), - } => { - let x = *x as u32; - let y = *y as u32; - if let Some(attr) = self.get_capability::() { - // terminfo expansion automatically converts coordinates to 1-based, - // so we can pass in the 0-based coordinates as-is - attr.expand().x(x).y(y).to(out.by_ref())?; - } else { - // We need to manually convert to 1-based as the CSI representation - // requires it and there's no automatic conversion. - write!( - out, - "{}", - CSI::Cursor(Cursor::Position { - line: OneBased::from_zero_based(x), - col: OneBased::from_zero_based(y), - }) - )?; - } - } - Change::CursorPosition { .. } => { - error!( - "unhandled CursorPosition in TerminfoRenderer::render_to: {:?}", - change - ); - } + Change::CursorColor(_color) => { // TODO: this isn't spec'd by terminfo, but some terminals // support it. Add this to capabilities? diff --git a/termwiz/src/render/windows.rs b/termwiz/src/render/windows.rs index 2d7c0fcef..6baaff036 100644 --- a/termwiz/src/render/windows.rs +++ b/termwiz/src/render/windows.rs @@ -209,15 +209,14 @@ impl WindowsConsoleRenderer { // For horizontal cursor movement, we consider the full width // of the screen buffer, even if the viewport is smaller let x = match x { - Position::NoChange => info.dwCursorPosition.X, Position::Absolute(x) => *x as i16, Position::Relative(delta) => info.dwCursorPosition.X + *delta as i16, Position::EndRelative(delta) => info.dwSize.X - *delta as i16, }; + // For vertical cursor movement, we constrain the movement to // the viewport. let y = match y { - Position::NoChange => info.dwCursorPosition.Y, Position::Absolute(y) => info.srWindow.Top + *y as i16, Position::Relative(delta) => info.dwCursorPosition.Y + *delta as i16, Position::EndRelative(delta) => info.srWindow.Bottom - *delta as i16, diff --git a/termwiz/src/surface/mod.rs b/termwiz/src/surface/mod.rs index 69752aac7..2d7566c5d 100644 --- a/termwiz/src/surface/mod.rs +++ b/termwiz/src/surface/mod.rs @@ -18,10 +18,9 @@ pub use self::line::Line; /// Relative(0) is the current position in the line or /// column and EndRelative(0) is the end position in the /// line or column. -#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] pub enum Position { - NoChange, - /// Negative values move up, positive values down + /// Negative values move up, positive values down, 0 means no change Relative(isize), /// Relative to the start of the line or top of the screen Absolute(usize), @@ -229,8 +228,8 @@ impl Surface { } // Ensure that the cursor position is well-defined - self.xpos = compute_position_change(self.xpos, &Position::NoChange, self.width); - self.ypos = compute_position_change(self.ypos, &Position::NoChange, self.height); + self.xpos = compute_position_change(self.xpos, &Position::Relative(0), self.width); + self.ypos = compute_position_change(self.ypos, &Position::Relative(0), self.height); } /// Efficiently apply a series of changes @@ -831,15 +830,17 @@ impl Surface { fn compute_position_change(current: usize, pos: &Position, limit: usize) -> usize { use self::Position::*; match pos { - NoChange => min(current, limit.saturating_sub(1)), Relative(delta) => { - if *delta > 0 { - min(current.saturating_add(*delta as usize), limit - 1) + if *delta >= 0 { + min( + current.saturating_add(*delta as usize), + limit.saturating_sub(1), + ) } else { current.saturating_sub((*delta).abs() as usize) } } - Absolute(abs) => min(*abs, limit - 1), + Absolute(abs) => min(*abs, limit.saturating_sub(1)), EndRelative(delta) => limit.saturating_sub(*delta), } } diff --git a/termwiz/src/terminal/windows.rs b/termwiz/src/terminal/windows.rs index 406213fd8..8db63ab93 100644 --- a/termwiz/src/terminal/windows.rs +++ b/termwiz/src/terminal/windows.rs @@ -149,12 +149,7 @@ impl OutputHandle { } fn dimensions_from_buffer_info(info: CONSOLE_SCREEN_BUFFER_INFO) -> (usize, usize) { - // NOTE: the default console behavior is different from unix style - // terminals wrt. handling printing in the last column position. - // We under report the width by one to make it easier to have similar - // semantics to unix style terminals. - - let cols = 0 + (info.srWindow.Right - info.srWindow.Left); + let cols = 1 + (info.srWindow.Right - info.srWindow.Left); let rows = 1 + (info.srWindow.Bottom - info.srWindow.Top); (cols as usize, rows as usize) } @@ -292,7 +287,9 @@ impl ConsoleOutputHandle for OutputHandle { } == 0 { bail!( - "SetConsoleCursorPosition failed: {}", + "SetConsoleCursorPosition(x={}, y={}) failed: {}", + x, + y, IoError::last_os_error() ); } @@ -559,8 +556,7 @@ impl Terminal for WindowsTerminal { // FIXME: take into account the visible window size here; // this probably changes the size of everything including scrollback let size = COORD { - // See the note in get_screen_size() for info on the +1. - X: cast(size.cols + 1)?, + X: cast(size.cols)?, Y: cast(size.rows)?, }; let handle = self.output_handle.handle.as_raw_handle();