improve clustering and cursor rendering

We weren't quite right with handling the cursor around double-width
characters.  We're now a bit more robust at this because we're
clustering and taking pains to consider the printable width of the
cell as well as the width of the shaped (eg: with contextual ligatures)
glyph.

There may still be issues with contextual ligatures of length 3,
but I haven't managed to nail down exactly the issue yet.
This commit is contained in:
Wez Furlong committed 2018-02-04 08:28:32 -08:00
1 parent 78c2df34fc
commit 4c8e3ffd75
5 files changed
+339 -99

No files matched your search

+12 -3
View File
@@ -15,7 +15,6 @@ pub struct GlyphInfo {
#[cfg(debug_assertions)]
pub text: String,
/// Offset within text
#[cfg(debug_assertions)]
pub cluster: u32,
/// How many cells/columns this glyph occupies horizontally
pub num_cells: u8,
@@ -47,7 +46,6 @@ impl GlyphInfo {
num_cells,
font_idx,
glyph_pos: info.codepoint,
#[cfg(debug_assertions)]
cluster: info.cluster,
x_advance: pos.x_advance as f64 / 64.0,
y_advance: pos.y_advance as f64 / 64.0,
@@ -195,12 +193,14 @@ impl Font {
}
pub fn shape(&mut self, font_idx: usize, s: &str) -> Result<Vec<GlyphInfo>, Error> {
/*
debug!(
"shape text for font_idx {} with len {} {}",
font_idx,
s.len(),
s
);
*/
let features = vec![
// kerning
hbwrap::feature_from_string("kern")?,
@@ -259,7 +259,7 @@ impl Font {
sizes[last] = diff;
}
}
debug!("sizes: {:?}", sizes);
//debug!("sizes: {:?}", sizes);
// Now make a second pass to determine if we need
// to perform fallback to a later font.
@@ -277,6 +277,11 @@ impl Font {
let substr = &s[start..pos];
let mut shape = self.shape(font_idx + 1, substr)?;
// Fixup the cluster member to match our current offset
for info in shape.iter_mut() {
info.cluster += start as u32;
}
cluster.append(&mut shape);
first_fallback_pos = None;
@@ -299,6 +304,10 @@ impl Font {
substr,
);
let mut shape = self.shape(font_idx + 1, substr)?;
// Fixup the cluster member to match our current offset
for info in shape.iter_mut() {
info.cluster += start as u32;
}
cluster.append(&mut shape);
}
+2 -1
View File
@@ -131,8 +131,9 @@ fn run() -> Result<(), Error> {
)?;
let terminal = term::Terminal::new(initial_rows as usize, initial_cols as usize, 3000);
// let message = "x_advance != \x1b[38;2;1;0;125;145;mfoo->bar(); ❤ 😍🤢\n\x1b[91;mw00t\n\x1b[37;104;m bleet\x1b[0;m.";
// let message = "; ❤ 😍🤢\n\x1b[91;mw00t\n\x1b[37;104;m bleet\x1b[0;m.";
// terminal.advance_bytes(message);
// !=
let mut window = TerminalWindow::new(
&conn,
+59 -1
View File
@@ -256,7 +256,7 @@ impl<'a> Drop for Context<'a> {
}
/// A color stored as big endian bgra32
#[derive(Copy, Clone)]
#[derive(Copy, Clone, Debug)]
pub struct Color(u32);
impl Color {
@@ -335,6 +335,7 @@ impl From<RgbColor> for Color {
/// More information on these and their temrinology can be found
/// in the Cairo documentation here:
/// https://www.cairographics.org/operators/
#[derive(Debug, Clone, Copy)]
pub enum Operator {
/// Apply the alpha channel of src and combine src with dest,
/// according to the classic OVER composite operator
@@ -431,6 +432,63 @@ pub trait BitmapImage {
}
}
/// Draw a 1-pixel wide rectangle
fn draw_rect(
&mut self,
dest_x: isize,
dest_y: isize,
width: usize,
height: usize,
color: Color,
operator: Operator,
) {
let (dim_width, dim_height) = self.image_dimensions();
// Draw the vertical lines down either side
for y in 0..height {
let dest_y = y as isize + dest_y;
if dest_y < 0 {
continue;
}
if dest_y >= dim_height as isize {
break;
}
if dest_x >= 0 && dest_x < dim_width as isize {
let left = self.pixel_mut(dest_x as usize, dest_y as usize);
*left = color.composite(Color(*left), &operator).0;
}
let right_x = dest_x + width as isize - 1;
if right_x >= 0 && right_x < dim_width as isize {
let right = self.pixel_mut(right_x as usize, dest_y as usize);
*right = color.composite(Color(*right), &operator).0;
}
}
// And the horizontals for the top and bottom
for x in 0..width {
let dest_x = x as isize + dest_x;
if dest_x < 0 {
continue;
}
if dest_x >= dim_width as isize {
break;
}
if dest_y >= 0 && dest_y < dim_height as isize {
let top = self.pixel_mut(dest_x as usize, dest_y as usize);
*top = color.composite(Color(*top), &operator).0;
}
let bot_y = dest_y + height as isize - 1;
if bot_y >= 0 && bot_y < dim_height as isize {
let bottom = self.pixel_mut(dest_x as usize, bot_y as usize);
*bottom = color.composite(Color(*bottom), &operator).0;
}
}
}
fn draw_image(&mut self, dest_x: isize, dest_y: isize, im: &BitmapImage, operator: Operator) {
let (dest_width, dest_height) = im.image_dimensions();
self.draw_image_subset(dest_x, dest_y, 0, 0, dest_width, dest_height, im, operator)
+146 -76
View File
@@ -365,6 +365,7 @@ impl<'a> TerminalWindow<'a> {
let mut x = 0 as isize;
let y = (line_idx * cell_height) as isize;
// Clear this dirty row
self.buffer_image.clear_rect(
0,
y,
@@ -373,101 +374,170 @@ impl<'a> TerminalWindow<'a> {
background_color.into(),
);
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;
}
// Break the line into clusters of cells with the same attributes
let cell_clusters = line.cluster();
for cluster in cell_clusters {
let attrs = &cluster.attrs;
let is_cursor_cell = if cell_idx == cursor.x && line_idx == cursor.y as usize {
true
} else {
false
let (fg_color, bg_color) = {
let mut fg_color = &attrs.foreground;
let mut bg_color = &attrs.background;
if attrs.reverse() {
mem::swap(&mut fg_color, &mut bg_color);
}
(fg_color, bg_color)
};
let attrs = &line.cells[cell_idx].attrs;
let bg_color = palette.resolve(bg_color);
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),
)
};
// Shape the printable text from this cluster
let glyph_info = self.shape_text(&cluster.text)?;
for info in glyph_info.iter() {
let cell_idx = cluster.byte_to_cell_idx[info.cluster as usize];
let cell = &line.cells[cell_idx];
let cell_print_width = cell.width();
// Render the cell background color
self.buffer_image.clear_rect(
x,
y,
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={}",
// Render the cell background color
self.buffer_image.clear_rect(
x,
y,
self.descender,
glyph.bearing_x,
glyph.bearing_y,
glyph.x_offset,
glyph.y_offset,
glyph.x_advance,
glyph.y_advance,
glyph.scale
cell_print_width * cell_width,
cell_height,
bg_color.into(),
);
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 + cell_height as isize + self.descender -
(glyph.y_offset as isize + glyph.bearing_y),
image,
operator,
// Render the cursor, if it overlaps with the current cluster
if line_idx as i64 == cursor.y {
for cur_x in cell_idx..cell_idx + info.num_cells as usize {
if cursor.x == cur_x {
// The cursor fits in this cell, so render the cursor bg
self.buffer_image.clear_rect(
(cur_x * cell_width) as isize,
y,
cell_width * line.cells[cur_x].width(),
cell_height,
palette.cursor().into(),
);
}
}
}
let glyph = self.cached_glyph(info)?;
// glyph.image.is_none() for whitespace glyphs
if let &Some(ref image) = &glyph.image {
if false && line_idx == cursor.y as usize {
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_width, glyph_height) = image.image_dimensions();
// This is a little bit tricky.
// We may have a double-wide glyph based on double-wide contents
// of the cell, or we may have a double-wide glyph based on
// the result of shaping a contextual ligature. The computed
// cell_print_width tells us about the former. The shaping
// data in info.num_cells includes both cases. In order not
// to skip out on rendering the cursor we need to slice the
// glyph up into cell strips and render them.
for slice_x in 0..info.num_cells as usize {
let is_cursor = cursor.x == slice_x + cell_idx &&
line_idx as i64 == cursor.y;
let glyph_color = if is_cursor {
// overlaps with cursor, so adjust colors.
// TODO: could make cursor fg color an option.
&attrs.background
} else {
fg_color
};
let glyph_color = palette.resolve(glyph_color);
let operator = if glyph.has_color {
xgfx::Operator::Over
} else {
xgfx::Operator::MultiplyThenOver(glyph_color.into())
};
let slice_offset = slice_x * cell_width;
self.buffer_image.draw_image_subset(
slice_offset as isize + x + glyph.x_offset as isize +
glyph.bearing_x,
y + cell_height as isize + self.descender -
(glyph.y_offset as isize + glyph.bearing_y),
slice_offset,
0,
(glyph_width - slice_offset).min(cell_width),
glyph_height.min(cell_height),
image,
operator,
);
if is_cursor {
// Render a block outline style of cursor.
// TODO: make this respect user configuration
self.buffer_image.draw_rect(
(slice_offset + (cell_idx * cell_width)) as
isize,
y,
// take care to use the print width here otherwise
// the rectangle will incorrectly bisect the glyph
(cell_print_width * cell_width),
cell_height,
palette.cursor().into(),
xgfx::Operator::Over,
);
}
}
}
x += glyph.x_advance;
}
}
// If we have SHM available, we can send up just this changed line
match &self.buffer_image {
&BufferImage::Shared(ref shm) => {
self.window_context.copy_area(
shm,
0,
y as i16,
&self.window,
0,
y as i16,
self.width,
cell_height as u16,
);
}
x += glyph.x_advance;
&BufferImage::Image(_) => {
// Will handle this at the end
}
}
}
}
match &self.buffer_image {
&BufferImage::Shared(ref shm) => {
&BufferImage::Shared(_) => {
// We handled this above
self.window_context.copy_area(
shm,
0,
0,
&self.window,
0,
0,
self.width,
self.height,
);
}
&BufferImage::Image(ref buffer) => {
// With no SHM available, we have to push the whole screen buffer
// here, regardless of which lines are dirty.
self.window_context.put_image(0, 0, buffer);
}
}
+120 -18
View File
@@ -216,7 +216,7 @@ impl Default for CellAttributes {
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Cell {
chars: [u8; 8],
bytes: [u8; 8],
pub attrs: CellAttributes,
}
@@ -228,22 +228,27 @@ impl Default for Cell {
impl Cell {
#[inline]
pub fn chars(&self) -> &[u8] {
if let Some(len) = self.chars.iter().position(|&c| c == 0) {
&self.chars[0..len]
pub fn bytes(&self) -> &[u8] {
if let Some(len) = self.bytes.iter().position(|&c| c == 0) {
&self.bytes[0..len]
} else {
&self.chars
&self.bytes
}
}
pub fn from_char(c: char, attr: &CellAttributes) -> Cell {
let mut chars = [0u8; 8];
c.encode_utf8(&mut chars);
let mut bytes = [0u8; 8];
c.encode_utf8(&mut bytes);
Cell {
chars,
bytes,
attrs: *attr,
}
}
pub fn width(&self) -> usize {
use unicode_width::UnicodeWidthStr;
std::str::from_utf8(self.bytes()).unwrap_or("").width()
}
}
impl From<char> for Cell {
@@ -258,6 +263,41 @@ pub struct Line {
dirty: bool,
}
/// A CellCluster is another representation of a Line.
/// A Vec<CellCluster> is produced by walking through the Cells in
/// a line and collecting succesive Cells with the same attributes
/// together into a CellCluster instance. Additional metadata to
/// aid in font rendering is also collected.
#[derive(Debug, Clone)]
pub struct CellCluster {
pub attrs: CellAttributes,
pub text: String,
pub byte_to_cell_idx: Vec<usize>,
}
impl CellCluster {
/// Start off a new cluster with some initial data
fn new(attrs: CellAttributes, text: &str, cell_idx: usize) -> CellCluster {
let mut idx = Vec::new();
for _ in 0..text.len() {
idx.push(cell_idx);
}
CellCluster {
attrs,
text: text.into(),
byte_to_cell_idx: idx,
}
}
/// Add to this cluster
fn add(&mut self, text: &str, cell_idx: usize) {
for _ in 0..text.len() {
self.byte_to_cell_idx.push(cell_idx);
}
self.text.push_str(text);
}
}
impl Line {
/// Create a new line with the specified number of columns.
/// Each cell has the default attributes.
@@ -273,22 +313,57 @@ impl Line {
pub fn as_str(&self) -> String {
let mut s = String::new();
for c in self.cells.iter() {
s.push_str(std::str::from_utf8(c.chars()).unwrap_or("?"));
s.push_str(std::str::from_utf8(c.bytes()).unwrap_or("?"));
}
s
}
/// Compute the list of CellClusters for this line
pub fn cluster(&self) -> Vec<CellCluster> {
let mut last_cluster = None;
let mut clusters = Vec::new();
for (cell_idx, c) in self.cells.iter().enumerate() {
let cell_str = std::str::from_utf8(c.bytes()).unwrap_or("?");
last_cluster = match last_cluster.take() {
None => {
// Start new cluster
Some(CellCluster::new(c.attrs, cell_str, cell_idx))
}
Some(mut last) => {
if last.attrs != c.attrs {
// Flush pending cluster and start a new one
clusters.push(last);
Some(CellCluster::new(c.attrs, cell_str, cell_idx))
} else {
// Add to current cluster
last.add(cell_str, cell_idx);
Some(last)
}
}
};
}
if let Some(cluster) = last_cluster {
// Don't forget to include any pending cluster on the final step!
clusters.push(cluster);
}
clusters
}
#[allow(dead_code)]
pub fn from_text(s: &str, attrs: &CellAttributes) -> Line {
let mut cells = Vec::new();
for (_, sub) in unicode_segmentation::UnicodeSegmentation::grapheme_indices(s, true) {
let mut chars = [0u8; 8];
let mut bytes = [0u8; 8];
let len = sub.len().min(8);
chars[0..len].copy_from_slice(sub.as_bytes());
bytes[0..len].copy_from_slice(sub.as_bytes());
cells.push(Cell {
chars,
bytes,
attrs: *attrs,
});
}
@@ -406,7 +481,13 @@ impl Screen {
/// 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: VisibleRowIndex, c: char, attr: &CellAttributes) {
pub fn set_cell(
&mut self,
x: usize,
y: VisibleRowIndex,
c: char,
attr: &CellAttributes,
) -> &Cell {
let line_idx = self.phys_row(y);
debug!(
"set_cell x,y {},{}, line_idx = {} {} {:?}",
@@ -424,6 +505,7 @@ impl Screen {
cells.resize(x + 1, Cell::default());
}
cells[x] = Cell::from_char(c, attr);
&cells[x]
}
pub fn clear_line(&mut self, y: VisibleRowIndex, cols: std::ops::Range<usize>) {
@@ -887,7 +969,6 @@ impl vte::Perform for TerminalState {
/// Draw a character to the screen
fn print(&mut self, c: char) {
if self.wrap_next {
// TODO: remember that this was a wrapped line in the attributes?
self.new_line(true);
}
@@ -896,11 +977,32 @@ impl vte::Perform for TerminalState {
let width = self.screen().physical_cols;
let pen = self.pen;
self.screen_mut().set_cell(x, y, c, &pen);
if x + 1 < width {
// TODO: the 1 here should be based on the glyph width
self.set_cursor_pos(&Position::Relative(1), &Position::Relative(0));
// Assign the cell and extract its printable width
let print_width = {
let cell = self.screen_mut().set_cell(x, y, c, &pen);
cell.width()
};
// for double- or triple-wide cells, the client of the terminal
// expects the cursor to move by the visible width, which means that
// we need to generate non-printing cells to pad out the gap. They
// need to be non-printing rather than space so that that renderer
// doesn't render an actual space between the glyphs.
for non_print_x in 1..print_width {
self.screen_mut().set_cell(
x + non_print_x,
y,
0 as char, // non-printable
&pen,
);
}
if x + print_width < width {
self.set_cursor_pos(
&Position::Relative(print_width as i64),
&Position::Relative(0),
);
} else {
self.wrap_next = true;
}