API Cleanup - part 3 (#240)

This commit is contained in:
Zrzka 2019-09-20 23:50:53 +02:00 committed by Timon
parent 60cd12710a
commit 5216ecbdec
28 changed files with 152 additions and 163 deletions

1
.github/CODEOWNERS vendored Normal file
View File

@ -0,0 +1 @@
* @TimonPost

View File

@ -183,7 +183,7 @@ cursor.goto(5,20);
// Print at X: 5 Y: 20. // Print at X: 5 Y: 20.
print!("Yea!"); print!("Yea!");
// Reset back to X: 5 Y: 5. // Reset back to X: 5 Y: 5.
cursor.reset_position(); cursor.restore_position();
// Print 'Back' at X: 5 Y: 5. // Print 'Back' at X: 5 Y: 5.
print!("Back"); print!("Back");

View File

@ -106,7 +106,7 @@ cursor.goto(5,20);
// Print at X: 5 Y: 20. // Print at X: 5 Y: 20.
print!("Yea!"); print!("Yea!");
// Reset back to X: 5 Y: 5. // Reset back to X: 5 Y: 5.
cursor.reset_position(); cursor.restore_position();
// Print 'Back' at X: 5 Y: 5. // Print 'Back' at X: 5 Y: 5.
print!("Back"); print!("Back");

View File

@ -42,7 +42,7 @@ trait ITerminalCursor: Sync + Send {
/// is stored program based not per instance of the cursor struct. /// is stored program based not per instance of the cursor struct.
fn save_position(&self) -> Result<()>; fn save_position(&self) -> Result<()>;
/// Return to saved cursor position /// Return to saved cursor position
fn reset_position(&self) -> Result<()>; fn restore_position(&self) -> Result<()>;
/// Hide the terminal cursor. /// Hide the terminal cursor.
fn hide(&self) -> Result<()>; fn hide(&self) -> Result<()>;
/// Show the terminal cursor /// Show the terminal cursor

View File

@ -28,8 +28,8 @@ pub fn get_move_left_ansi(count: u16) -> String {
format!(csi!("{}D"), count) format!(csi!("{}D"), count)
} }
pub static SAFE_POS_ANSI: &'static str = csi!("s"); pub static SAVE_POS_ANSI: &'static str = csi!("s");
pub static RESET_POS_ANSI: &'static str = csi!("u"); pub static RESTORE_POS_ANSI: &'static str = csi!("u");
pub static HIDE_ANSI: &'static str = csi!("?25l"); pub static HIDE_ANSI: &'static str = csi!("?25l");
pub static SHOW_ANSI: &'static str = csi!("?25h"); pub static SHOW_ANSI: &'static str = csi!("?25h");
pub static BLINK_ON_ANSI: &'static str = csi!("?12h"); pub static BLINK_ON_ANSI: &'static str = csi!("?12h");
@ -75,12 +75,12 @@ impl ITerminalCursor for AnsiCursor {
} }
fn save_position(&self) -> Result<()> { fn save_position(&self) -> Result<()> {
write_cout!(SAFE_POS_ANSI)?; write_cout!(SAVE_POS_ANSI)?;
Ok(()) Ok(())
} }
fn reset_position(&self) -> Result<()> { fn restore_position(&self) -> Result<()> {
write_cout!(RESET_POS_ANSI)?; write_cout!(RESTORE_POS_ANSI)?;
Ok(()) Ok(())
} }
@ -111,45 +111,37 @@ mod tests {
// TODO - Test is ingored, because it's stalled on Travis CI // TODO - Test is ingored, because it's stalled on Travis CI
#[test] #[test]
#[ignore] #[ignore]
fn reset_safe_ansi() { fn test_ansi_save_restore_position() {
if try_enable_ansi() { if try_enable_ansi() {
let cursor = AnsiCursor::new(); let cursor = AnsiCursor::new();
let pos = cursor.pos();
assert!(pos.is_ok());
let (x, y) = pos.unwrap();
assert!(cursor.save_position().is_ok()); let (saved_x, saved_y) = cursor.pos().unwrap();
assert!(cursor.goto(5, 5).is_ok());
assert!(cursor.reset_position().is_ok());
let pos = cursor.pos(); cursor.save_position().unwrap();
assert!(pos.is_ok()); cursor.goto(saved_x + 1, saved_y + 1).unwrap();
let (x_saved, y_saved) = pos.unwrap(); cursor.restore_position().unwrap();
assert_eq!(x, x_saved); let (x, y) = cursor.pos().unwrap();
assert_eq!(y, y_saved);
assert_eq!(x, saved_x);
assert_eq!(y, saved_y);
} }
} }
// TODO - Test is ingored, because it's stalled on Travis CI // TODO - Test is ingored, because it's stalled on Travis CI
#[test] #[test]
#[ignore] #[ignore]
fn goto_ansi() { fn test_ansi_goto() {
if try_enable_ansi() { if try_enable_ansi() {
let cursor = AnsiCursor::new(); let cursor = AnsiCursor::new();
let pos = cursor.pos();
assert!(pos.is_ok());
let (x_saved, y_saved) = pos.unwrap();
assert!(cursor.goto(5, 5).is_ok()); let (saved_x, saved_y) = cursor.pos().unwrap();
let pos = cursor.pos();
assert!(pos.is_ok());
let (x, y) = pos.unwrap();
assert!(cursor.goto(x_saved, y_saved).is_ok()); cursor.goto(saved_x + 1, saved_y + 1).unwrap();
assert_eq!(cursor.pos().unwrap(), (saved_x + 1, saved_y + 1));
assert_eq!(x, 5); cursor.goto(saved_x, saved_y).unwrap();
assert_eq!(y, 5); assert_eq!(cursor.pos().unwrap(), (saved_x, saved_y));
} }
} }

View File

@ -95,8 +95,8 @@ impl TerminalCursor {
} }
/// Return to saved cursor position /// Return to saved cursor position
pub fn reset_position(&self) -> Result<()> { pub fn restore_position(&self) -> Result<()> {
self.cursor.reset_position() self.cursor.restore_position()
} }
/// Hide de cursor in the console. /// Hide de cursor in the console.
@ -131,7 +131,7 @@ pub struct Goto(pub u16, pub u16);
impl Command for Goto { impl Command for Goto {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::get_goto_ansi(self.0, self.1) ansi_cursor::get_goto_ansi(self.0, self.1)
} }
@ -149,7 +149,7 @@ pub struct Up(pub u16);
impl Command for Up { impl Command for Up {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::get_move_up_ansi(self.0) ansi_cursor::get_move_up_ansi(self.0)
} }
@ -167,7 +167,7 @@ pub struct Down(pub u16);
impl Command for Down { impl Command for Down {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::get_move_down_ansi(self.0) ansi_cursor::get_move_down_ansi(self.0)
} }
@ -185,7 +185,7 @@ pub struct Left(pub u16);
impl Command for Left { impl Command for Left {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::get_move_left_ansi(self.0) ansi_cursor::get_move_left_ansi(self.0)
} }
@ -203,7 +203,7 @@ pub struct Right(pub u16);
impl Command for Right { impl Command for Right {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::get_move_right_ansi(self.0) ansi_cursor::get_move_right_ansi(self.0)
} }
@ -223,8 +223,8 @@ pub struct SavePos;
impl Command for SavePos { impl Command for SavePos {
type AnsiType = &'static str; type AnsiType = &'static str;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::SAFE_POS_ANSI ansi_cursor::SAVE_POS_ANSI
} }
#[cfg(windows)] #[cfg(windows)]
@ -241,13 +241,13 @@ pub struct ResetPos;
impl Command for ResetPos { impl Command for ResetPos {
type AnsiType = &'static str; type AnsiType = &'static str;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::RESET_POS_ANSI ansi_cursor::RESTORE_POS_ANSI
} }
#[cfg(windows)] #[cfg(windows)]
fn execute_winapi(&self) -> Result<()> { fn execute_winapi(&self) -> Result<()> {
WinApiCursor::new().reset_position() WinApiCursor::new().restore_position()
} }
} }
@ -259,7 +259,7 @@ pub struct Hide;
impl Command for Hide { impl Command for Hide {
type AnsiType = &'static str; type AnsiType = &'static str;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::HIDE_ANSI ansi_cursor::HIDE_ANSI
} }
@ -277,7 +277,7 @@ pub struct Show;
impl Command for Show { impl Command for Show {
type AnsiType = &'static str; type AnsiType = &'static str;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::SHOW_ANSI ansi_cursor::SHOW_ANSI
} }
@ -298,7 +298,7 @@ pub struct BlinkOn;
impl Command for BlinkOn { impl Command for BlinkOn {
type AnsiType = &'static str; type AnsiType = &'static str;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::BLINK_ON_ANSI ansi_cursor::BLINK_ON_ANSI
} }
@ -319,7 +319,7 @@ pub struct BlinkOff;
impl Command for BlinkOff { impl Command for BlinkOff {
type AnsiType = &'static str; type AnsiType = &'static str;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_cursor::BLINK_OFF_ANSI ansi_cursor::BLINK_OFF_ANSI
} }

