diff --git a/examples/cursor_at.rs b/examples/cursor_at.rs new file mode 100644 index 00000000..9a1bb3d5 --- /dev/null +++ b/examples/cursor_at.rs @@ -0,0 +1,30 @@ +extern crate console; + +use std::io; +use std::thread; +use std::time::Duration; + +use console::{style, Term}; + +fn write_chars() -> io::Result<()> { + let term = Term::stdout(); + let (heigth, width) = term.size(); + for x in 0..width { + for y in 0..heigth { + term.move_cursor_to(x as usize, y as usize)?; + let text = if (x + y) % 2 == 0 { + format!("{}", style(x % 10).black().on_red()) + } else { + format!("{}", style(x % 10).red().on_black()) + }; + + term.write_str(&text)?; + thread::sleep(Duration::from_micros(600)); + } + } + Ok(()) +} + +fn main() { + write_chars().unwrap(); +} diff --git a/src/term.rs b/src/term.rs index 07a4dfdd..7e42ba9e 100644 --- a/src/term.rs +++ b/src/term.rs @@ -192,6 +192,11 @@ impl Term { terminal_size() } + /// Moves the cursor to `x` and `y` + pub fn move_cursor_to(&self, x: usize, y: usize) -> io::Result<()> { + move_cursor_to(self, x, y) + } + /// Moves the cursor up `n` lines pub fn move_cursor_up(&self, n: usize) -> io::Result<()> { move_cursor_up(self, n) diff --git a/src/unix_term.rs b/src/unix_term.rs index 1c5c36c2..b4a72f83 100644 --- a/src/unix_term.rs +++ b/src/unix_term.rs @@ -51,6 +51,10 @@ pub fn move_cursor_down(out: &Term, n: usize) -> io::Result<()> { } } +pub fn move_cursor_to(out: &Term, x: usize, y: usize) -> io::Result<()> { + out.write_str(&format!("\x1B[{};{}H", y + 1, x + 1)) +} + pub fn move_cursor_up(out: &Term, n: usize) -> io::Result<()> { if n > 0 { out.write_str(&format!("\x1b[{}A", n)) diff --git a/src/windows_term.rs b/src/windows_term.rs index a3fef97e..ad8582c2 100644 --- a/src/windows_term.rs +++ b/src/windows_term.rs @@ -46,14 +46,14 @@ pub fn terminal_size() -> Option<(u16, u16)> { } } -pub fn move_cursor_up(out: &Term, n: usize) -> io::Result<()> { +pub fn move_cursor_to(out: &Term, x: usize, y: usize) -> io::Result<()> { if let Some((hand, csbi)) = get_console_screen_buffer_info(as_handle(out)) { unsafe { SetConsoleCursorPosition( hand, COORD { - X: 0, - Y: csbi.dwCursorPosition.Y - n as i16, + X: x as i16, + Y: y as i16, }, ); } @@ -61,17 +61,16 @@ pub fn move_cursor_up(out: &Term, n: usize) -> io::Result<()> { Ok(()) } +pub fn move_cursor_up(out: &Term, n: usize) -> io::Result<()> { + if let Some((hand, csbi)) = get_console_screen_buffer_info(as_handle(out)) { + move_cursor_to(out, 0, csbi.dwCursorPosition.Y as usize - n); + } + Ok(()) +} + pub fn move_cursor_down(out: &Term, n: usize) -> io::Result<()> { if let Some((hand, csbi)) = get_console_screen_buffer_info(as_handle(out)) { - unsafe { - SetConsoleCursorPosition( - hand, - COORD { - X: 0, - Y: csbi.dwCursorPosition.Y + n as i16, - }, - ); - } + move_cursor_to(out, 0, csbi.dwCursorPosition.Y as usize + n); } Ok(()) }