pub struct Terminal<W: Write> { /* private fields */ }
Expand description
A simple interface to perform operations on the terminal. It also allows terminal values to be queried.
§Examples
use terminal::{Clear, Action, Value, Retrieved, error};
pub fn main() -> error::Result<()> {
let terminal = terminal::stdout();
// perform an single action.
terminal.act(Action::ClearTerminal(Clear::All))?;
// batch multiple actions.
for i in 0..100 {
terminal.batch(Action::MoveCursorTo(0, i))?;
}
// execute batch.
terminal.flush_batch();
// get an terminal value.
if let Retrieved::TerminalSize(x, y) = terminal.get(Value::TerminalSize)? {
println!("x: {}, y: {}", x, y);
}
Ok(())
}
§Notes
Implementations§
Source§impl<W: Write> Terminal<W>
impl<W: Write> Terminal<W>
Sourcepub fn custom(buffer: W) -> Terminal<W> ⓘ
pub fn custom(buffer: W) -> Terminal<W> ⓘ
Creates a custom buffered Terminal with the given buffer.
Examples found in repository?
5fn different_buffers() {
6 let _stdout = stdout();
7 let _stderr = stderr();
8 let _file = Terminal::custom(File::create("./test.txt").unwrap());
9}
10
11/// Gets values from the terminal.
12fn get_value() -> error::Result<()> {
13 let stdout = stdout();
14
15 if let Retrieved::CursorPosition(x, y) = stdout.get(Value::CursorPosition)? {
16 println!("X: {}, Y: {}", x, y);
17 }
18
19 if let Retrieved::TerminalSize(column, row) = stdout.get(Value::TerminalSize)? {
20 println!("columns: {}, rows: {}", column, row);
21 }
22
23 // see '/examples/event.rs'
24 if let Retrieved::Event(event) = stdout.get(Value::Event(None))? {
25 println!("Event: {:?}\r", event);
26 }
27
28 Ok(())
29}
30
31fn perform_action() -> error::Result<()> {
32 let stdout = stdout();
33 stdout.act(Action::MoveCursorTo(10, 10))
34}
35
36/// Batches multiple actions before executing.
37fn batch_actions() -> error::Result<()> {
38 let terminal = stdout();
39 terminal.batch(Action::ClearTerminal(Clear::All))?;
40 terminal.batch(Action::MoveCursorTo(5, 5))?;
41
42 thread::sleep(Duration::from_millis(2000));
43 println!("@");
44
45 terminal.flush_batch()
46}
47
48/// Acquires lock once, and uses that lock to do actions.
49fn lock_terminal() -> error::Result<()> {
50 let terminal = Terminal::custom(File::create("./test.txt").unwrap());
51
52 let mut lock = terminal.lock_mut()?;
53
54 for i in 0..10000 {
55 println!("{}", i);
56
57 if i % 100 == 0 {
58 lock.act(Action::ClearTerminal(Clear::All))?;
59 lock.act(Action::MoveCursorTo(0, 0))?;
60 }
61 thread::sleep(Duration::from_millis(10));
62 }
63
64 Ok(())
65}
Sourcepub fn lock_mut(&self) -> Result<TerminalLock<'_, W>>
pub fn lock_mut(&self) -> Result<TerminalLock<'_, W>>
Locks this Terminal, returning a mutable lock guard. A deadlock is not possible, instead an error will be returned if a lock is already in use. Make sure this lock is only used at one place. The lock is released when the returned lock goes out of scope.
Examples found in repository?
More examples
49fn lock_terminal() -> error::Result<()> {
50 let terminal = Terminal::custom(File::create("./test.txt").unwrap());
51
52 let mut lock = terminal.lock_mut()?;
53
54 for i in 0..10000 {
55 println!("{}", i);
56
57 if i % 100 == 0 {
58 lock.act(Action::ClearTerminal(Clear::All))?;
59 lock.act(Action::MoveCursorTo(0, 0))?;
60 }
61 thread::sleep(Duration::from_millis(10));
62 }
63
64 Ok(())
65}
5fn main() {
6 let terminal = stdout();
7
8 let mut lock = terminal.lock_mut().unwrap();
9
10 lock.act(Action::EnterAlternateScreen).unwrap();
11 lock.act(Action::EnableRawMode).unwrap();
12 lock.act(Action::HideCursor).unwrap();
13
14 write_alt_screen_msg(&mut lock);
15
16 lock.flush_batch().unwrap();
17
18 loop {
19 if let Retrieved::Event(Some(Event::Key(key))) = lock.get(Value::Event(None)).unwrap() {
20 match key {
21 KeyEvent {
22 code: KeyCode::Char('q'),
23 ..
24 } => {
25 break;
26 }
27 KeyEvent {
28 code: KeyCode::Char('1'),
29 ..
30 } => {
31 lock.act(Action::LeaveAlternateScreen).unwrap();
32 }
33 KeyEvent {
34 code: KeyCode::Char('2'),
35 ..
36 } => {
37 lock.act(Action::EnterAlternateScreen).unwrap();
38 write_alt_screen_msg(&mut lock);
39 }
40 _ => {}
41 };
42 }
43 }
44
45 lock.act(Action::DisableRawMode).unwrap();
46 lock.act(Action::ShowCursor).unwrap();
47}
Sourcepub fn act(&self, action: Action) -> Result<()>
pub fn act(&self, action: Action) -> Result<()>
Performs an action on the terminal.
§Note
Acquires an lock for underlying mutability, this can be prevented with lock_mut.
Examples found in repository?
More examples
10fn block_read() -> error::Result<()> {
11 let terminal = stdout();
12
13 terminal.act(Action::EnableRawMode)?;
14
15 loop {
16 if let Retrieved::Event(event) = terminal.get(Value::Event(None))? {
17 match event {
18 Some(Event::Key(KeyEvent {
19 code: KeyCode::Esc, ..
20 })) => return Ok(()),
21 Some(event) => {
22 println!("{:?}\r", event);
23 }
24 _ => {}
25 }
26 }
27 }
28}
29
30/// Reads events withing a certain duration.
31fn with_duration_read() -> error::Result<()> {
32 let terminal = stdout();
33
34 terminal.act(Action::EnableRawMode)?;
35 terminal.act(Action::EnableMouseCapture)?;
36
37 loop {
38 if let Retrieved::Event(event) =
39 terminal.get(Value::Event(Some(Duration::from_millis(500))))?
40 {
41 match event {
42 Some(Event::Key(KeyEvent {
43 code: KeyCode::Esc, ..
44 })) => return Ok(()),
45 Some(event) => {
46 println!("{:?}\r", event);
47 }
48 None => println!("...\r"),
49 }
50 }
51 }
52}
4pub fn main() -> error::Result<()> {
5 let mut terminal = terminal::stdout();
6
7 // perform an single action.
8 terminal.act(Action::ClearTerminal(Clear::All))?;
9
10 // batch multiple actions.
11 for i in 0..20 {
12 terminal.batch(Action::MoveCursorTo(0, i))?;
13 terminal.write(format!("{}", i).as_bytes());
14 }
15
16 // execute batch.
17 terminal.flush_batch();
18
19 // get an terminal value.
20 if let Retrieved::TerminalSize(x, y) = terminal.get(Value::TerminalSize)? {
21 println!("\nx: {}, y: {}", x, y);
22 }
23
24 Ok(())
25}
Sourcepub fn batch(&self, action: Action) -> Result<()>
pub fn batch(&self, action: Action) -> Result<()>
Batches an action for later execution. You can flush/execute the batched actions with batch.
§Note
Acquires an lock for underlying mutability, this can be prevented with lock_mut.
Examples found in repository?
More examples
4pub fn main() -> error::Result<()> {
5 let mut terminal = terminal::stdout();
6
7 // perform an single action.
8 terminal.act(Action::ClearTerminal(Clear::All))?;
9
10 // batch multiple actions.
11 for i in 0..20 {
12 terminal.batch(Action::MoveCursorTo(0, i))?;
13 terminal.write(format!("{}", i).as_bytes());
14 }
15
16 // execute batch.
17 terminal.flush_batch();
18
19 // get an terminal value.
20 if let Retrieved::TerminalSize(x, y) = terminal.get(Value::TerminalSize)? {
21 println!("\nx: {}, y: {}", x, y);
22 }
23
24 Ok(())
25}
Sourcepub fn flush_batch(&self) -> Result<()>
pub fn flush_batch(&self) -> Result<()>
Flushes the batched actions, this executes the actions in the order that they were batched. You can batch an action with batch.
§Note
Acquires an lock for underlying mutability, this can be prevented with lock_mut.
Examples found in repository?
More examples
4pub fn main() -> error::Result<()> {
5 let mut terminal = terminal::stdout();
6
7 // perform an single action.
8 terminal.act(Action::ClearTerminal(Clear::All))?;
9
10 // batch multiple actions.
11 for i in 0..20 {
12 terminal.batch(Action::MoveCursorTo(0, i))?;
13 terminal.write(format!("{}", i).as_bytes());
14 }
15
16 // execute batch.
17 terminal.flush_batch();
18
19 // get an terminal value.
20 if let Retrieved::TerminalSize(x, y) = terminal.get(Value::TerminalSize)? {
21 println!("\nx: {}, y: {}", x, y);
22 }
23
24 Ok(())
25}
Sourcepub fn get(&self, value: Value) -> Result<Retrieved>
pub fn get(&self, value: Value) -> Result<Retrieved>
Gets an value from the terminal.
Examples found in repository?
10fn block_read() -> error::Result<()> {
11 let terminal = stdout();
12
13 terminal.act(Action::EnableRawMode)?;
14
15 loop {
16 if let Retrieved::Event(event) = terminal.get(Value::Event(None))? {
17 match event {
18 Some(Event::Key(KeyEvent {
19 code: KeyCode::Esc, ..
20 })) => return Ok(()),
21 Some(event) => {
22 println!("{:?}\r", event);
23 }
24 _ => {}
25 }
26 }
27 }
28}
29
30/// Reads events withing a certain duration.
31fn with_duration_read() -> error::Result<()> {
32 let terminal = stdout();
33
34 terminal.act(Action::EnableRawMode)?;
35 terminal.act(Action::EnableMouseCapture)?;
36
37 loop {
38 if let Retrieved::Event(event) =
39 terminal.get(Value::Event(Some(Duration::from_millis(500))))?
40 {
41 match event {
42 Some(Event::Key(KeyEvent {
43 code: KeyCode::Esc, ..
44 })) => return Ok(()),
45 Some(event) => {
46 println!("{:?}\r", event);
47 }
48 None => println!("...\r"),
49 }
50 }
51 }
52}
More examples
12fn get_value() -> error::Result<()> {
13 let stdout = stdout();
14
15 if let Retrieved::CursorPosition(x, y) = stdout.get(Value::CursorPosition)? {
16 println!("X: {}, Y: {}", x, y);
17 }
18
19 if let Retrieved::TerminalSize(column, row) = stdout.get(Value::TerminalSize)? {
20 println!("columns: {}, rows: {}", column, row);
21 }
22
23 // see '/examples/event.rs'
24 if let Retrieved::Event(event) = stdout.get(Value::Event(None))? {
25 println!("Event: {:?}\r", event);
26 }
27
28 Ok(())
29}
4pub fn main() -> error::Result<()> {
5 let mut terminal = terminal::stdout();
6
7 // perform an single action.
8 terminal.act(Action::ClearTerminal(Clear::All))?;
9
10 // batch multiple actions.
11 for i in 0..20 {
12 terminal.batch(Action::MoveCursorTo(0, i))?;
13 terminal.write(format!("{}", i).as_bytes());
14 }
15
16 // execute batch.
17 terminal.flush_batch();
18
19 // get an terminal value.
20 if let Retrieved::TerminalSize(x, y) = terminal.get(Value::TerminalSize)? {
21 println!("\nx: {}, y: {}", x, y);
22 }
23
24 Ok(())
25}
Trait Implementations§
Source§impl<'a, W: Write> Write for Terminal<W>
impl<'a, W: Write> Write for Terminal<W>
Source§fn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
Source§fn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
Source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
)1.0.0 · Source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
Source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored
)Auto Trait Implementations§
impl<W> !Freeze for Terminal<W>
impl<W> RefUnwindSafe for Terminal<W>
impl<W> Send for Terminal<W>where
W: Send,
impl<W> Sync for Terminal<W>
impl<W> Unpin for Terminal<W>where
W: Unpin,
impl<W> UnwindSafe for Terminal<W>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T, A> ExecutableCommand<A> for T
impl<T, A> ExecutableCommand<A> for T
Source§fn execute(
&mut self,
command: impl Command<AnsiType = A>,
) -> Result<&mut T, ErrorKind>
fn execute( &mut self, command: impl Command<AnsiType = A>, ) -> Result<&mut T, ErrorKind>
Executes the given command directly.
The given command its ANSI escape code will be written and flushed onto Self
.
§Arguments
-
The command that you want to execute directly.
§Example
use std::io::{Write, stdout};
use crossterm::{Result, ExecutableCommand, style::Print};
fn main() -> Result<()> {
// will be executed directly
stdout()
.execute(Print("sum:\n".to_string()))?
.execute(Print(format!("1 + 1= {} ", 1 + 1)))?;
Ok(())
// ==== Output ====
// sum:
// 1 + 1 = 2
}
Have a look over at the Command API for more details.
§Notes
- In the case of UNIX and Windows 10, ANSI codes are written to the given ‘writer’.
- In case of Windows versions lower than 10, a direct WinApi call will be made.
The reason for this is that Windows versions lower than 10 do not support ANSI codes,
and can therefore not be written to the given
writer
. Therefore, there is no difference between execute and queue for those old Windows versions.
Source§impl<T, A> QueueableCommand<A> for T
impl<T, A> QueueableCommand<A> for T
Source§fn queue(
&mut self,
command: impl Command<AnsiType = A>,
) -> Result<&mut T, ErrorKind>
fn queue( &mut self, command: impl Command<AnsiType = A>, ) -> Result<&mut T, ErrorKind>
Queues the given command for further execution.
Queued commands will be executed in the following cases:
- When
flush
is called manually on the given type implementingio::Write
. - The terminal will
flush
automatically if the buffer is full. - Each line is flushed in case of
stdout
, because it is line buffered.
§Arguments
-
The command that you want to queue for later execution.
§Examples
use std::io::{Write, stdout};
use crossterm::{Result, QueueableCommand, style::Print};
fn main() -> Result<()> {
let mut stdout = stdout();
// `Print` will executed executed when `flush` is called.
stdout
.queue(Print("foo 1\n".to_string()))?
.queue(Print("foo 2".to_string()))?;
// some other code (no execution happening here) ...
// when calling `flush` on `stdout`, all commands will be written to the stdout and therefore executed.
stdout.flush()?;
Ok(())
// ==== Output ====
// foo 1
// foo 2
}
Have a look over at the Command API for more details.
§Notes
- In the case of UNIX and Windows 10, ANSI codes are written to the given ‘writer’.
- In case of Windows versions lower than 10, a direct WinApi call will be made.
The reason for this is that Windows versions lower than 10 do not support ANSI codes,
and can therefore not be written to the given
writer
. Therefore, there is no difference between execute and queue for those old Windows versions.