View File

@ -58,8 +58,8 @@ impl ITerminalCursor for WinApiCursor {
Ok(()) Ok(())
} }
fn reset_position(&self) -> Result<()> { fn restore_position(&self) -> Result<()> {
Cursor::reset_to_saved_position()?; Cursor::restore_cursor_pos()?;
Ok(()) Ok(())
} }
@ -83,35 +83,31 @@ mod tests {
use super::{ITerminalCursor, WinApiCursor}; use super::{ITerminalCursor, WinApiCursor};
#[test] #[test]
fn goto_winapi() { fn test_winapi_goto() {
let cursor = WinApiCursor::new(); let cursor = WinApiCursor::new();
assert!(cursor.goto(5, 5).is_ok()); let (saved_x, saved_y) = cursor.pos().unwrap();
let pos = cursor.pos();
assert!(pos.is_ok());
let (x, y) = pos.unwrap();
assert_eq!(x, 5); cursor.goto(saved_x + 1, saved_y + 1).unwrap();
assert_eq!(y, 5); assert_eq!(cursor.pos().unwrap(), (saved_x + 1, saved_y + 1));
cursor.goto(saved_x, saved_y).unwrap();
assert_eq!(cursor.pos().unwrap(), (saved_x, saved_y));
} }
#[test] #[test]
fn reset_safe_winapi() { fn test_winapi_save_and_restore() {
let cursor = WinApiCursor::new(); let cursor = WinApiCursor::new();
let pos = cursor.pos(); let (saved_x, saved_y) = cursor.pos().unwrap();
assert!(pos.is_ok());
let (x, y) = pos.unwrap();
assert!(cursor.save_position().is_ok()); cursor.save_position().unwrap();
assert!(cursor.goto(5, 5).is_ok()); cursor.goto(saved_x + 1, saved_y + 1).unwrap();
assert!(cursor.reset_position().is_ok()); cursor.restore_position().unwrap();
let pos = cursor.pos(); let (x, y) = cursor.pos().unwrap();
assert!(pos.is_ok());
let (x_saved, y_saved) = pos.unwrap();
assert_eq!(x, x_saved); assert_eq!(x, saved_x);
assert_eq!(y, y_saved); assert_eq!(y, saved_y);
} }
} }

