move renderer state into the Terminal instance

This simplifies usage and the Terminal trait
This commit is contained in:
Wez Furlong committed 2018-07-21 13:19:38 -07:00
1 parent db787fdfd0
commit 86e59293d3
8 files changed
+311 -351

No files matched your search

+7 -23
View File
@@ -3,41 +3,25 @@ extern crate termwiz;
use failure::Error;
use termwiz::caps::Capabilities;
use termwiz::cell::{AttributeChange, CellAttributes};
use termwiz::cell::AttributeChange;
use termwiz::color::AnsiColor;
#[cfg(unix)]
use termwiz::render::terminfo::TerminfoRenderer;
#[cfg(windows)]
use termwiz::render::windows::WindowsConsoleRenderer;
use termwiz::render::Renderer;
use termwiz::screen::{Change, Screen};
use termwiz::terminal::{self, Terminal};
#[cfg(unix)]
fn get_terminal() -> Result<impl Terminal, failure::Error> {
terminal::UnixTerminal::new()
}
#[cfg(unix)]
fn get_renderer(caps: Capabilities) -> impl Renderer {
TerminfoRenderer::new(caps)
fn get_terminal(caps: Capabilities) -> Result<impl Terminal, failure::Error> {
terminal::UnixTerminal::new(caps)
}
#[cfg(windows)]
fn get_terminal() -> Result<impl Terminal, failure::Error> {
terminal::WindowsTerminal::new()
}
#[cfg(windows)]
fn get_renderer(_caps: Capabilities) -> impl Renderer {
WindowsConsoleRenderer::new()
fn get_terminal(caps: Capabilities) -> Result<impl Terminal, failure::Error> {
terminal::WindowsTerminal::new(caps)
}
fn main() -> Result<(), Error> {
let caps = Capabilities::new_from_env()?;
let mut renderer = get_renderer(caps);
let mut terminal = get_terminal()?;
let mut terminal = get_terminal(caps)?;
terminal.set_raw_mode()?;
let size = terminal.get_screen_size()?;
@@ -53,7 +37,7 @@ fn main() -> Result<(), Error> {
screen.add_change("and in red here\r\n");
let (_seq, changes) = screen.get_changes(0);
let _end_attr = renderer.render_to(&CellAttributes::default(), &changes, &mut terminal);
terminal.render(&changes)?;
//println!("changes: {:?}", changes);
println!("size: {:?}", size);
+1
View File
@@ -126,6 +126,7 @@ pub enum ColorLevel {
/// database, but there are some newish capabilities that are not yet
/// described by the majority of terminfo installations and thus have some
/// additional handling in this struct.
#[derive(Debug, Clone)]
pub struct Capabilities {
color_level: ColorLevel,
hyperlinks: bool,
+1 -31
View File
@@ -1,34 +1,4 @@
use cell::CellAttributes;
use failure;
use screen::Change;
use terminal::Terminal;
/// 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(
&mut self,
starting_attr: &CellAttributes,
changes: &[Change],
out: &mut Terminal,
) -> Result<CellAttributes, failure::Error>;
}
#[cfg(unix)]
pub mod terminfo;
#[cfg(windows)]
pub mod windows;
+209 -226
View File
@@ -5,10 +5,9 @@ use color::{ColorAttribute, ColorSpec};
use escape::csi::{Cursor, Edit, EraseInDisplay, Sgr, CSI};
use escape::osc::OperatingSystemCommand;
use failure;
use render::Renderer;
use screen::{Change, Position};
use std::io::{Error as IoError, Write};
use terminal::Terminal;
use std::io::{Read, Write};
use terminal::unix::UnixTty;
use terminfo::{capability as cap, Capability as TermInfoCapability};
pub struct TerminfoRenderer {
@@ -44,12 +43,15 @@ impl TerminfoRenderer {
});
}
fn flush_pending_attr(&mut self, out: &mut Terminal) -> Result<(), failure::Error> {
fn flush_pending_attr<W: UnixTty + Write>(
&mut self,
out: &mut W,
) -> Result<(), failure::Error> {
macro_rules! attr_on_off {
($cap_on:ident, $cap_off:ident, $attr:expr, $accesor:ident, $sgr:ident) => {
let value = $attr.$accesor();
if value != self.current_attr.$accesor() {
let mut out = WriteWrapper::new(out);
let mut out = out.by_ref();
let on: bool = value.into();
if on {
if let Some(attr) = self.get_capability::<cap::$cap_on>() {
@@ -78,10 +80,10 @@ impl TerminfoRenderer {
.blink(attr.blink() != Blink::None)
.reverse(attr.reverse())
.invisible(attr.invisible())
.to(WriteWrapper::new(out))?;
.to(out.by_ref())?;
} else {
if let Some(exit) = self.get_capability::<cap::ExitAttributeMode>() {
exit.expand().to(WriteWrapper::new(out))?;
exit.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Sgr(Sgr::Reset))?;
}
@@ -90,14 +92,14 @@ impl TerminfoRenderer {
match attr.intensity() {
Intensity::Bold => {
if let Some(bold) = self.get_capability::<cap::EnterBoldMode>() {
bold.expand().to(WriteWrapper::new(out))?;
bold.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Sgr(Sgr::Intensity(attr.intensity())))?;
}
}
Intensity::Half => {
if let Some(dim) = self.get_capability::<cap::EnterDimMode>() {
dim.expand().to(WriteWrapper::new(out))?;
dim.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Sgr(Sgr::Intensity(attr.intensity())))?;
}
@@ -124,7 +126,7 @@ impl TerminfoRenderer {
if attr.blink() != self.current_attr.blink() {
if let Some(attr) = self.get_capability::<cap::EnterBlinkMode>() {
attr.expand().to(WriteWrapper::new(out))?;
attr.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Sgr(Sgr::Blink(attr.blink())))?;
}
@@ -132,7 +134,7 @@ impl TerminfoRenderer {
if attr.reverse() != self.current_attr.reverse() {
if let Some(attr) = self.get_capability::<cap::EnterReverseMode>() {
attr.expand().to(WriteWrapper::new(out))?;
attr.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Sgr(Sgr::Inverse(attr.reverse())))?;
}
@@ -176,7 +178,7 @@ impl TerminfoRenderer {
(false, ColorAttribute::TrueColorWithPaletteFallback(_, idx))
| (_, ColorAttribute::PaletteIndex(idx)) => {
if let Some(set) = self.get_capability::<cap::SetAForeground>() {
set.expand().color(idx).to(WriteWrapper::new(out))?;
set.expand().color(idx).to(out.by_ref())?;
} else {
write!(
out,
@@ -207,7 +209,7 @@ impl TerminfoRenderer {
(false, ColorAttribute::TrueColorWithPaletteFallback(_, idx))
| (_, ColorAttribute::PaletteIndex(idx)) => {
if let Some(set) = self.get_capability::<cap::SetABackground>() {
set.expand().color(idx).to(WriteWrapper::new(out))?;
set.expand().color(idx).to(out.by_ref())?;
} else {
write!(
out,
@@ -237,39 +239,13 @@ impl TerminfoRenderer {
}
}
// 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 Terminal,
}
impl<'a> WriteWrapper<'a> {
fn new(out: &'a mut Terminal) -> Self {
Self { out }
}
}
impl<'a> Write for WriteWrapper<'a> {
fn write(&mut self, buf: &[u8]) -> Result<usize, IoError> {
self.out.write(buf)
}
fn flush(&mut self) -> Result<(), IoError> {
self.out.flush()
}
}
impl Renderer for TerminfoRenderer {
fn render_to(
impl TerminfoRenderer {
pub fn render_to<R: UnixTty + Read, W: UnixTty + Write>(
&mut self,
start_attr: &CellAttributes,
changes: &[Change],
out: &mut Terminal,
) -> Result<CellAttributes, failure::Error> {
self.current_attr = start_attr.clone();
self.pending_attr = None;
_read: &mut R,
out: &mut W,
) -> Result<(), failure::Error> {
macro_rules! record {
($accesor:ident, $value:expr) => {
self.attr_apply(|attr| {
@@ -296,10 +272,10 @@ impl Renderer for TerminfoRenderer {
// or we're clearing to the default background color, so we can
// simply emit a clear screen op.
if let Some(clr) = self.get_capability::<cap::ClearScreen>() {
clr.expand().to(WriteWrapper::new(out))?;
clr.expand().to(out.by_ref())?;
} else {
if let Some(attr) = self.get_capability::<cap::CursorHome>() {
attr.expand().to(WriteWrapper::new(out))?;
attr.expand().to(out.by_ref())?;
} else {
write!(
out,
@@ -319,13 +295,13 @@ impl Renderer for TerminfoRenderer {
// paint the whole thing.
if let Some(attr) = self.get_capability::<cap::CursorHome>() {
attr.expand().to(WriteWrapper::new(out))?;
attr.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Cursor(Cursor::Position { line: 1, col: 1 }))?;
}
let size = out.get_screen_size()?;
let num_spaces = size.cols * size.rows;
let size = out.get_size()?;
let num_spaces = size.ws_col as usize * size.ws_row as usize;
let mut buf = Vec::with_capacity(num_spaces);
buf.resize(num_spaces, b' ');
out.write(buf.as_slice())?;
@@ -366,20 +342,20 @@ impl Renderer for TerminfoRenderer {
}
Change::Text(text) => {
self.flush_pending_attr(out)?;
WriteWrapper::new(out).write_all(text.as_bytes())?;
out.by_ref().write_all(text.as_bytes())?;
}
Change::CursorPosition {
x: Position::Absolute(0),
y: Position::Relative(1),
} => {
WriteWrapper::new(out).write_all(b"\r\n")?;
out.by_ref().write_all(b"\r\n")?;
}
Change::CursorPosition {
x: Position::Absolute(0),
y: Position::Absolute(0),
} => {
if let Some(attr) = self.get_capability::<cap::CursorHome>() {
attr.expand().to(WriteWrapper::new(out))?;
attr.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Cursor(Cursor::Position { line: 1, col: 1 }))?;
}
@@ -389,7 +365,7 @@ impl Renderer for TerminfoRenderer {
y: Position::Relative(1),
} => {
if let Some(attr) = self.get_capability::<cap::CursorDown>() {
attr.expand().to(WriteWrapper::new(out))?;
attr.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Cursor(Cursor::Down(1)))?;
}
@@ -399,7 +375,7 @@ impl Renderer for TerminfoRenderer {
y: Position::Relative(-1),
} => {
if let Some(attr) = self.get_capability::<cap::CursorUp>() {
attr.expand().to(WriteWrapper::new(out))?;
attr.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Cursor(Cursor::Up(1)))?;
}
@@ -409,7 +385,7 @@ impl Renderer for TerminfoRenderer {
y: Position::NoChange,
} => {
if let Some(attr) = self.get_capability::<cap::CursorLeft>() {
attr.expand().to(WriteWrapper::new(out))?;
attr.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Cursor(Cursor::Left(1)))?;
}
@@ -419,7 +395,7 @@ impl Renderer for TerminfoRenderer {
y: Position::NoChange,
} => {
if let Some(attr) = self.get_capability::<cap::CursorRight>() {
attr.expand().to(WriteWrapper::new(out))?;
attr.expand().to(out.by_ref())?;
} else {
write!(out, "{}", CSI::Cursor(Cursor::Right(1)))?;
}
@@ -433,7 +409,7 @@ impl Renderer for TerminfoRenderer {
if let Some(attr) = self.get_capability::<cap::CursorAddress>() {
// 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(WriteWrapper::new(out))?;
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.
@@ -458,7 +434,7 @@ impl Renderer for TerminfoRenderer {
self.flush_pending_attr(out)?;
out.flush()?;
Ok(self.current_attr.clone())
Ok(())
}
}
@@ -470,8 +446,14 @@ mod test {
use escape::parser::Parser;
use escape::{Action, Esc, EscCode};
use failure::Error;
use libc::winsize;
use std::io::{Error as IoError, ErrorKind, Read, Result as IoResult, Write};
use std::mem;
use terminal::unix::{Purge, SetAttributeWhen, UnixTty};
use terminal::ScreenSize;
use terminal::{cast, Terminal};
use terminfo;
use termios::Termios;
/// Return Capabilities loaded from the included xterm terminfo data
fn xterm_terminfo() -> Capabilities {
@@ -497,48 +479,109 @@ mod test {
).unwrap()
}
use std::io::{Read, Result as IOResult, Write};
struct FakeTerm {
struct FakeTty {
buf: Vec<u8>,
size: ScreenSize,
size: winsize,
termios: Termios,
}
impl FakeTerm {
fn new() -> Self {
Self::new_with_size(80, 24)
}
impl FakeTty {
fn new_with_size(width: usize, height: usize) -> Self {
let size = ScreenSize {
cols: width,
rows: height,
xpixel: 0,
ypixel: 0,
let size = winsize {
ws_col: cast(width).unwrap(),
ws_row: cast(height).unwrap(),
ws_xpixel: 0,
ws_ypixel: 0,
};
let buf = Vec::new();
Self { size, buf }
}
fn parse(&self) -> Vec<Action> {
let mut p = Parser::new();
p.parse_as_vec(&self.buf)
Self {
size,
buf,
termios: unsafe { mem::zeroed() },
}
}
}
impl Write for FakeTerm {
fn write(&mut self, buf: &[u8]) -> IOResult<usize> {
impl UnixTty for FakeTty {
fn get_size(&mut self) -> Result<winsize, Error> {
Ok(self.size.clone())
}
fn set_size(&mut self, size: winsize) -> Result<(), Error> {
self.size = size.clone();
Ok(())
}
fn get_termios(&mut self) -> Result<Termios, Error> {
Ok(self.termios.clone())
}
fn set_termios(&mut self, termios: &Termios, _when: SetAttributeWhen) -> Result<(), Error> {
self.termios = termios.clone();
Ok(())
}
/// Waits until all written data has been transmitted.
fn drain(&mut self) -> Result<(), Error> {
Ok(())
}
fn purge(&mut self, _purge: Purge) -> Result<(), Error> {
Ok(())
}
}
impl Read for FakeTty {
fn read(&mut self, _buf: &mut [u8]) -> Result<usize, IoError> {
Err(IoError::new(ErrorKind::Other, "not implemented"))
}
}
impl Write for FakeTty {
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
self.buf.write(buf)
}
fn flush(&mut self) -> IOResult<()> {
fn flush(&mut self) -> IoResult<()> {
self.buf.flush()
}
}
struct FakeTerm {
read: FakeTty,
write: FakeTty,
renderer: TerminfoRenderer,
}
impl FakeTerm {
fn new(caps: Capabilities) -> Self {
Self::new_with_size(caps, 80, 24)
}
fn new_with_size(caps: Capabilities, width: usize, height: usize) -> Self {
let read = FakeTty::new_with_size(width, height);
let write = FakeTty::new_with_size(width, height);
let renderer = TerminfoRenderer::new(caps);
Self {
read,
write,
renderer,
}
}
fn parse(&self) -> Vec<Action> {
let mut p = Parser::new();
p.parse_as_vec(&self.write.buf)
}
}
impl Write for FakeTerm {
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
self.write.write(buf)
}
fn flush(&mut self) -> IoResult<()> {
self.write.flush()
}
}
impl Read for FakeTerm {
fn read(&mut self, _buf: &mut [u8]) -> IOResult<usize> {
Ok(0)
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
self.read.read(buf)
}
}
@@ -546,57 +589,56 @@ mod test {
fn set_raw_mode(&mut self) -> Result<(), Error> {
bail!("not implemented");
}
fn render(&mut self, changes: &[Change]) -> Result<(), Error> {
self.renderer
.render_to(changes, &mut self.read, &mut self.write)
}
fn get_screen_size(&mut self) -> Result<ScreenSize, Error> {
Ok(self.size.clone())
let size = self.write.get_size()?;
Ok(ScreenSize {
rows: cast(size.ws_row)?,
cols: cast(size.ws_col)?,
xpixel: cast(size.ws_xpixel)?,
ypixel: cast(size.ws_ypixel)?,
})
}
fn set_screen_size(&mut self, size: ScreenSize) -> Result<(), Error> {
self.size = size;
Ok(())
let size = winsize {
ws_row: cast(size.rows)?,
ws_col: cast(size.cols)?,
ws_xpixel: cast(size.xpixel)?,
ws_ypixel: cast(size.ypixel)?,
};
self.write.set_size(size)
}
}
#[test]
fn empty_render() {
let mut out = FakeTerm::new();
let mut renderer = TerminfoRenderer::new(xterm_terminfo());
let end_attr = renderer
.render_to(&CellAttributes::default(), &[], &mut out)
.unwrap();
assert_eq!("", String::from_utf8(out.buf).unwrap());
assert_eq!(end_attr, CellAttributes::default());
let mut out = FakeTerm::new(xterm_terminfo());
out.render(&[]).unwrap();
assert_eq!("", String::from_utf8(out.write.buf).unwrap());
assert_eq!(out.renderer.current_attr, CellAttributes::default());
}
#[test]
fn basic_text() {
let mut out = FakeTerm::new();
let mut renderer = TerminfoRenderer::new(xterm_terminfo());
let end_attr = renderer
.render_to(
&CellAttributes::default(),
&[Change::Text("foo".into())],
&mut out,
)
.unwrap();
assert_eq!("foo", String::from_utf8(out.buf).unwrap());
assert_eq!(end_attr, CellAttributes::default());
let mut out = FakeTerm::new(xterm_terminfo());
out.render(&[Change::Text("foo".into())]).unwrap();
assert_eq!("foo", String::from_utf8(out.write.buf).unwrap());
assert_eq!(out.renderer.current_attr, CellAttributes::default());
}
#[test]
fn bold_text() {
let mut out = FakeTerm::new();
let mut renderer = TerminfoRenderer::new(xterm_terminfo());
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();
let mut out = FakeTerm::new(xterm_terminfo());
out.render(&[
Change::Text("not ".into()),
Change::Attribute(AttributeChange::Intensity(Intensity::Bold)),
Change::Text("foo".into()),
]).unwrap();
let result = out.parse();
assert_eq!(
@@ -616,7 +658,7 @@ mod test {
);
assert_eq!(
end_attr,
out.renderer.current_attr,
CellAttributes::default()
.set_intensity(Intensity::Bold)
.clone()
@@ -625,14 +667,8 @@ mod test {
#[test]
fn clear_screen() {
let mut out = FakeTerm::new_with_size(4, 3);
let mut renderer = TerminfoRenderer::new(xterm_terminfo());
let end_attr = renderer
.render_to(
&CellAttributes::default(),
&[Change::ClearScreen(ColorAttribute::default())],
&mut out,
)
let mut out = FakeTerm::new_with_size(xterm_terminfo(), 4, 3);
out.render(&[Change::ClearScreen(ColorAttribute::default())])
.unwrap();
let result = out.parse();
@@ -646,19 +682,13 @@ mod test {
]
);
assert_eq!(end_attr, CellAttributes::default());
assert_eq!(out.renderer.current_attr, CellAttributes::default());
}
#[test]
fn clear_screen_bce() {
let mut out = FakeTerm::new_with_size(4, 3);
let mut renderer = TerminfoRenderer::new(xterm_terminfo());
let end_attr = renderer
.render_to(
&CellAttributes::default(),
&[Change::ClearScreen(AnsiColor::Maroon.into())],
&mut out,
)
let mut out = FakeTerm::new_with_size(xterm_terminfo(), 4, 3);
out.render(&[Change::ClearScreen(AnsiColor::Maroon.into())])
.unwrap();
let result = out.parse();
@@ -674,7 +704,7 @@ mod test {
);
assert_eq!(
end_attr,
out.renderer.current_attr,
CellAttributes::default()
.set_background(AnsiColor::Maroon)
.clone()
@@ -683,14 +713,8 @@ mod test {
#[test]
fn clear_screen_no_terminfo() {
let mut out = FakeTerm::new_with_size(4, 3);
let mut renderer = TerminfoRenderer::new(no_terminfo_all_enabled());
let end_attr = renderer
.render_to(
&CellAttributes::default(),
&[Change::ClearScreen(ColorAttribute::default())],
&mut out,
)
let mut out = FakeTerm::new_with_size(no_terminfo_all_enabled(), 4, 3);
out.render(&[Change::ClearScreen(ColorAttribute::default())])
.unwrap();
let result = out.parse();
@@ -704,19 +728,13 @@ mod test {
]
);
assert_eq!(end_attr, CellAttributes::default());
assert_eq!(out.renderer.current_attr, CellAttributes::default());
}
#[test]
fn clear_screen_bce_no_terminfo() {
let mut out = FakeTerm::new_with_size(4, 3);
let mut renderer = TerminfoRenderer::new(no_terminfo_all_enabled());
let end_attr = renderer
.render_to(
&CellAttributes::default(),
&[Change::ClearScreen(AnsiColor::Maroon.into())],
&mut out,
)
let mut out = FakeTerm::new_with_size(no_terminfo_all_enabled(), 4, 3);
out.render(&[Change::ClearScreen(AnsiColor::Maroon.into())])
.unwrap();
let result = out.parse();
@@ -743,7 +761,7 @@ mod test {
);
assert_eq!(
end_attr,
out.renderer.current_attr,
CellAttributes::default()
.set_background(AnsiColor::Maroon)
.clone()
@@ -752,19 +770,12 @@ mod test {
#[test]
fn bold_text_no_terminfo() {
let mut out = FakeTerm::new();
let mut renderer = TerminfoRenderer::new(no_terminfo_all_enabled());
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();
let mut out = FakeTerm::new(no_terminfo_all_enabled());
out.render(&[
Change::Text("not ".into()),
Change::Attribute(AttributeChange::Intensity(Intensity::Bold)),
Change::Text("foo".into()),
]).unwrap();
let result = out.parse();
assert_eq!(
@@ -783,7 +794,7 @@ mod test {
);
assert_eq!(
end_attr,
out.renderer.current_attr,
CellAttributes::default()
.set_intensity(Intensity::Bold)
.clone()
@@ -792,20 +803,13 @@ mod test {
#[test]
fn red_bold_text() {
let mut out = FakeTerm::new();
let mut renderer = TerminfoRenderer::new(xterm_terminfo());
let end_attr = renderer
.render_to(
&CellAttributes::default(),
&[
Change::Attribute(AttributeChange::Foreground(AnsiColor::Maroon.into())),
Change::Attribute(AttributeChange::Intensity(Intensity::Bold)),
Change::Text("red".into()),
Change::Attribute(AttributeChange::Foreground(AnsiColor::Red.into())),
],
&mut out,
)
.unwrap();
let mut out = FakeTerm::new(xterm_terminfo());
out.render(&[
Change::Attribute(AttributeChange::Foreground(AnsiColor::Maroon.into())),
Change::Attribute(AttributeChange::Intensity(Intensity::Bold)),
Change::Text("red".into()),
Change::Attribute(AttributeChange::Foreground(AnsiColor::Red.into())),
]).unwrap();
let result = out.parse();
assert_eq!(
@@ -824,7 +828,7 @@ mod test {
);
assert_eq!(
end_attr,
out.renderer.current_attr,
CellAttributes::default()
.set_intensity(Intensity::Bold)
.set_foreground(AnsiColor::Red)
@@ -834,20 +838,13 @@ mod test {
#[test]
fn red_bold_text_no_terminfo() {
let mut out = FakeTerm::new();
let mut renderer = TerminfoRenderer::new(no_terminfo_all_enabled());
let end_attr = renderer
.render_to(
&CellAttributes::default(),
&[
Change::Attribute(AttributeChange::Foreground(AnsiColor::Maroon.into())),
Change::Attribute(AttributeChange::Intensity(Intensity::Bold)),
Change::Text("red".into()),
Change::Attribute(AttributeChange::Foreground(AnsiColor::Red.into())),
],
&mut out,
)
.unwrap();
let mut out = FakeTerm::new(no_terminfo_all_enabled());
out.render(&[
Change::Attribute(AttributeChange::Foreground(AnsiColor::Maroon.into())),
Change::Attribute(AttributeChange::Intensity(Intensity::Bold)),
Change::Text("red".into()),
Change::Attribute(AttributeChange::Foreground(AnsiColor::Red.into())),
]).unwrap();
let result = out.parse();
assert_eq!(
@@ -865,7 +862,7 @@ mod test {
);
assert_eq!(
end_attr,
out.renderer.current_attr,
CellAttributes::default()
.set_intensity(Intensity::Bold)
.set_foreground(AnsiColor::Red)
@@ -875,20 +872,13 @@ mod test {
#[test]
fn truecolor() {
let mut out = FakeTerm::new();
let mut renderer = TerminfoRenderer::new(xterm_terminfo());
renderer
.render_to(
&CellAttributes::default(),
&[
Change::Attribute(AttributeChange::Foreground(
ColorSpec::TrueColor(RgbColor::new(255, 128, 64)).into(),
)),
Change::Text("A".into()),
],
&mut out,
)
.unwrap();
let mut out = FakeTerm::new(xterm_terminfo());
out.render(&[
Change::Attribute(AttributeChange::Foreground(
ColorSpec::TrueColor(RgbColor::new(255, 128, 64)).into(),
)),
Change::Text("A".into()),
]).unwrap();
let result = out.parse();
assert_eq!(
@@ -904,20 +894,13 @@ mod test {
#[test]
fn truecolor_no_terminfo() {
let mut out = FakeTerm::new();
let mut renderer = TerminfoRenderer::new(no_terminfo_all_enabled());
renderer
.render_to(
&CellAttributes::default(),
&[
Change::Attribute(AttributeChange::Foreground(
ColorSpec::TrueColor(RgbColor::new(255, 128, 64)).into(),
)),
Change::Text("A".into()),
],
&mut out,
)
.unwrap();
let mut out = FakeTerm::new(no_terminfo_all_enabled());
out.render(&[
Change::Attribute(AttributeChange::Foreground(
ColorSpec::TrueColor(RgbColor::new(255, 128, 64)).into(),
)),
Change::Text("A".into()),
]).unwrap();
let result = out.parse();
assert_eq!(
+38 -43
View File
@@ -1,23 +1,28 @@
//! A Renderer for windows consoles
use caps::Capabilities;
use cell::{AttributeChange, CellAttributes, Underline};
use color::{AnsiColor, ColorAttribute};
use failure;
use num;
use render::Renderer;
use screen::{Change, Position};
use terminal::Terminal;
use std::io::{Read, Write};
use terminal::windows::{ConsoleInputHandle, ConsoleOutputHandle};
use winapi::um::wincon::{
BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_INTENSITY, BACKGROUND_RED,
COMMON_LVB_REVERSE_VIDEO, COMMON_LVB_UNDERSCORE, FOREGROUND_BLUE, FOREGROUND_GREEN,
FOREGROUND_INTENSITY, FOREGROUND_RED,
};
pub struct WindowsConsoleRenderer {}
pub struct WindowsConsoleRenderer {
current_attr: CellAttributes,
}
impl WindowsConsoleRenderer {
pub fn new() -> Self {
Self {}
pub fn new(_caps: Capabilities) -> Self {
Self {
current_attr: CellAttributes::default(),
}
}
}
@@ -106,30 +111,28 @@ fn to_attr_word(attr: &CellAttributes) -> u16 {
bg | fg | reverse | underline
}
impl Renderer for WindowsConsoleRenderer {
fn render_to(
impl WindowsConsoleRenderer {
pub fn render_to<A: ConsoleInputHandle + Read, B: ConsoleOutputHandle + Write>(
&mut self,
starting_attr: &CellAttributes,
changes: &[Change],
out: &mut Terminal,
) -> Result<CellAttributes, failure::Error> {
let mut current_attr = starting_attr.clone();
_read: &mut A,
out: &mut B,
) -> Result<(), failure::Error> {
for change in changes {
match change {
Change::ClearScreen(color) => {
out.flush()?;
current_attr = CellAttributes::default()
self.current_attr = CellAttributes::default()
.set_background(color.clone())
.clone();
let info = out.get_console_output_handle().get_buffer_info()?;
let info = out.get_buffer_info()?;
// We want to clear only the viewport; we don't want to toss out
// the scrollback.
if info.srWindow.Left != 0 {
// The user has scrolled the viewport horizontally; let's move
// it back to the left for the sake of sanity
out.get_console_output_handle().set_viewport(
out.set_viewport(
0,
info.srWindow.Top,
info.srWindow.Right - info.srWindow.Left,
@@ -141,30 +144,23 @@ impl Renderer for WindowsConsoleRenderer {
// And clear all of the visible lines from this point down
let visible_height = info.dwSize.Y as u32 - info.srWindow.Top as u32;
let num_spaces = visible_width * visible_height;
out.get_console_output_handle().fill_char(
' ',
out.fill_char(' ', 0, info.srWindow.Top, num_spaces as u32)?;
out.fill_attr(
to_attr_word(&self.current_attr),
0,
info.srWindow.Top,
num_spaces as u32,
)?;
out.get_console_output_handle().fill_attr(
to_attr_word(&current_attr),
0,
info.srWindow.Top,
num_spaces as u32,
)?;
out.get_console_output_handle()
.set_cursor_position(0, info.srWindow.Top)?;
out.set_cursor_position(0, info.srWindow.Top)?;
}
Change::Text(text) => {
out.flush()?;
out.get_console_output_handle()
.set_attr(to_attr_word(&current_attr))?;
out.set_attr(to_attr_word(&self.current_attr))?;
out.write_all(text.as_bytes())?;
}
Change::CursorPosition { x, y } => {
out.flush()?;
let info = out.get_console_output_handle().get_buffer_info()?;
let info = out.get_buffer_info()?;
// For horizontal cursor movement, we consider the full width
// of the screen buffer, even if the viewport is smaller
let x = match x {
@@ -182,46 +178,45 @@ impl Renderer for WindowsConsoleRenderer {
Position::EndRelative(delta) => info.srWindow.Bottom - *delta as i16,
};
out.get_console_output_handle().set_cursor_position(x, y)?;
out.set_cursor_position(x, y)?;
}
Change::Attribute(AttributeChange::Intensity(value)) => {
current_attr.set_intensity(*value);
self.current_attr.set_intensity(*value);
}
Change::Attribute(AttributeChange::Italic(value)) => {
current_attr.set_italic(*value);
self.current_attr.set_italic(*value);
}
Change::Attribute(AttributeChange::Reverse(value)) => {
current_attr.set_reverse(*value);
self.current_attr.set_reverse(*value);
}
Change::Attribute(AttributeChange::StrikeThrough(value)) => {
current_attr.set_strikethrough(*value);
self.current_attr.set_strikethrough(*value);
}
Change::Attribute(AttributeChange::Blink(value)) => {
current_attr.set_blink(*value);
self.current_attr.set_blink(*value);
}
Change::Attribute(AttributeChange::Invisible(value)) => {
current_attr.set_invisible(*value);
self.current_attr.set_invisible(*value);
}
Change::Attribute(AttributeChange::Underline(value)) => {
current_attr.set_underline(*value);
self.current_attr.set_underline(*value);
}
Change::Attribute(AttributeChange::Foreground(col)) => {
current_attr.set_foreground(*col);
self.current_attr.set_foreground(*col);
}
Change::Attribute(AttributeChange::Background(col)) => {
current_attr.set_background(*col);
self.current_attr.set_background(*col);
}
Change::Attribute(AttributeChange::Hyperlink(link)) => {
current_attr.hyperlink = link.clone();
self.current_attr.hyperlink = link.clone();
}
Change::AllAttributes(all) => {
current_attr = all.clone();
self.current_attr = all.clone();
}
}
}
out.flush()?;
out.get_console_output_handle()
.set_attr(to_attr_word(&current_attr))?;
Ok(current_attr)
out.set_attr(to_attr_word(&self.current_attr))?;
Ok(())
}
}
+7 -8
View File
@@ -6,6 +6,7 @@
use failure::Error;
use num::{self, NumCast};
use screen::Change;
use std::fmt::Display;
use std::io::{Read, Write};
@@ -17,7 +18,7 @@ pub mod windows;
#[cfg(unix)]
pub use self::unix::UnixTerminal;
#[cfg(windows)]
pub use self::windows::{ConsoleInputHandle, ConsoleOutputHandle, WindowsTerminal};
pub use self::windows::WindowsTerminal;
/// Represents the size of the terminal screen.
/// The number of rows and columns of character cells are expressed.
@@ -56,20 +57,18 @@ pub trait Terminal: Read + Write {
/// Sets the current screen size
fn set_screen_size(&mut self, size: ScreenSize) -> Result<(), Error>;
/// Render a series of changes to the terminal output
fn render(&mut self, changes: &[Change]) -> Result<(), Error>;
/*
/// Sets the terminal to cooked mode, which is essentially the opposite
/// to raw mode: input and output processing are enabled.
fn set_cooked_mode(&mut self) -> Result<(), Error>;
*/
#[cfg(windows)]
fn get_console_input_handle(&mut self) -> &mut ConsoleInputHandle;
#[cfg(windows)]
fn get_console_output_handle(&mut self) -> &mut ConsoleOutputHandle;
*/
}
const BUF_SIZE: usize = 128;
fn cast<T: NumCast + Display + Copy, U: NumCast>(n: T) -> Result<U, Error> {
pub(crate) fn cast<T: NumCast + Display + Copy, U: NumCast>(n: T) -> Result<U, Error> {
num::cast(n).ok_or_else(|| format_err!("{} is out of bounds for this system", n))
}
+22 -13
View File
@@ -9,6 +9,9 @@ use termios::{
TCSAFLUSH, TCSANOW,
};
use caps::Capabilities;
use render::terminfo::TerminfoRenderer;
use screen::Change;
use terminal::{cast, ScreenSize, Terminal, BUF_SIZE};
/// Helper function to duplicate a file descriptor.
@@ -147,6 +150,7 @@ pub struct UnixTerminal {
write: TtyHandle,
saved_termios: Termios,
write_buffer: Vec<u8>,
renderer: TerminfoRenderer,
}
impl UnixTerminal {
@@ -155,16 +159,25 @@ impl UnixTerminal {
/// Note that this will duplicate the underlying file descriptors
/// and will no longer participate in the stdin/stdout locking
/// provided by the rust standard library.
pub fn new_from_stdio() -> Result<UnixTerminal, Error> {
let read = TtyHandle::new(&stdin())?;
let mut write = TtyHandle::new(&stdout())?;
pub fn new_from_stdio(caps: Capabilities) -> Result<UnixTerminal, Error> {
Self::new_with(caps, &stdin(), &stdout())
}
pub fn new_with<A: AsRawFd, B: AsRawFd>(
caps: Capabilities,
read: &A,
write: &B,
) -> Result<UnixTerminal, Error> {
let read = TtyHandle::new(read)?;
let mut write = TtyHandle::new(write)?;
let saved_termios = write.get_termios()?;
let renderer = TerminfoRenderer::new(caps);
Ok(UnixTerminal {
read,
write,
saved_termios,
renderer,
write_buffer: Vec::with_capacity(BUF_SIZE),
})
}
@@ -173,18 +186,10 @@ impl UnixTerminal {
/// (/dev/tty) and build a `UnixTerminal` from there. This will
/// yield a terminal even if the stdio streams have been redirected,
/// provided that the process has an associated controlling terminal.
pub fn new() -> Result<UnixTerminal, Error> {
pub fn new(caps: Capabilities) -> Result<UnixTerminal, Error> {
use std::fs::OpenOptions;
let file = OpenOptions::new().read(true).write(true).open("/dev/tty")?;
let read = TtyHandle::new(&file)?;
let mut write = TtyHandle::new(&file)?;
let saved_termios = write.get_termios()?;
Ok(UnixTerminal {
read,
write,
saved_termios,
write_buffer: Vec::with_capacity(BUF_SIZE),
})
Self::new_with(caps, &file, &file)
}
fn flush_local_buffer_only(&mut self) -> IOResult<()> {
@@ -249,6 +254,10 @@ impl Terminal for UnixTerminal {
self.write.set_size(size)
}
fn render(&mut self, changes: &[Change]) -> Result<(), Error> {
self.renderer
.render_to(changes, &mut self.read, &mut self.write)
}
}
impl Drop for UnixTerminal {
+26 -7
View File
@@ -13,6 +13,9 @@ use winapi::um::wincon::{
ENABLE_VIRTUAL_TERMINAL_PROCESSING, SMALL_RECT,
};
use caps::Capabilities;
use render::windows::WindowsConsoleRenderer;
use screen::Change;
use terminal::{cast, ScreenSize, Terminal, BUF_SIZE};
pub trait ConsoleInputHandle {
@@ -49,6 +52,12 @@ impl DerefMut for InputHandle {
}
}
impl Read for InputHandle {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, IOError> {
self.handle.read(buf)
}
}
impl ConsoleInputHandle for InputHandle {
fn set_input_mode(&mut self, mode: u32) -> Result<(), Error> {
if unsafe { consoleapi::SetConsoleMode(self.handle.as_raw_handle(), mode) } == 0 {
@@ -84,6 +93,16 @@ impl DerefMut for OutputHandle {
}
}
impl Write for OutputHandle {
fn write(&mut self, buf: &[u8]) -> IOResult<usize> {
self.handle.write(buf)
}
fn flush(&mut self) -> IOResult<()> {
self.handle.flush()
}
}
impl ConsoleOutputHandle for OutputHandle {
fn set_output_mode(&mut self, mode: u32) -> Result<(), Error> {
self.handle.flush()?;
@@ -201,6 +220,7 @@ pub struct WindowsTerminal {
write_buffer: Vec<u8>,
saved_input_mode: u32,
saved_output_mode: u32,
renderer: WindowsConsoleRenderer,
}
impl Drop for WindowsTerminal {
@@ -215,7 +235,7 @@ impl Drop for WindowsTerminal {
}
impl WindowsTerminal {
pub fn new() -> Result<Self, Error> {
pub fn new(caps: Capabilities) -> Result<Self, Error> {
let read = stdin();
let write = stdout();
@@ -228,12 +248,14 @@ impl WindowsTerminal {
let saved_input_mode = input_handle.get_input_mode()?;
let saved_output_mode = output_handle.get_output_mode()?;
let renderer = WindowsConsoleRenderer::new(caps);
Ok(Self {
input_handle,
output_handle,
saved_input_mode,
saved_output_mode,
renderer,
write_buffer: Vec::with_capacity(BUF_SIZE),
})
}
@@ -324,11 +346,8 @@ impl Terminal for WindowsTerminal {
Ok(())
}
fn get_console_input_handle(&mut self) -> &mut ConsoleInputHandle {
&mut self.input_handle
}
fn get_console_output_handle(&mut self) -> &mut ConsoleOutputHandle {
&mut self.output_handle
fn render(&mut self, changes: &[Change]) -> Result<(), Error> {
self.renderer
.render_to(changes, &mut self.input_handle, &mut self.output_handle)
}
}