Skip to content

Commit

Permalink
Add support to move cursor to (x, y) position
Browse files Browse the repository at this point in the history
  • Loading branch information
Roger committed Sep 29, 2018
1 parent f61c274 commit 42d4efa
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 12 deletions.
30 changes: 30 additions & 0 deletions 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();
}
5 changes: 5 additions & 0 deletions src/term.rs
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions src/unix_term.rs
Expand Up @@ -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))
Expand Down
23 changes: 11 additions & 12 deletions src/windows_term.rs
Expand Up @@ -46,32 +46,31 @@ 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,
},
);
}
}
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(())
}
Expand Down

0 comments on commit 42d4efa

Please sign in to comment.