Struct Terminal

Source
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>

Source

pub fn custom(buffer: W) -> Terminal<W>

Creates a custom buffered Terminal with the given buffer.

Examples found in repository?
examples/basic.rs (line 8)
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}
Source

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?
examples/style.rs (line 74)
72fn main() {
73    let terminal = stdout();
74    let mut lock = terminal.lock_mut().unwrap();
75
76    rgb(&mut lock);
77
78    thread::sleep(Duration::from_millis(2000))
79}
More examples
Hide additional examples
examples/attribute.rs (line 39)
37pub fn main() {
38    let stdout = stdout();
39    let mut lock = stdout.lock_mut().unwrap();
40
41    display_attributes(&mut lock);
42
43    thread::sleep(Duration::from_millis(5000))
44}
examples/basic.rs (line 52)
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}
examples/alternate-raw.rs (line 8)
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}
Source

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?
examples/basic.rs (line 33)
31fn perform_action() -> error::Result<()> {
32    let stdout = stdout();
33    stdout.act(Action::MoveCursorTo(10, 10))
34}
More examples
Hide additional examples
examples/event.rs (line 13)
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}
examples/readme.rs (line 8)
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}
Source

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?
examples/basic.rs (line 39)
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}
More examples
Hide additional examples
examples/readme.rs (line 12)
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}
Source

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?
examples/basic.rs (line 45)
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}
More examples
Hide additional examples
examples/readme.rs (line 17)
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}
Source

pub fn get(&self, value: Value) -> Result<Retrieved>

Gets an value from the terminal.

Examples found in repository?
examples/event.rs (line 16)
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
Hide additional examples
examples/basic.rs (line 15)
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}
examples/readme.rs (line 20)
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>

Source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

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>
where W: Send + Sync,

§

impl<W> Unpin for Terminal<W>
where W: Unpin,

§

impl<W> UnwindSafe for Terminal<W>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T, A> ExecutableCommand<A> for T
where A: Display, T: Write,

Source§

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
  • Command

    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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, A> QueueableCommand<A> for T
where A: Display, T: Write,

Source§

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 implementing io::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
  • Command

    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.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.