From a9bb29dde137377d7e0b47930cfaaa20d94bd8ff Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Fri, 13 Jul 2018 20:58:53 -0700 Subject: [PATCH] Initial work on the render concept --- Cargo.toml | 4 +- src/cell.rs | 48 +++-- src/color.rs | 20 ++- src/lib.rs | 3 + src/render/mod.rs | 30 ++++ src/render/terminfo.rs | 388 +++++++++++++++++++++++++++++++++++++++++ src/screen.rs | 28 ++- 7 files changed, 484 insertions(+), 37 deletions(-) create mode 100644 src/render/mod.rs create mode 100644 src/render/terminfo.rs diff --git a/Cargo.toml b/Cargo.toml index d02c9224f..95eb48999 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,9 @@ version = "0.1.0" authors = ["Wez Furlong"] [dependencies] -terminfo = "~0.5" +# SetAttributes is only in master +terminfo = { git = "https://github.com/meh/rust-terminfo" } palette = "~0.4" serde = "~1.0" serde_derive = "~1.0" +failure = "~0.1" diff --git a/src/cell.rs b/src/cell.rs index 4f0ea0ce3..7877f0a0d 100644 --- a/src/cell.rs +++ b/src/cell.rs @@ -1,4 +1,4 @@ -use color; +use color::ColorAttribute; use std::mem; use std::rc::Rc; @@ -8,11 +8,11 @@ pub struct Hyperlink { pub url: String, } -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Default, Clone, Eq, PartialEq)] pub struct CellAttributes { attributes: u16, - pub foreground: color::ColorAttribute, - pub background: color::ColorAttribute, + pub foreground: ColorAttribute, + pub background: ColorAttribute, pub hyperlink: Option>, } @@ -31,9 +31,10 @@ macro_rules! bitfield { } #[inline] - pub fn $setter(&mut self, value: bool) { + pub fn $setter(&mut self, value: bool) -> &mut Self { let attr_value = if value { 1 << $bitnum } else { 0 }; self.attributes = (self.attributes & !(1 << $bitnum)) | attr_value; + self } }; @@ -44,10 +45,11 @@ macro_rules! bitfield { } #[inline] - pub fn $setter(&mut self, value: u16) { + pub fn $setter(&mut self, value: u16) -> &mut Self { let clear = !($bitmask << $bitshift); let attr_value = (value & $bitmask) << $bitshift; self.attributes = (self.attributes & clear) | attr_value; + self } }; @@ -58,11 +60,12 @@ macro_rules! bitfield { } #[inline] - pub fn $setter(&mut self, value: $enum) { + pub fn $setter(&mut self, value: $enum) -> &mut Self { let value = value as u16; let clear = !($bitmask << $bitshift); let attr_value = (value & $bitmask) << $bitshift; self.attributes = (self.attributes & clear) | attr_value; + self } }; } @@ -83,23 +86,6 @@ pub enum Underline { Double = 2, } -impl Default for CellAttributes { - fn default() -> Self { - Self { - attributes: 0, - foreground: color::ColorAttribute { - ansi: color::ColorSpec::Foreground, - full: None, - }, - background: color::ColorAttribute { - ansi: color::ColorSpec::Background, - full: None, - }, - hyperlink: None, - } - } -} - impl CellAttributes { bitfield!(intensity, set_intensity, Intensity, 0b11, 0); bitfield!(underline, set_underline, Underline, 0b11, 2); @@ -109,6 +95,16 @@ impl CellAttributes { bitfield!(strikethrough, set_strikethrough, 7); bitfield!(invisible, set_invisible, 8); + pub fn set_foreground>(&mut self, foreground: C) -> &mut Self { + self.foreground = foreground.into(); + self + } + + pub fn set_background>(&mut self, background: C) -> &mut Self { + self.background = background.into(); + self + } + /// Clone the attributes, but exclude fancy extras such /// as hyperlinks or future sprite things pub fn clone_sgr_only(&self) -> Self { @@ -172,7 +168,7 @@ pub enum AttributeChange { Reverse(bool), StrikeThrough(bool), Invisible(bool), - Foreground(color::ColorAttribute), - Background(color::ColorAttribute), + Foreground(ColorAttribute), + Background(ColorAttribute), Hyperlink(Option>), } diff --git a/src/color.rs b/src/color.rs index 30648981c..cfc2831fd 100644 --- a/src/color.rs +++ b/src/color.rs @@ -94,13 +94,18 @@ impl<'de> Deserialize<'de> for RgbColor { #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum ColorSpec { - Foreground, - Background, + Default, /// Use either a raw number, or use values from the `AnsiColor` enum PaletteIndex(u8), } -#[derive(Debug, Clone, Copy, Eq, PartialEq)] +impl Default for ColorSpec { + fn default() -> Self { + ColorSpec::Default + } +} + +#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)] pub struct ColorAttribute { /// Used if the terminal supports full color pub full: Option, @@ -109,6 +114,15 @@ pub struct ColorAttribute { pub ansi: ColorSpec, } +impl From for ColorAttribute { + fn from(col: AnsiColor) -> Self { + Self { + full: None, + ansi: ColorSpec::PaletteIndex(col as u8), + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/lib.rs b/src/lib.rs index 7527cf37d..155f9923f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +#[macro_use] +extern crate failure; extern crate palette; extern crate serde; extern crate terminfo; @@ -6,4 +8,5 @@ extern crate serde_derive; pub mod cell; pub mod color; +pub mod render; pub mod screen; diff --git a/src/render/mod.rs b/src/render/mod.rs new file mode 100644 index 000000000..0117bcc16 --- /dev/null +++ b/src/render/mod.rs @@ -0,0 +1,30 @@ +use cell::CellAttributes; +use failure; +use screen::Change; +use std; + +/// The `Renderer` trait defines a way to translate a sequence +/// of `Change`s into an output stream. This is typically a +/// sequence of ANSI or other escape sequences suitable for the +/// active terminal. +/// This interface is suitable for the unix pty interface but is +/// likely to fall short for the classic windows console API. +pub trait Renderer { + /// Given a starting set of attributes, successively consider each + /// of the entries in `changes` and emit the appropriate sequence + /// of data to `out` such that an associated pty would render the + /// information described by `changes`. Returns the attribute + /// value of the terminal at the end of the stream of changes. + /// + /// The intent is that you'd set `starting_attr` to `CellAttributes::default()` + /// on the first call, then feed the return value in on subsequent calls + /// to maintain the running view of the attributes. + fn render_to( + &self, + starting_attr: &CellAttributes, + changes: &[Change], + out: &mut std::io::Write, + ) -> Result; +} + +pub mod terminfo; diff --git a/src/render/terminfo.rs b/src/render/terminfo.rs new file mode 100644 index 000000000..1b5069849 --- /dev/null +++ b/src/render/terminfo.rs @@ -0,0 +1,388 @@ +//! Rendering of Changes using terminfo +use cell::{AttributeChange, CellAttributes, Intensity, Underline}; +use color::ColorSpec; +use failure; +use render::Renderer; +use screen::{Change, Position}; +use std::io::{Error as IoError, Write}; +use terminfo::{capability as cap, Database}; + +pub struct TerminfoRenderer { + db: Database, +} + +impl TerminfoRenderer { + pub fn new(db: Database) -> Self { + Self { db } + } +} + +// The terminfo crate wants us to move the Write instance in on +// each call. This is a little struct that allows us to do that +// without moving out the actual Write ref. +struct WriteWrapper<'a> { + out: &'a mut Write, +} + +impl<'a> WriteWrapper<'a> { + fn new(out: &'a mut Write) -> Self { + Self { out } + } +} + +impl<'a> Write for WriteWrapper<'a> { + fn write(&mut self, buf: &[u8]) -> Result { + self.out.write(buf) + } + + fn flush(&mut self) -> Result<(), IoError> { + self.out.flush() + } +} + +impl Renderer for TerminfoRenderer { + fn render_to( + &self, + start_attr: &CellAttributes, + changes: &[Change], + out: &mut Write, + ) -> Result { + let mut current_attr = start_attr.clone(); + let mut pending_attr: Option = None; + + macro_rules! attr_apply { + ($apply:expr) => { + pending_attr = Some(match pending_attr { + Some(mut attr) => { + $apply(&mut attr); + attr + } + None => { + let mut attr = current_attr.clone(); + $apply(&mut attr); + attr + } + }); + }; + } + macro_rules! record { + ($accesor:ident, $value:expr) => { + attr_apply!(|attr: &mut CellAttributes| { + attr.$accesor(*$value); + }); + }; + } + + macro_rules! attr_on_off { + ($cap_on:ident, $cap_off:ident, $value:expr) => { + if $value { + if let Some(attr) = self.db.get::() { + attr.expand().to(WriteWrapper::new(out))?; + } + } else { + if let Some(attr) = self.db.get::() { + attr.expand().to(WriteWrapper::new(out))?; + } + } + }; + } + + macro_rules! flush_pending_attr { + () => { + if let Some(attr) = pending_attr.take() { + if let Some(sgr) = self.db.get::() { + sgr.expand() + .bold(attr.intensity() == Intensity::Bold) + .dim(attr.intensity() == Intensity::Half) + .underline(attr.underline() != Underline::None) + .blink(attr.blink()) + .reverse(attr.reverse()) + .invisible(attr.invisible()) + .to(WriteWrapper::new(out))?; + } + + if attr.italic() != current_attr.italic() { + attr_on_off!(EnterItalicsMode, ExitItalicsMode, attr.italic()); + } + + // Note: strikethrough is not exposed in terminfo + + let has_true_color = self.db + .get::() + .unwrap_or(cap::TrueColor(false)) + .0; + + if attr.foreground != current_attr.foreground { + match (has_true_color, attr.foreground.full, attr.foreground.ansi) { + (true, Some(tc), _) => { + write!( + WriteWrapper::new(out), + "\x1b[38;2;{};{};{}m", + tc.red, + tc.green, + tc.blue + )?; + } + (_, _, ColorSpec::Default) => { + // Terminfo doesn't define a reset color to default, so + // we use the ANSI code. + write!(WriteWrapper::new(out), "\x1b[39m")?; + } + (_, _, ColorSpec::PaletteIndex(idx)) => { + if let Some(set) = self.db.get::() { + set.expand().color(idx).to(WriteWrapper::new(out))?; + } + } + } + } + + if attr.background != current_attr.background { + match (has_true_color, attr.background.full, attr.background.ansi) { + (true, Some(tc), _) => { + write!( + WriteWrapper::new(out), + "\x1b[48;2;{};{};{}m", + tc.red, + tc.green, + tc.blue + )?; + } + (_, _, ColorSpec::Default) => { + // Terminfo doesn't define a reset color to default, so + // we use the ANSI code. + write!(WriteWrapper::new(out), "\x1b[49m")?; + } + (_, _, ColorSpec::PaletteIndex(idx)) => { + if let Some(set) = self.db.get::() { + set.expand().color(idx).to(WriteWrapper::new(out))?; + } + } + } + } + + // See https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda + if let Some(link) = attr.hyperlink.as_ref() { + write!(WriteWrapper::new(out), "\x1b]8;")?; + if !link.id.is_empty() { + write!(WriteWrapper::new(out), "id={}", link.id)?; + } + write!(WriteWrapper::new(out), ";{}\x1b\\", link.url)?; + } else if current_attr.hyperlink.is_some() { + // Close out the old hyperlink + write!(WriteWrapper::new(out), "\x1b]8;;\x1b\\")?; + } + + current_attr = attr; + } + }; + } + + for change in changes { + match change { + Change::Attribute(AttributeChange::Intensity(value)) => { + record!(set_intensity, value); + } + Change::Attribute(AttributeChange::Italic(value)) => { + record!(set_italic, value); + } + Change::Attribute(AttributeChange::Reverse(value)) => { + record!(set_reverse, value); + } + Change::Attribute(AttributeChange::StrikeThrough(_)) => { + // Not possible via terminfo + } + Change::Attribute(AttributeChange::Blink(value)) => { + record!(set_blink, value); + } + Change::Attribute(AttributeChange::Invisible(value)) => { + record!(set_invisible, value); + } + Change::Attribute(AttributeChange::Underline(value)) => { + record!(set_underline, value); + } + Change::Attribute(AttributeChange::Foreground(col)) => { + attr_apply!(|attr: &mut CellAttributes| attr.foreground = *col); + } + Change::Attribute(AttributeChange::Background(col)) => { + attr_apply!(|attr: &mut CellAttributes| attr.background = *col); + } + Change::Attribute(AttributeChange::Hyperlink(link)) => { + attr_apply!(|attr: &mut CellAttributes| attr.hyperlink = link.clone()); + } + Change::AllAttributes(all) => { + pending_attr = Some(all.clone()); + } + Change::Text(text) => { + flush_pending_attr!(); + WriteWrapper::new(out).write_all(text.as_bytes())?; + } + Change::CursorPosition { + x: Position::Absolute(0), + y: Position::Relative(1), + } => { + WriteWrapper::new(out).write_all(b"\r\n")?; + } + Change::CursorPosition { + x: Position::Absolute(0), + y: Position::Absolute(0), + } => { + if let Some(attr) = self.db.get::() { + attr.expand().to(WriteWrapper::new(out))?; + } + } + Change::CursorPosition { + x: Position::NoChange, + y: Position::Relative(1), + } => { + if let Some(attr) = self.db.get::() { + attr.expand().to(WriteWrapper::new(out))?; + } + } + Change::CursorPosition { + x: Position::NoChange, + y: Position::Relative(-1), + } => { + if let Some(attr) = self.db.get::() { + attr.expand().to(WriteWrapper::new(out))?; + } + } + Change::CursorPosition { + x: Position::Relative(-1), + y: Position::NoChange, + } => { + if let Some(attr) = self.db.get::() { + attr.expand().to(WriteWrapper::new(out))?; + } + } + Change::CursorPosition { + x: Position::Relative(1), + y: Position::NoChange, + } => { + if let Some(attr) = self.db.get::() { + attr.expand().to(WriteWrapper::new(out))?; + } + } + Change::CursorPosition { + x: Position::Absolute(x), + y: Position::Absolute(y), + } => { + if let Some(attr) = self.db.get::() { + let x = (*x as u32) + 1; + let y = (*y as u32) + 1; + attr.expand().x(x).y(y).to(WriteWrapper::new(out))?; + } + } + Change::CursorPosition { .. } => { + eprintln!( + "unhandled CursorPosition in TerminfoRenderer::render_to: {:?}", + change + ); + } + } + } + + flush_pending_attr!(); + Ok(current_attr) + } +} + +#[cfg(test)] +mod test { + use super::*; + use color::AnsiColor; + + fn xterm() -> Database { + // Load the xterm entry from the system location. + // Depending on how things go, we may want to include + // our own definition in the repo and load from that path + // instead. + Database::from_name("xterm").unwrap() + } + + #[test] + fn test_empty_render() { + let mut out = Vec::::new(); + let renderer = TerminfoRenderer::new(xterm()); + let end_attr = renderer + .render_to(&CellAttributes::default(), &[], &mut out) + .unwrap(); + assert_eq!("", String::from_utf8(out).unwrap()); + assert_eq!(end_attr, CellAttributes::default()); + } + + #[test] + fn test_basic_text() { + let mut out = Vec::::new(); + let renderer = TerminfoRenderer::new(xterm()); + let end_attr = renderer + .render_to( + &CellAttributes::default(), + &[Change::Text("foo".into())], + &mut out, + ) + .unwrap(); + assert_eq!("foo", String::from_utf8(out).unwrap()); + assert_eq!(end_attr, CellAttributes::default()); + } + + #[test] + fn test_bold_text() { + let mut out = Vec::::new(); + let renderer = TerminfoRenderer::new(xterm()); + let end_attr = renderer + .render_to( + &CellAttributes::default(), + &[ + Change::Text("not ".into()), + Change::Attribute(AttributeChange::Intensity(Intensity::Bold)), + Change::Text("foo".into()), + ], + &mut out, + ) + .unwrap(); + + assert_eq!( + // The `CSI (B` sequence is rmacs + "not \x1b(B\x1b[0;1mfoo", + String::from_utf8(out).unwrap() + ); + + assert_eq!( + end_attr, + CellAttributes::default() + .set_intensity(Intensity::Bold) + .clone() + ); + } + + #[test] + fn test_red_bold_text() { + let mut out = Vec::::new(); + let renderer = TerminfoRenderer::new(xterm()); + let end_attr = renderer + .render_to( + &CellAttributes::default(), + &[ + Change::Attribute(AttributeChange::Foreground(AnsiColor::Red.into())), + Change::Attribute(AttributeChange::Intensity(Intensity::Bold)), + Change::Text("red".into()), + ], + &mut out, + ) + .unwrap(); + + // Note that the render code rearranges (red,bold) to (bold,red) + assert_eq!( + "\x1b(B\x1b[0;1m\x1b[39mred", + String::from_utf8(out).unwrap() + ); + + assert_eq!( + end_attr, + CellAttributes::default() + .set_intensity(Intensity::Bold) + .set_foreground(AnsiColor::Red) + .clone() + ); + } +} diff --git a/src/screen.rs b/src/screen.rs index f74d6596f..cf92c46e3 100644 --- a/src/screen.rs +++ b/src/screen.rs @@ -200,13 +200,27 @@ impl Screen { fn change_attribute(&mut self, change: &AttributeChange) { use cell::AttributeChange::*; match change { - Intensity(value) => self.attributes.set_intensity(*value), - Underline(value) => self.attributes.set_underline(*value), - Italic(value) => self.attributes.set_italic(*value), - Blink(value) => self.attributes.set_blink(*value), - Reverse(value) => self.attributes.set_reverse(*value), - StrikeThrough(value) => self.attributes.set_strikethrough(*value), - Invisible(value) => self.attributes.set_invisible(*value), + Intensity(value) => { + self.attributes.set_intensity(*value); + } + Underline(value) => { + self.attributes.set_underline(*value); + } + Italic(value) => { + self.attributes.set_italic(*value); + } + Blink(value) => { + self.attributes.set_blink(*value); + } + Reverse(value) => { + self.attributes.set_reverse(*value); + } + StrikeThrough(value) => { + self.attributes.set_strikethrough(*value); + } + Invisible(value) => { + self.attributes.set_invisible(*value); + } Foreground(value) => self.attributes.foreground = *value, Background(value) => self.attributes.background = *value, Hyperlink(value) => self.attributes.hyperlink = value.clone(),