cut over to termwiz Cell

This commit is contained in:
Wez Furlong committed 2018-08-04 09:35:39 -07:00
1 parent 1ec83706e7
commit 472d243a33
12 files changed
+132 -371

No files matched your search

+1 -1
View File
@@ -159,7 +159,7 @@ pub struct StyleRule {
pub italic: Option<bool>,
/// If present, this rule matches when CellAttributes::blink holds
/// a value that matches this rule.
pub blink: Option<bool>,
pub blink: Option<term::Blink>,
/// If present, this rule matches when CellAttributes::reverse holds
/// a value that matches this rule.
pub reverse: Option<bool>,
+6 -6
View File
@@ -630,7 +630,7 @@ impl Renderer {
(fg_color, bg_color)
};
let bg_color = self.palette.resolve(bg_color).to_linear_tuple_rgba();
let bg_color = self.palette.resolve_bg(bg_color).to_linear_tuple_rgba();
// Shape the printable text from this cluster
let glyph_info = {
@@ -644,11 +644,11 @@ impl Renderer {
let glyph = self.cached_glyph(info, style)?;
let glyph_color = match *fg_color {
term::color::ColorAttribute::Foreground => {
term::color::ColorAttribute::Default => {
if let Some(fg) = style.foreground {
fg
} else {
self.palette.resolve(fg_color)
self.palette.resolve_fg(fg_color)
}
}
term::color::ColorAttribute::PaletteIndex(idx) if idx < 8 => {
@@ -661,9 +661,9 @@ impl Renderer {
idx
};
self.palette
.resolve(&term::color::ColorAttribute::PaletteIndex(idx))
.resolve_fg(&term::color::ColorAttribute::PaletteIndex(idx))
}
_ => self.palette.resolve(fg_color),
_ => self.palette.resolve_fg(fg_color),
}.to_linear_tuple_rgba();
let left: f32 = glyph.x_offset as f32 + glyph.bearing_x as f32;
@@ -873,7 +873,7 @@ impl Renderer {
) -> Result<(), Error> {
let background_color = self
.palette
.resolve(&term::color::ColorAttribute::Background);
.resolve_bg(&term::color::ColorAttribute::Default);
let (r, g, b, a) = background_color.to_linear_tuple_rgba();
target.clear_color(r, g, b, a);
+2 -3
View File
@@ -7,12 +7,11 @@ version = "0.1.0"
bitflags = "1.0.1"
failure = "0.1.1"
maplit = "1.0.1"
palette = "0.2.1"
regex = "0.2.6"
serde = "1.0.27"
serde_derive = "1.0.27"
unicode-segmentation = "1.2.0"
unicode-width = "0.1.4"
unicode-segmentation = "~1.2"
unicode-width = "~0.1"
[dependencies.termwiz]
path = "../../termwiz"
-210
View File
@@ -1,210 +0,0 @@
use std::mem;
use std::rc::Rc;
use std::str;
use super::color;
use super::hyperlink::Hyperlink;
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct CellAttributes {
attributes: u16,
pub foreground: color::ColorAttribute,
pub background: color::ColorAttribute,
pub hyperlink: Option<Rc<Hyperlink>>,
}
/// Define getter and setter for the attributes bitfield.
/// The first form is for a simple boolean value stored in
/// a single bit. The $bitnum parameter specifies which bit.
/// The second form is for an integer value that occupies a range
/// of bits. The $bitmask and $bitshift parameters define how
/// to transform from the stored bit value to the consumable
/// value.
macro_rules! bitfield {
($getter:ident, $setter:ident, $bitnum:expr) => {
#[inline]
#[allow(dead_code)]
pub fn $getter(&self) -> bool {
(self.attributes & (1 << $bitnum)) == (1 << $bitnum)
}
#[inline]
#[allow(dead_code)]
pub fn $setter(&mut self, value: bool) {
let attr_value = if value { 1 << $bitnum } else { 0 };
self.attributes = (self.attributes & !(1 << $bitnum)) | attr_value;
}
};
($getter:ident, $setter:ident, $bitmask:expr, $bitshift:expr) => {
#[inline]
#[allow(dead_code)]
pub fn $getter(&self) -> u16 {
(self.attributes >> $bitshift) & $bitmask
}
#[inline]
#[allow(dead_code)]
pub fn $setter(&mut self, value: u16) {
let clear = !($bitmask << $bitshift);
let attr_value = (value & $bitmask) << $bitshift;
self.attributes = (self.attributes & clear) | attr_value;
}
};
($getter:ident, $setter:ident, $enum:ident, $bitmask:expr, $bitshift:expr) => {
#[inline]
#[allow(dead_code)]
pub fn $getter(&self) -> $enum {
unsafe { mem::transmute(((self.attributes >> $bitshift) & $bitmask) as u16)}
}
#[inline]
#[allow(dead_code)]
pub fn $setter(&mut self, value: $enum) {
let value = value as u16;
let clear = !($bitmask << $bitshift);
let attr_value = (value & $bitmask) << $bitshift;
self.attributes = (self.attributes & clear) | attr_value;
}
};
}
pub use termwiz::cell::Intensity;
pub use termwiz::cell::Underline;
impl CellAttributes {
bitfield!(intensity, set_intensity, Intensity, 0b11, 0);
bitfield!(underline, set_underline, Underline, 0b11, 2);
bitfield!(italic, set_italic, 4);
bitfield!(blink, set_blink, 5);
bitfield!(reverse, set_reverse, 6);
bitfield!(strikethrough, set_strikethrough, 7);
bitfield!(invisible, set_invisible, 8);
// Allow up to 8 different font values
//bitfield!(font, set_font, 0b111000000, 6);
/// Clone the attributes, but exclude fancy extras such
/// as hyperlinks or future sprite things
pub fn clone_sgr_only(&self) -> Self {
Self {
attributes: self.attributes,
foreground: self.foreground,
background: self.background,
hyperlink: None,
}
}
}
impl Default for CellAttributes {
fn default() -> CellAttributes {
CellAttributes {
attributes: 0,
foreground: color::ColorAttribute::Foreground,
background: color::ColorAttribute::Background,
hyperlink: None,
}
}
}
#[cfg(test)]
mod test {
use super::*;
/// Make sure that the bit shifting stuff works correctly
#[test]
fn cell_attributes() {
let mut attrs = CellAttributes::default();
attrs.set_underline(Underline::None);
assert_eq!(Underline::None, attrs.underline());
attrs.set_underline(Underline::Single);
assert_eq!(Underline::Single, attrs.underline());
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Cell {
len: u8,
bytes: [u8; 7],
pub attrs: CellAttributes,
}
impl Default for Cell {
fn default() -> Cell {
let bytes = [b' ', 0, 0, 0, 0, 0, 0];
Cell {
len: 1,
bytes,
attrs: CellAttributes::default(),
}
}
}
impl Cell {
pub fn new(s: &str, attrs: &CellAttributes) -> Cell {
let mut bytes = [0u8; 7];
let len = s.len().min(7);
bytes[0..len].copy_from_slice(s.as_bytes());
Cell {
len: len as u8,
bytes,
attrs: attrs.clone(),
}
}
#[inline]
pub fn bytes(&self) -> &[u8] {
&self.bytes[0..self.len as usize]
}
pub fn from_char(c: char, attr: &CellAttributes) -> Cell {
let mut bytes = [0u8; 7];
let len = if c == 0 as char {
0u8
} else if c < 0x80 as char {
bytes[0] = c as u8;
1u8
} else {
c.encode_utf8(&mut bytes).len() as u8
};
Cell {
len,
bytes,
attrs: attr.clone(),
}
}
#[inline]
pub fn str(&self) -> &str {
str::from_utf8(self.bytes()).unwrap_or("?")
}
pub fn width(&self) -> usize {
if self.len <= 1 {
self.len as usize
} else {
use unicode_width::UnicodeWidthStr;
self.str().width()
}
}
#[inline]
pub fn reset(&mut self) {
self.len = 1;
self.bytes[0] = b' ';
self.attrs = CellAttributes::default();
}
#[inline]
pub fn reset_with_attributes(&mut self, attr: &CellAttributes) {
self.len = 1;
self.bytes[0] = b' ';
self.attrs = attr.clone();
}
}
impl From<char> for Cell {
fn from(c: char) -> Cell {
Cell::from_char(c, &CellAttributes::default())
}
}
+13 -103
View File
@@ -1,106 +1,8 @@
//! Colors for attributes
use palette;
use serde::{self, Deserialize, Deserializer};
use std::fmt;
use std::result::Result;
pub use termwiz::color::AnsiColor;
use termwiz::color::ColorSpec;
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash)]
pub struct RgbColor {
pub red: u8,
pub green: u8,
pub blue: u8,
}
pub type RgbTuple = (f32, f32, f32);
pub type RgbaTuple = (f32, f32, f32, f32);
impl RgbColor {
/// Construct a color from discrete red, green, blue values
/// in the range 0-255.
pub fn new(red: u8, green: u8, blue: u8) -> Self {
Self { red, green, blue }
}
pub fn to_linear(&self) -> palette::Rgba {
palette::Rgba::new_u8(self.red, self.green, self.blue, 0xff)
}
pub fn to_linear_tuple_rgb(&self) -> RgbTuple {
self.to_linear().to_pixel()
}
pub fn to_linear_tuple_rgba(&self) -> RgbaTuple {
self.to_linear().to_pixel()
}
/// Construct a color from an SVG/CSS3 color name. The name
/// must be lower case. Returns None if the supplied name is
/// not recognized.
/// The list of names can be found here:
/// https://ogeon.github.io/docs/palette/master/palette/named/index.html
pub fn from_named(name: &str) -> Option<RgbColor> {
palette::named::from_str(name).map(|(r, g, b)| Self::new(r, g, b))
}
/// Construct a color from a string of the form `#RRGGBB` where
/// R, G and B are all hex digits.
pub fn from_rgb_str(s: &str) -> Option<RgbColor> {
if s.as_bytes()[0] == b'#' && s.len() == 7 {
let mut chars = s.chars().skip(1);
macro_rules! digit {
() => {{
let hi = match chars.next().unwrap().to_digit(16) {
Some(v) => (v as u8) << 4,
None => return None,
};
let lo = match chars.next().unwrap().to_digit(16) {
Some(v) => v as u8,
None => return None,
};
hi | lo
}};
}
Some(Self::new(digit!(), digit!(), digit!()))
} else {
None
}
}
}
impl<'de> Deserialize<'de> for RgbColor {
fn deserialize<D>(deserializer: D) -> Result<RgbColor, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
RgbColor::from_rgb_str(&s)
.or_else(|| RgbColor::from_named(&s))
.ok_or_else(|| format!("unknown color name: {}", s))
.map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ColorAttribute {
Foreground,
Background,
PaletteIndex(u8),
Rgb(RgbColor),
}
impl From<ColorSpec> for ColorAttribute {
fn from(spec: ColorSpec) -> Self {
match spec {
ColorSpec::Default => ColorAttribute::Foreground, // FIXME!
ColorSpec::PaletteIndex(i) => ColorAttribute::PaletteIndex(i),
ColorSpec::TrueColor(c) => ColorAttribute::Rgb(RgbColor::new(c.red, c.green, c.blue)),
}
}
}
pub use termwiz::color::{AnsiColor, ColorAttribute, RgbColor, RgbaTuple};
#[derive(Clone)]
pub struct Palette256(pub [RgbColor; 256]);
@@ -127,12 +29,20 @@ impl fmt::Debug for Palette256 {
}
impl ColorPalette {
pub fn resolve(&self, color: &ColorAttribute) -> RgbColor {
pub fn resolve_fg(&self, color: &ColorAttribute) -> RgbColor {
match *color {
ColorAttribute::Foreground => self.foreground,
ColorAttribute::Background => self.background,
ColorAttribute::Default => self.foreground,
ColorAttribute::PaletteIndex(idx) => self.colors.0[idx as usize],
ColorAttribute::Rgb(color) => color,
ColorAttribute::TrueColorWithPaletteFallback(color, _)
| ColorAttribute::TrueColorWithDefaultFallback(color) => color,
}
}
pub fn resolve_bg(&self, color: &ColorAttribute) -> RgbColor {
match *color {
ColorAttribute::Default => self.background,
ColorAttribute::PaletteIndex(idx) => self.colors.0[idx as usize],
ColorAttribute::TrueColorWithPaletteFallback(color, _)
| ColorAttribute::TrueColorWithDefaultFallback(color) => color,
}
}
}
-1
View File
@@ -8,7 +8,6 @@
use failure::Error;
use regex::{Captures, Regex};
use serde::{self, Deserialize, Deserializer};
use std::collections::HashMap;
use std::ops::Range;
use std::rc::Rc;
+1 -3
View File
@@ -5,7 +5,6 @@ extern crate bitflags;
extern crate failure;
#[macro_use]
extern crate maplit;
extern crate palette;
extern crate regex;
extern crate serde;
#[macro_use]
@@ -25,8 +24,7 @@ mod debug;
pub mod input;
pub use input::*;
pub mod cell;
pub use cell::*;
pub use termwiz::cell::{self, *};
pub mod line;
pub use line::*;
+59 -19
View File
@@ -72,17 +72,38 @@ impl Line {
let blank = Cell::default();
self.cells.resize(width, blank);
for mut cell in &mut self.cells {
cell.reset();
*cell = Cell::default();
}
}
/// Iterates the visible cells, respecting the width of the cell.
/// For instance, a double-width cell overlaps the following (blank)
/// cell, so that blank cell is omitted from the iterator results.
/// The iterator yields (column_index, Cell). Column index is the
/// index into Self::cells, and due to the possibility of skipping
/// the characters that follow wide characters, the column index may
/// skip some positions. It is returned as a convenience to the consumer
/// as using .enumerate() on this iterator wouldn't be as useful.
pub fn visible_cells(&self) -> impl Iterator<Item = (usize, &Cell)> {
let mut skip_width = 0;
self.cells.iter().enumerate().filter(move |(_idx, cell)| {
if skip_width > 0 {
skip_width -= 1;
false
} else {
skip_width = cell.width().saturating_sub(1);
true
}
})
}
/// Recompose line into the corresponding utf8 string.
/// In the future, we'll want to decompose into clusters of Cells that share
/// the same render attributes
pub fn as_str(&self) -> String {
let mut s = String::new();
for c in &self.cells {
s.push_str(c.str());
for (_, cell) in self.visible_cells() {
s.push_str(cell.str());
}
s
}
@@ -90,9 +111,11 @@ impl Line {
/// Returns a substring from the line.
pub fn columns_as_str(&self, range: Range<usize>) -> String {
let mut s = String::new();
let limit = range.end - range.start;
for (n, c) in self.cells.iter().skip(range.start).enumerate() {
if n >= limit {
for (n, c) in self.visible_cells() {
if n < range.start {
continue;
}
if n >= range.end {
break;
}
s.push_str(c.str());
@@ -105,19 +128,19 @@ impl Line {
let mut last_cluster = None;
let mut clusters = Vec::new();
for (cell_idx, c) in self.cells.iter().enumerate() {
for (cell_idx, c) in self.visible_cells() {
let cell_str = c.str();
last_cluster = match last_cluster.take() {
None => {
// Start new cluster
Some(CellCluster::new(c.attrs.clone(), cell_str, cell_idx))
Some(CellCluster::new(c.attrs().clone(), cell_str, cell_idx))
}
Some(mut last) => {
if last.attrs != c.attrs {
if last.attrs != *c.attrs() {
// Flush pending cluster and start a new one
clusters.push(last);
Some(CellCluster::new(c.attrs.clone(), cell_str, cell_idx))
Some(CellCluster::new(c.attrs().clone(), cell_str, cell_idx))
} else {
// Add to current cluster
last.add(cell_str, cell_idx);
@@ -138,8 +161,13 @@ impl Line {
pub fn from_text(s: &str, attrs: &CellAttributes) -> Line {
let mut cells = Vec::new();
for (_, sub) in unicode_segmentation::UnicodeSegmentation::grapheme_indices(s, true) {
cells.push(Cell::new(sub, attrs))
for sub in unicode_segmentation::UnicodeSegmentation::graphemes(s, true) {
let cell = Cell::new_grapheme(sub, attrs.clone());
let width = cell.width();
cells.push(cell);
for _ in 1..width {
cells.push(Cell::new(' ', attrs.clone()));
}
}
Line {
@@ -163,12 +191,18 @@ impl Line {
pub fn invalidate_implicit_links(&mut self) {
// Clear any cells that have implicit hyperlinks
for mut cell in &mut self.cells {
let link = cell.attrs.hyperlink.take();
cell.attrs.hyperlink = match link.as_ref() {
Some(link) if link.params().contains_key("implicit") => None,
Some(link) => Some(Rc::clone(link)),
None => None,
let replace = match cell.attrs().hyperlink {
Some(ref link) if link.params().contains_key("implicit") => {
Some(Cell::new_grapheme(
cell.str(),
cell.attrs().clone().set_hyperlink(None).clone(),
))
}
_ => None,
};
if let Some(replace) = replace {
*cell = replace;
}
}
// We'll need to recompute them after the line has been mutated
self.has_implicit_hyperlinks = ImplicitHyperlinks::DontKnow;
@@ -186,12 +220,18 @@ impl Line {
// The capture range is measured in bytes but we need to translate
// that to the char index of the column.
for (cell_idx, (byte_idx, _char)) in line.char_indices().enumerate() {
if self.cells[cell_idx].attrs.hyperlink.is_some() {
if self.cells[cell_idx].attrs().hyperlink.is_some() {
// Don't replace existing links
continue;
}
if in_range(byte_idx, &m.range) {
self.cells[cell_idx].attrs.hyperlink = Some(Rc::clone(&m.link));
let attrs = self.cells[cell_idx]
.attrs()
.clone()
.set_hyperlink(Some(Rc::clone(&m.link)))
.clone();
let cell = Cell::new_grapheme(self.cells[cell_idx].str(), attrs);
self.cells[cell_idx] = cell;
self.has_implicit_hyperlinks = ImplicitHyperlinks::HasSome;
self.has_hyperlink = true;
}
+2 -2
View File
@@ -138,7 +138,7 @@ impl Screen {
}
let width = line.cells.len();
let cell = Cell::from_char(c, attr);
let cell = Cell::new(c, attr.clone());
if x == width {
line.cells.push(cell);
} else if x > width {
@@ -164,7 +164,7 @@ impl Screen {
if x >= max_col {
break;
}
line.cells[x].reset_with_attributes(attr);
line.cells[x] = Cell::new(' ', attr.clone());
}
}
+28 -14
View File
@@ -306,7 +306,7 @@ impl TerminalState {
Some(ref mut line) => {
line.find_hyperlinks(rules);
match line.cells.get(x) {
Some(cell) => cell.attrs.hyperlink.as_ref().cloned(),
Some(cell) => cell.attrs().hyperlink.as_ref().cloned(),
None => None,
}
}
@@ -1376,19 +1376,33 @@ impl TerminalState {
self.pen = CellAttributes::default();
self.pen.hyperlink = link;
}
Sgr::Intensity(intensity) => self.pen.set_intensity(intensity),
Sgr::Underline(underline) => self.pen.set_underline(underline),
Sgr::Blink(blink) => self.pen.set_blink(if blink == termwiz::cell::Blink::None {
false
} else {
true
}),
Sgr::Italic(italic) => self.pen.set_italic(italic),
Sgr::Inverse(inverse) => self.pen.set_reverse(inverse),
Sgr::Invisible(invis) => self.pen.set_invisible(invis),
Sgr::StrikeThrough(strike) => self.pen.set_strikethrough(strike),
Sgr::Foreground(col) => self.pen.foreground = col.into(),
Sgr::Background(col) => self.pen.background = col.into(),
Sgr::Intensity(intensity) => {
self.pen.set_intensity(intensity);
}
Sgr::Underline(underline) => {
self.pen.set_underline(underline);
}
Sgr::Blink(blink) => {
self.pen.set_blink(blink);
}
Sgr::Italic(italic) => {
self.pen.set_italic(italic);
}
Sgr::Inverse(inverse) => {
self.pen.set_reverse(inverse);
}
Sgr::Invisible(invis) => {
self.pen.set_invisible(invis);
}
Sgr::StrikeThrough(strike) => {
self.pen.set_strikethrough(strike);
}
Sgr::Foreground(col) => {
self.pen.set_foreground(col);
}
Sgr::Background(col) => {
self.pen.set_background(col);
}
Sgr::Font(_) => {}
}
}
+6 -5
View File
@@ -147,12 +147,13 @@ fn test_ed() {
// Check that the background color paints all of the cells;
// this is also known as BCE - Background Color Erase.
let mut attr = CellAttributes::default();
attr.background = color::ColorAttribute::PaletteIndex(color::AnsiColor::Navy as u8);
let attr = CellAttributes::default()
.set_background(color::AnsiColor::Navy)
.clone();
let mut line: Line = " ".into();
line.cells[0].attrs = attr.clone();
line.cells[1].attrs = attr.clone();
line.cells[2].attrs = attr.clone();
line.cells[0] = Cell::new(' ', attr.clone());
line.cells[1] = Cell::new(' ', attr.clone());
line.cells[2] = Cell::new(' ', attr.clone());
assert_lines_equal(
&term.screen().visible_lines(),
&[line.clone(), line.clone(), line],
+14 -4
View File
@@ -256,8 +256,8 @@ fn assert_lines_equal(lines: &[Line], expect_lines: &[Line], compare: Compare) {
}
if compare.contains(Compare::ATTRS) {
let line_attrs: Vec<_> = line.cells.iter().map(|c| c.attrs.clone()).collect();
let expect_attrs: Vec<_> = expect.cells.iter().map(|c| c.attrs.clone()).collect();
let line_attrs: Vec<_> = line.cells.iter().map(|c| c.attrs().clone()).collect();
let expect_attrs: Vec<_> = expect.cells.iter().map(|c| c.attrs().clone()).collect();
assert_eq!(expect_attrs, line_attrs, "line {} attrs didn't match", idx,);
}
if compare.contains(Compare::TEXT) {
@@ -510,8 +510,18 @@ fn test_hyperlinks() {
term.print("00t");
let mut partial_line: Line = "wo00t".into();
partial_line.cells[0].attrs.hyperlink = Some(Rc::clone(&otherlink));
partial_line.cells[1].attrs.hyperlink = Some(Rc::clone(&otherlink));
partial_line.cells[0] = Cell::new(
'w',
CellAttributes::default()
.set_hyperlink(Some(Rc::clone(&otherlink)))
.clone(),
);
partial_line.cells[1] = Cell::new(
'o',
CellAttributes::default()
.set_hyperlink(Some(Rc::clone(&otherlink)))
.clone(),
);
assert_lines_equal(
&term.screen().visible_lines(),