View File

@ -26,7 +26,7 @@ pub fn show_cursor(show_cursor: bool) -> Result<()> {
} }
pub fn pos() -> Result<(u16, u16)> { pub fn pos() -> Result<(u16, u16)> {
unix::into_raw_mode()?; unix::enable_raw_mode()?;
let pos = pos_raw(); let pos = pos_raw();
unix::disable_raw_mode()?; unix::disable_raw_mode()?;
pos pos

View File

@ -67,7 +67,7 @@ impl Cursor {
unsafe { unsafe {
if !is_true(SetConsoleCursorPosition( if !is_true(SetConsoleCursorPosition(
**self.screen_buffer.get_handle(), **self.screen_buffer.handle(),
position, position,
)) { )) {
Err(io::Error::last_os_error())?; Err(io::Error::last_os_error())?;
@ -85,7 +85,7 @@ impl Cursor {
unsafe { unsafe {
if !is_true(SetConsoleCursorInfo( if !is_true(SetConsoleCursorInfo(
**self.screen_buffer.get_handle(), **self.screen_buffer.handle(),
&cursor_info, &cursor_info,
)) { )) {
Err(io::Error::last_os_error())?; Err(io::Error::last_os_error())?;
@ -95,7 +95,7 @@ impl Cursor {
} }
/// Reset to saved cursor position /// Reset to saved cursor position
pub fn reset_to_saved_position() -> Result<()> { pub fn restore_cursor_pos() -> Result<()> {
let cursor = Cursor::new()?; let cursor = Cursor::new()?;
unsafe { unsafe {

View File

@ -10,7 +10,7 @@ impl RawModeCommand {
/// Enables raw mode. /// Enables raw mode.
pub fn enable(&mut self) -> Result<()> { pub fn enable(&mut self) -> Result<()> {
crossterm_utils::sys::unix::into_raw_mode()?; crossterm_utils::sys::unix::enable_raw_mode()?;
Ok(()) Ok(())
} }

View File

@ -70,7 +70,7 @@ impl TerminalColor {
/// # Remarks /// # Remarks
/// ///
/// This does not always provide a good result. /// This does not always provide a good result.
pub fn get_available_color_count(&self) -> u16 { pub fn available_color_count(&self) -> u16 {
env::var("TERM") env::var("TERM")
.map(|x| if x.contains("256color") { 256 } else { 8 }) .map(|x| if x.contains("256color") { 256 } else { 8 })
.unwrap_or(8) .unwrap_or(8)
@ -90,7 +90,7 @@ pub struct SetFg(pub Color);
impl Command for SetFg { impl Command for SetFg {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_color::get_set_fg_ansi(self.0) ansi_color::get_set_fg_ansi(self.0)
} }
@ -108,7 +108,7 @@ pub struct SetBg(pub Color);
impl Command for SetBg { impl Command for SetBg {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_color::get_set_bg_ansi(self.0) ansi_color::get_set_bg_ansi(self.0)
} }
@ -126,7 +126,7 @@ pub struct SetAttr(pub Attribute);
impl Command for SetAttr { impl Command for SetAttr {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
ansi_color::get_set_attr_ansi(self.0) ansi_color::get_set_attr_ansi(self.0)
} }
@ -148,7 +148,7 @@ where
{ {
type AnsiType = StyledObject<D>; type AnsiType = StyledObject<D>;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
self.0.clone() self.0.clone()
} }

View File

@ -52,7 +52,7 @@ impl ITerminalColor for WinApiColor {
color = color | wincon::BACKGROUND_INTENSITY as u16; color = color | wincon::BACKGROUND_INTENSITY as u16;
} }
Console::from(**screen_buffer.get_handle()).set_text_attribute(color)?; Console::from(**screen_buffer.handle()).set_text_attribute(color)?;
Ok(()) Ok(())
} }
@ -79,7 +79,7 @@ impl ITerminalColor for WinApiColor {
color = color | wincon::FOREGROUND_INTENSITY as u16; color = color | wincon::FOREGROUND_INTENSITY as u16;
} }
Console::from(**screen_buffer.get_handle()).set_text_attribute(color)?; Console::from(**screen_buffer.handle()).set_text_attribute(color)?;
Ok(()) Ok(())
} }

View File

@ -88,21 +88,21 @@ mod tests {
// TODO - Test is disabled, because it's failing on Travis CI // TODO - Test is disabled, because it's failing on Travis CI
#[test] #[test]
#[ignore] #[ignore]
fn resize_ansi() { fn test_resize_ansi() {
if try_enable_ansi() { if try_enable_ansi() {
let terminal = AnsiTerminal::new(); let terminal = AnsiTerminal::new();
assert!(terminal.set_size(50, 50).is_ok()); let (width, height) = terminal.size().unwrap();
terminal.set_size(30, 30).unwrap();
// see issue: https://github.com/eminence/terminal-size/issues/11 // see issue: https://github.com/eminence/terminal-size/issues/11
thread::sleep(time::Duration::from_millis(30)); thread::sleep(time::Duration::from_millis(30));
assert_eq!((30, 30), terminal.size().unwrap());
let size = terminal.size(); terminal.set_size(width, height).unwrap();
assert!(size.is_ok()); // see issue: https://github.com/eminence/terminal-size/issues/11
let (x, y) = size.unwrap(); thread::sleep(time::Duration::from_millis(30));
assert_eq!((width, height), terminal.size().unwrap());
assert_eq!(x, 50);
assert_eq!(y, 50);
} }
} }

View File

@ -145,7 +145,7 @@ pub struct ScrollUp(pub u16);
impl Command for ScrollUp { impl Command for ScrollUp {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
super::ansi_terminal::get_scroll_up_ansi(self.0) super::ansi_terminal::get_scroll_up_ansi(self.0)
} }
@ -163,7 +163,7 @@ pub struct ScrollDown(pub u16);
impl Command for ScrollDown { impl Command for ScrollDown {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
super::ansi_terminal::get_scroll_down_ansi(self.0) super::ansi_terminal::get_scroll_down_ansi(self.0)
} }
@ -181,7 +181,7 @@ pub struct Clear(pub ClearType);
impl Command for Clear { impl Command for Clear {
type AnsiType = &'static str; type AnsiType = &'static str;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
match self.0 { match self.0 {
ClearType::All => { ClearType::All => {
return super::ansi_terminal::CLEAR_ALL; return super::ansi_terminal::CLEAR_ALL;
@ -211,7 +211,7 @@ pub struct SetSize(pub u16, pub u16);
impl Command for SetSize { impl Command for SetSize {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
super::ansi_terminal::get_set_size_ansi(self.0, self.1) super::ansi_terminal::get_set_size_ansi(self.0, self.1)
} }

View File

@ -93,7 +93,7 @@ impl ITerminal for WinApiTerminal {
// Get the position of the current console window // Get the position of the current console window
let screen_buffer = ScreenBuffer::current()?; let screen_buffer = ScreenBuffer::current()?;
let console = Console::from(**screen_buffer.get_handle()); let console = Console::from(**screen_buffer.handle());
let csbi = screen_buffer.info()?; let csbi = screen_buffer.info()?;
let current_size = csbi.buffer_size(); let current_size = csbi.buffer_size();
@ -283,16 +283,15 @@ mod tests {
// TODO - Test is ignored, because it returns wrong result (31 != 30) // TODO - Test is ignored, because it returns wrong result (31 != 30)
#[test] #[test]
#[ignore] #[ignore]
fn resize_winapi() { fn test_resize_winapi() {
let terminal = WinApiTerminal::new(); let terminal = WinApiTerminal::new();
assert!(terminal.set_size(30, 30).is_ok()); let (width, height) = terminal.size().unwrap();
let size = terminal.size(); terminal.set_size(30, 30).unwrap();
assert!(size.is_ok()); assert_eq!((30, 30), terminal.size().unwrap());
let (x, y) = size.unwrap();
assert_eq!(x, 30); terminal.set_size(width, height).unwrap();
assert_eq!(y, 30); assert_eq!((width, height), terminal.size().unwrap());
} }
} }

View File

@ -17,7 +17,7 @@ pub trait Command {
/// You are able to use ANSI escape codes only for windows 10 and UNIX systems. /// You are able to use ANSI escape codes only for windows 10 and UNIX systems.
/// ///
/// **This method is mainly used internally by crossterm!** /// **This method is mainly used internally by crossterm!**
fn get_ansi_code(&self) -> Self::AnsiType; fn ansi_code(&self) -> Self::AnsiType;
/// Execute this command. /// Execute this command.
/// ///
@ -104,7 +104,7 @@ pub struct Output(pub String);
impl Command for Output { impl Command for Output {
type AnsiType = String; type AnsiType = String;
fn get_ansi_code(&self) -> Self::AnsiType { fn ansi_code(&self) -> Self::AnsiType {
return self.0.clone(); return self.0.clone();
} }

View File

@ -5,24 +5,15 @@ use crate::sys::winapi::ansi::set_virtual_terminal_processing;
pub fn supports_ansi() -> bool { pub fn supports_ansi() -> bool {
// Some terminals on windows like GitBash can't use WinaApi calls directly so when we try to enable the ANSI-flag for windows this won't work. // Some terminals on windows like GitBash can't use WinaApi calls directly so when we try to enable the ANSI-flag for windows this won't work.
// Because of that we should check first if the TERM-variable is set and see if the current terminal is a terminal who does support ANSI. // Because of that we should check first if the TERM-variable is set and see if the current terminal is a terminal who does support ANSI.
let supports_ansi = is_specific_term();
match supports_ansi { if is_specific_term() {
true => { return true;
return true;
}
false => {
// if it is not listed we should try with WinApi to check if we do support ANSI-codes.
match set_virtual_terminal_processing(true) {
Ok(_) => {
return true;
}
Err(_) => {
return false;
}
}
}
} }
// if it is not listed we should try with WinApi to check if we do support ANSI-codes.
set_virtual_terminal_processing(true)
.map(|_| true)
.unwrap_or(false)
} }
// checks if the 'TERM' environment variable is set to check if the terminal supports ANSI-codes. // checks if the 'TERM' environment variable is set to check if the terminal supports ANSI-codes.

View File

@ -80,7 +80,7 @@ macro_rules! queue {
#[cfg(windows)] #[cfg(windows)]
{ {
if $crate::supports_ansi() { if $crate::supports_ansi() {
match write!($write, "{}", $command.get_ansi_code()) { match write!($write, "{}", $command.ansi_code()) {
Err(e) => { Err(e) => {
error = Some(Err($crate::ErrorKind::from(e))); error = Some(Err($crate::ErrorKind::from(e)));
} }
@ -96,7 +96,7 @@ macro_rules! queue {
}; };
} }
#[cfg(unix)] #[cfg(unix)]
match write!($write, "{}", $command.get_ansi_code()) { match write!($write, "{}", $command.ansi_code()) {
Err(e) => { Err(e) => {
error = Some(Err($crate::ErrorKind::from(e))); error = Some(Err($crate::ErrorKind::from(e)));
} }
@ -154,7 +154,7 @@ macro_rules! execute {
#[cfg(windows)] #[cfg(windows)]
{ {
if $crate::supports_ansi() { if $crate::supports_ansi() {
if let Err(e) = write_cout!($write, $command.get_ansi_code()) { if let Err(e) = write_cout!($write, $command.ansi_code()) {
error = Some($crate::ErrorKind::from(e)); error = Some($crate::ErrorKind::from(e));
}; };
} else { } else {
@ -165,7 +165,7 @@ macro_rules! execute {
} }
#[cfg(unix)] #[cfg(unix)]
{ {
if let Err(e) = write_cout!($write, $command.get_ansi_code()) { if let Err(e) = write_cout!($write, $command.ansi_code()) {
error = Some($crate::ErrorKind::from(e)); error = Some($crate::ErrorKind::from(e));
} }
} }
@ -185,7 +185,7 @@ macro_rules! impl_display {
$(impl ::std::fmt::Display for $t { $(impl ::std::fmt::Display for $t {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> {
use $crate::Command; use $crate::Command;
write!(f, "{}", self.get_ansi_code()) write!(f, "{}", self.ansi_code())
} }
})* })*
} }

View File

@ -43,7 +43,7 @@ pub fn set_terminal_attr(termios: &Termios) -> Result<()> {
wrap_with_result(unsafe { tcsetattr(0, 0, termios) }) wrap_with_result(unsafe { tcsetattr(0, 0, termios) })
} }
pub fn into_raw_mode() -> Result<()> { pub fn enable_raw_mode() -> Result<()> {
let mut ios = get_terminal_attr()?; let mut ios = get_terminal_attr()?;
let prev_ios = ios; let prev_ios = ios;

View File

@ -1,6 +1,8 @@
use std::io::Result;
use crossterm_winapi::{Console, ScreenBuffer}; use crossterm_winapi::{Console, ScreenBuffer};
fn set_background_color() -> std::io::Result<()> { fn set_background_color() -> Result<()> {
// background value // background value
const BLUE_BACKGROUND: u16 = 0x0010; const BLUE_BACKGROUND: u16 = 0x0010;
@ -16,12 +18,12 @@ fn set_background_color() -> std::io::Result<()> {
let new_color = fg_color | BLUE_BACKGROUND; let new_color = fg_color | BLUE_BACKGROUND;
// set the console text attribute to the new color value. // set the console text attribute to the new color value.
Console::from(**screen_buffer.get_handle()).set_text_attribute(new_color)?; Console::from(**screen_buffer.handle()).set_text_attribute(new_color)?;
Ok(()) Ok(())
} }
fn set_foreground_color() -> std::io::Result<()> { fn set_foreground_color() -> Result<()> {
// background value // background value
const BLUE_FOREGROUND: u16 = 0x0001; const BLUE_FOREGROUND: u16 = 0x0001;
@ -41,12 +43,12 @@ fn set_foreground_color() -> std::io::Result<()> {
} }
// set the console text attribute to the new color value. // set the console text attribute to the new color value.
Console::from(**screen_buffer.get_handle()).set_text_attribute(color)?; Console::from(**screen_buffer.handle()).set_text_attribute(color)?;
Ok(()) Ok(())
} }
fn main() { fn main() -> Result<()> {
set_background_color().unwrap(); set_background_color()?;
set_foreground_color().unwrap(); set_foreground_color()
} }

View File

@ -1,17 +1,17 @@
use std::io::Result;
use crossterm_winapi::ConsoleMode; use crossterm_winapi::ConsoleMode;
fn change_console_mode() { fn change_console_mode() -> Result<()> {
let console_mode = ConsoleMode::new().unwrap(); let console_mode = ConsoleMode::new()?;
// get the current console mode: // get the current console mode:
let _mode: u32 = console_mode.mode().unwrap(); let _mode: u32 = console_mode.mode()?;
// set the console mode (not sure if this is an actual value xp) // set the console mode (not sure if this is an actual value xp)
console_mode console_mode.set_mode(10)
.set_mode(10)
.expect("Unable to set console mode");
} }
fn main() { fn main() -> Result<()> {
change_console_mode(); change_console_mode()
} }

View File

@ -1,12 +1,14 @@
use std::io::Result;
use crossterm_winapi::{Handle, HandleType}; use crossterm_winapi::{Handle, HandleType};
#[allow(unused_variables)] #[allow(unused_variables)]
fn main() { fn main() -> Result<()> {
// see the description of the types to see what they do. // see the description of the types to see what they do.
let out_put_handle = Handle::new(HandleType::OutputHandle).unwrap(); let out_put_handle = Handle::new(HandleType::OutputHandle)?;
let out_put_handle = Handle::new(HandleType::InputHandle).unwrap(); let out_put_handle = Handle::new(HandleType::InputHandle)?;
let curr_out_put_handle = Handle::new(HandleType::CurrentOutputHandle).unwrap(); let curr_out_put_handle = Handle::new(HandleType::CurrentOutputHandle)?;
let curr_out_put_handle = Handle::new(HandleType::CurrentInputHandle).unwrap(); let curr_out_put_handle = Handle::new(HandleType::CurrentInputHandle)?;
// now you have this handle you might want to get the WinApi `HANDLE` it is wrapping. // now you have this handle you might want to get the WinApi `HANDLE` it is wrapping.
// you can do this by defencing. // you can do this by defencing.
@ -15,4 +17,6 @@ fn main() {
// you can also pass you own `HANDLE` to create an instance of `Handle` // you can also pass you own `HANDLE` to create an instance of `Handle`
let handle = Handle::from(handle); /* winapi::um::winnt::HANDLE */ let handle = Handle::from(handle); /* winapi::um::winnt::HANDLE */
Ok(())
} }

View File

@ -1,26 +1,31 @@
#![allow(dead_code)]
use std::io::Result;
use crossterm_winapi::ScreenBuffer; use crossterm_winapi::ScreenBuffer;
fn print_screen_buffer_information() { fn print_screen_buffer_information() -> Result<()> {
let screen_buffer = ScreenBuffer::current().unwrap(); let screen_buffer = ScreenBuffer::current()?;
// get console screen buffer information // get console screen buffer information
let csbi = screen_buffer.info().unwrap(); let csbi = screen_buffer.info()?;
println!("cursor post: {:?}", csbi.cursor_pos()); println!("cursor post: {:?}", csbi.cursor_pos());
println!("attributes: {:?}", csbi.attributes()); println!("attributes: {:?}", csbi.attributes());
println!("terminal window dimentions {:?}", csbi.terminal_window()); println!("terminal window dimentions {:?}", csbi.terminal_window());
println!("terminal size {:?}", csbi.terminal_size()); println!("terminal size {:?}", csbi.terminal_size());
Ok(())
} }
#[allow(dead_code)] fn multiple_screen_buffers() -> Result<()> {
fn multiple_screen_buffers() {
// create new screen buffer // create new screen buffer
let screen_buffer = ScreenBuffer::create(); let screen_buffer = ScreenBuffer::create();
// which to this screen buffer // which to this screen buffer
screen_buffer.show().expect("Unable to show screen buffer"); screen_buffer.show()
} }
fn main() { fn main() -> Result<()> {
print_screen_buffer_information(); print_screen_buffer_information()
} }

View File

@ -82,16 +82,15 @@ mod tests {
// TODO - Test is ignored, because it's failing on Travis CI // TODO - Test is ignored, because it's failing on Travis CI
#[test] #[test]
#[ignore] #[ignore]
fn set_get_mode() { fn test_set_get_mode() {
let mode = ConsoleMode::new().unwrap(); let mode = ConsoleMode::new().unwrap();
let original_mode = mode.mode().unwrap(); let original_mode = mode.mode().unwrap();
assert!(mode.set_mode(0x0004).is_ok()); mode.set_mode(0x0004).unwrap();
let console_mode = mode.mode().unwrap(); let console_mode = mode.mode().unwrap();
assert_eq!(console_mode & 0x0004, mode.mode().unwrap());
assert_ne!(console_mode & 0x0004, 0); mode.set_mode(original_mode).unwrap();
assert!(mode.set_mode(original_mode).is_ok());
} }
} }

View File

@ -179,7 +179,7 @@ mod tests {
use super::{Handle, HandleType}; use super::{Handle, HandleType};
#[test] #[test]
fn get_handle() { fn test_get_handle() {
assert!(Handle::new(HandleType::OutputHandle).is_ok()); assert!(Handle::new(HandleType::OutputHandle).is_ok());
assert!(Handle::new(HandleType::InputHandle).is_ok()); assert!(Handle::new(HandleType::InputHandle).is_ok());
assert!(Handle::new(HandleType::CurrentOutputHandle).is_ok()); assert!(Handle::new(HandleType::CurrentOutputHandle).is_ok());

View File

@ -102,7 +102,7 @@ impl ScreenBuffer {
} }
/// Get the underlining raw `HANDLE` used by this type to execute whit. /// Get the underlining raw `HANDLE` used by this type to execute whit.
pub fn get_handle(&self) -> &Handle { pub fn handle(&self) -> &Handle {
return &self.handle; return &self.handle;
} }
} }
@ -126,7 +126,7 @@ mod tests {
use super::ScreenBuffer; use super::ScreenBuffer;
#[test] #[test]
fn screen_buffer_info() { fn test_screen_buffer_info() {
let buffer = ScreenBuffer::current().unwrap(); let buffer = ScreenBuffer::current().unwrap();
let info = buffer.info().unwrap(); let info = buffer.info().unwrap();
info.terminal_size(); info.terminal_size();

View File

@ -62,7 +62,7 @@ fn move_left() -> Result<()> {
} }
/// Save and reset cursor position | demonstration.. /// Save and reset cursor position | demonstration..
fn save_and_reset_position() -> Result<()> { fn save_and_restore_position() -> Result<()> {
let cursor = cursor(); let cursor = cursor();
// Goto X: 5 Y: 5 // Goto X: 5 Y: 5
@ -74,7 +74,7 @@ fn save_and_reset_position() -> Result<()> {
// Print at X: 5 Y: 20. // Print at X: 5 Y: 20.
println!("Yea!"); println!("Yea!");
// Reset back to X: 5 Y: 5. // Reset back to X: 5 Y: 5.
cursor.reset_position()?; cursor.restore_position()?;
// Print Back at X: 5 Y: 5. // Print Back at X: 5 Y: 5.
println!("Back"); println!("Back");

View File

@ -399,7 +399,7 @@ fn print_text_with_attributes() {
/// Print all supported RGB colors, not supported for Windows systems < 10 | demonstration. /// Print all supported RGB colors, not supported for Windows systems < 10 | demonstration.
fn print_supported_colors() { fn print_supported_colors() {
let count = color().get_available_color_count(); let count = color().available_color_count();
for i in 0..count { for i in 0..count {
println!("Test {}", Colored::Bg(Color::AnsiValue(i as u8))); println!("Test {}", Colored::Bg(Color::AnsiValue(i as u8)));