From 0ebf84ee1cc636b3b5c344fb3552dccbe34c48a3 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Mon, 29 Jan 2018 20:38:48 -0800 Subject: [PATCH] adopt dirtying mechanism for more efficient screen updates We now keep track of the dirty status on a per-line basis and use that status to realize when we need to repaint a portion of the screen. This reduces the compute cost of redrawing quite significantly; we're no longer on `top` when we're running `top`! --- src/term/mod.rs | 129 ++++++++++++++++++++++++++--------- src/xwin.rs | 178 +++++++++++++++++++++++------------------------- 2 files changed, 184 insertions(+), 123 deletions(-) diff --git a/src/term/mod.rs b/src/term/mod.rs index 05220cbbd..94034d159 100644 --- a/src/term/mod.rs +++ b/src/term/mod.rs @@ -171,6 +171,7 @@ impl Cell { #[derive(Debug, Clone)] pub struct Line { pub cells: Vec, + dirty: bool, } impl Line { @@ -179,7 +180,7 @@ impl Line { pub fn new(cols: usize) -> Line { let mut cells = Vec::with_capacity(cols); cells.resize(cols, Default::default()); - Line { cells } + Line { cells, dirty: true } } /// Recompose line into the corresponding utf8 string. @@ -193,6 +194,7 @@ impl Line { s } + #[allow(dead_code)] pub fn from_text(s: &str, attrs: &CellAttributes) -> Line { let mut cells = Vec::new(); @@ -207,7 +209,17 @@ impl Line { }); } - Line { cells } + Line { cells, dirty: true } + } + + #[inline] + fn set_dirty(&mut self) { + self.dirty = true; + } + + #[inline] + fn set_clean(&mut self) { + self.dirty = false; } } @@ -225,7 +237,7 @@ pub struct Screen { /// on the current window size) and will be the first line to be /// popped off the front of the screen when a new line is added that /// would otherwise have exceeded the line capacity - pub lines: Vec, + lines: Vec, /// Maximum number of lines of scrollback scrollback_size: usize, @@ -272,6 +284,29 @@ impl Screen { self.physical_cols = physical_cols; } + /// Get mutable reference to a line, relative to start of scrollback. + /// Sets the line dirty. + fn line_mut(&mut self, idx: usize) -> &mut Line { + let line = &mut self.lines[idx]; + line.set_dirty(); + line + } + + /// Sets a line dirty. The line is relative to the visible origin. + #[inline] + fn dirty_line(&mut self, idx: usize) { + let line_idx = (self.lines.len() - self.physical_rows) + idx; + self.lines[line_idx].set_dirty(); + } + + /// Clears the dirty flag for a line. The line is relative to the visible origin. + #[inline] + #[allow(dead_code)] + fn clean_line(&mut self, idx: usize) { + let line_idx = (self.lines.len() - self.physical_rows) + idx; + self.lines[line_idx].dirty = false; + } + /// Set a cell. the x and y coordinates are relative to the visible screeen /// origin. 0,0 is the top left. pub fn set_cell(&mut self, x: usize, y: usize, c: char, attr: &CellAttributes) { @@ -284,7 +319,8 @@ impl Screen { c, attr ); - let cells = &mut self.lines[line_idx].cells; + + let cells = &mut self.line_mut(line_idx).cells; let width = cells.len(); // if the line isn't wide enough, pad it out with the default attributes if x >= width { @@ -296,7 +332,7 @@ impl Screen { pub fn clear_line(&mut self, y: usize, cols: std::ops::Range) { let blank = Cell::from_char(' ', &CellAttributes::default()); let line_idx = (self.lines.len() - self.physical_rows) + y; - let line = &mut self.lines[line_idx]; + let line = self.line_mut(line_idx); let max_col = line.cells.len(); for x in cols { if x >= max_col { @@ -306,14 +342,20 @@ impl Screen { } } + /// TODO: properly implement scroll regions fn scroll_up(&mut self, scroll_top: usize, scroll_bottom: usize, num_rows: usize) { let max_allowed = self.physical_rows + self.scrollback_size; if self.lines.len() + num_rows >= max_allowed { + // Any rows that get pushed out of scrollback get removed let lines_to_pop = (self.lines.len() + num_rows) - max_allowed; for _ in 0..lines_to_pop { self.lines.remove(0); } } + let first_idx = (self.lines.len() - self.physical_rows) + scroll_top - num_rows; + for idx in first_idx..first_idx + (scroll_bottom - scroll_top) { + self.line_mut(idx); // has the side effect + } for _ in 0..num_rows { self.lines.push(Line::new(self.physical_cols)); } @@ -338,9 +380,6 @@ pub struct TerminalState { /// printed character wrap_next: bool, - /// If true then the terminal state has changed - state_changed: bool, - /// Some parsing operations may yield responses that need /// to be returned to the client. They are collected here /// and this is used as the result of the advance_bytes() @@ -368,7 +407,6 @@ impl TerminalState { pen: CellAttributes::default(), cursor_x: 0, cursor_y: 0, - state_changed: true, answerback: None, scroll_top: 0, scroll_bottom: physical_rows - 1, @@ -434,32 +472,51 @@ impl TerminalState { Ok(()) } - /// Return true if the state has changed; the implication is that the terminal - /// needs to be redrawn in some fashion. - /// TODO: should probably build up a damage list instead - pub fn get_state_changed(&self) -> bool { - self.state_changed - } - - /// Clear the state changed flag; the intent is that the consumer of this - /// class will clear the state after each paint. - pub fn clear_state_changed(&mut self) { - self.state_changed = false; - } - pub fn resize(&mut self, physical_rows: usize, physical_cols: usize) { self.screen.resize(physical_rows, physical_cols); self.alt_screen.resize(physical_rows, physical_cols); } - /// Returns the width of the screen and a slice over the visible rows - /// TODO: should allow an arbitrary view for scrollback - pub fn visible_cells(&self) -> (usize, &[Line]) { + /// Returns true if any of the visible lines are marked dirty + pub fn has_dirty_lines(&self) -> bool { let screen = self.screen(); - let width = screen.physical_cols; let height = screen.physical_rows; let len = screen.lines.len(); - (width, &screen.lines[len - height..len]) + + for line in screen.lines.iter().skip(len - height) { + if line.dirty { + return true; + } + } + + false + } + + /// Returns the set of visible lines that are dirty. + /// The return value is a Vec<(line_idx, line)>, where + /// line_idx is relative to the top of the viewport + pub fn get_dirty_lines(&self) -> Vec<(usize, &Line)> { + let mut res = Vec::new(); + + let screen = self.screen(); + let height = screen.physical_rows; + let len = screen.lines.len(); + + for (i, mut line) in screen.lines.iter().skip(len - height).enumerate() { + if line.dirty { + res.push((i, &*line)); + } + } + + res + } + + /// Clear the dirty flag for all dirty lines + pub fn clean_dirty_lines(&mut self) { + let screen = self.screen_mut(); + for line in screen.lines.iter_mut() { + line.set_clean(); + } } /// Returns the 0-based cursor position relative to the top left of @@ -473,10 +530,16 @@ impl TerminalState { /// TODO: DEC origin mode impacts the interpreation of these fn set_cursor_pos(&mut self, x: usize, y: usize) { let rows = self.screen().physical_rows; + let old_y = self.cursor_y; + let new_y = y.min(rows - 1); + self.cursor_x = x; - self.cursor_y = y.min(rows - 1); - self.state_changed = true; + self.cursor_y = new_y; self.wrap_next = false; + + let screen = self.screen_mut(); + screen.dirty_line(old_y); + screen.dirty_line(new_y); } fn delta_cursor_pos(&mut self, x: i64, y: i64) { @@ -581,16 +644,18 @@ impl vte::Perform for TerminalState { fn execute(&mut self, byte: u8) { match byte { - b'\n' | 0x0b /* VT */ | 0x0c /* FF */=> { + b'\n' | 0x0b /* VT */ | 0x0c /* FF */ => { self.new_line(true /* TODO: depend on terminal mode */) } b'\r' => { + let row = self.cursor_y; + self.screen_mut().dirty_line(row); self.cursor_x = 0; - self.state_changed = true; } 0x08 /* BS */ => { + let row = self.cursor_y; + self.screen_mut().dirty_line(row); self.cursor_x -= 1; - self.state_changed = true; } _ => println!("unhandled vte execute {}", byte), } diff --git a/src/xwin.rs b/src/xwin.rs index ba6332d54..7c44c9cfb 100644 --- a/src/xwin.rs +++ b/src/xwin.rs @@ -70,7 +70,6 @@ pub struct TerminalWindow<'a> { descender: isize, window_context: xgfx::Context<'a>, buffer_image: BufferImage<'a>, - need_paint: bool, terminal: term::Terminal, pty: MasterPty, process: Child, @@ -133,7 +132,6 @@ impl<'a> TerminalWindow<'a> { cell_height, cell_width, descender, - need_paint: true, terminal, pty, process, @@ -166,7 +164,6 @@ impl<'a> TerminalWindow<'a> { self.pty.resize(rows, cols, width, height)?; self.terminal.resize(rows as usize, cols as usize); - self.need_paint = true; Ok(true) } else { debug!("ignoring extra resize"); @@ -353,114 +350,112 @@ impl<'a> TerminalWindow<'a> { } pub fn paint(&mut self) -> Result<(), Error> { - self.need_paint = false; - let palette = term::color::ColorPalette::default(); - self.buffer_image.clear( - palette - .resolve(&term::color::ColorAttribute::Background) - .into(), - ); + let background_color = palette.resolve(&term::color::ColorAttribute::Background); let cell_height = self.cell_height.ceil() as usize; let cell_width = self.cell_width.ceil() as usize; - let mut y = 0 as isize; - - let (_, lines) = self.terminal.visible_cells(); let (cursor_x, cursor_y) = self.terminal.cursor_pos(); + { + let dirty_lines = self.terminal.get_dirty_lines(); - for (line_idx, line) in lines.iter().enumerate() { - let mut x = 0 as isize; - y += cell_height as isize; + for (line_idx, line) in dirty_lines { - let glyph_info = self.shape_text(&line.as_str())?; - for info in glyph_info.iter() { - // Figure out which column we should be looking at. - // We infer this from the X position rather than enumerate the - // glyph_info iterator because glyphs may advance by multiple cells. - let cell_idx = x as usize / cell_width; - if cell_idx >= line.cells.len() { - // Don't bother rendering outside the viewable area - break; - } + let mut x = 0 as isize; + let y = (line_idx * cell_height) as isize; - let is_cursor_cell = if cell_idx == cursor_x && line_idx == cursor_y { - true - } else { - false - }; - - let attrs = &line.cells[cell_idx].attrs; - - let (fg_color, bg_color) = if attrs.reverse() { - ( - palette.resolve(&attrs.background), - palette.resolve(&attrs.foreground), - ) - } else { - ( - palette.resolve(&attrs.foreground), - palette.resolve(&attrs.background), - ) - }; - - // Render the cell background color self.buffer_image.clear_rect( - x, - y - cell_height as isize, - info.num_cells as usize * self.cell_width as usize, + 0, + y, + self.width as usize, cell_height, - if is_cursor_cell { - palette.cursor() - } else { - bg_color - }.into(), + background_color.into(), ); - let glyph = self.cached_glyph(info)?; - // glyph.image.is_none() for whitespace glyphs - if let &Some(ref image) = &glyph.image { - debug!( - "x,y: {},{} desc={} bearing:{},{} off={},{} adv={},{} scale={}", - x, - y, - self.descender, - glyph.bearing_x, - glyph.bearing_y, - glyph.x_offset, - glyph.y_offset, - glyph.x_advance, - glyph.y_advance, - glyph.scale - ); + let glyph_info = self.shape_text(&line.as_str())?; + for info in glyph_info.iter() { + // Figure out which column we should be looking at. + // We infer this from the X position rather than enumerate the + // glyph_info iterator because glyphs may advance by multiple cells. + let cell_idx = x as usize / cell_width; + if cell_idx >= line.cells.len() { + // Don't bother rendering outside the viewable area + break; + } - let operator = if glyph.has_color { - xgfx::Operator::Over + let is_cursor_cell = if cell_idx == cursor_x && line_idx == cursor_y { + true } else { - xgfx::Operator::MultiplyThenOver(fg_color.into()) + false }; - self.buffer_image.draw_image( - x + glyph.x_offset as isize + glyph.bearing_x, - y + self.descender - - (glyph.y_offset as isize + glyph.bearing_y), - image, - operator, - ); - } - x += glyph.x_advance; - y += glyph.y_advance; + let attrs = &line.cells[cell_idx].attrs; + + let (fg_color, bg_color) = if attrs.reverse() { + ( + palette.resolve(&attrs.background), + palette.resolve(&attrs.foreground), + ) + } else { + ( + palette.resolve(&attrs.foreground), + palette.resolve(&attrs.background), + ) + }; + + // Render the cell background color + self.buffer_image.clear_rect( + x, + y - cell_height as isize, + info.num_cells as usize * self.cell_width as usize, + cell_height, + if is_cursor_cell { + palette.cursor() + } else { + bg_color + }.into(), + ); + + let glyph = self.cached_glyph(info)?; + // glyph.image.is_none() for whitespace glyphs + if let &Some(ref image) = &glyph.image { + debug!( + "x,y: {},{} desc={} bearing:{},{} off={},{} adv={},{} scale={}", + x, + y, + self.descender, + glyph.bearing_x, + glyph.bearing_y, + glyph.x_offset, + glyph.y_offset, + glyph.x_advance, + glyph.y_advance, + glyph.scale + ); + + let operator = if glyph.has_color { + xgfx::Operator::Over + } else { + xgfx::Operator::MultiplyThenOver(fg_color.into()) + }; + self.buffer_image.draw_image( + x + glyph.x_offset as isize + glyph.bearing_x, + y + self.descender - + (glyph.y_offset as isize + glyph.bearing_y), + image, + operator, + ); + } + + x += glyph.x_advance; + } } } - // FIXME: we have to push the render to the server in case it - // was the result of output from the process on the pty. It would - // be nice to make this paint function only re-render the changed - // portions and send only those to the X server here. This isn't - // so terrible when we have SHM available. match &self.buffer_image { &BufferImage::Shared(ref shm) => { + // We handled this above self.window_context.copy_area( shm, 0, @@ -477,6 +472,8 @@ impl<'a> TerminalWindow<'a> { } } + self.terminal.clean_dirty_lines(); + Ok(()) } @@ -505,7 +502,6 @@ impl<'a> TerminalWindow<'a> { if let Some(answer) = self.terminal.advance_bytes(&buf[0..size]) { self.pty.write(&answer).ok(); // discard error } - self.need_paint = true; if size < BUFSIZE { // If we had a short read then there is no more // data to read right now; we'll get called again @@ -522,7 +518,7 @@ impl<'a> TerminalWindow<'a> { } pub fn need_paint(&self) -> bool { - self.need_paint + self.terminal.has_dirty_lines() } fn decode_key(&self, event: &xcb::KeyPressEvent) -> (KeyCode, KeyModifiers) {