Crate prettytty

Source
Expand description

§Pretty 🌸 Tty

[ Docs.rs | GitHub Pages | Rust Crate | Repository ]

This crate provides lightweight and cross-platform terminal access. Its only dependency is the low-level crate enabling system calls, i.e., libc on Unix and windows-sys on Windows.

Using its connection-oriented interface is easy:

More generally, Input implements Read, BufRead, and Scan, with the latter turning bytes into UTF-8 text, control code, and control sequence tokens. Meanwhile, Output implements Write as well as the auto-flushing print(), println(), and exec() methods.

The cmd module provides a library of common Command and Query implementations. It includes, for example, commands to set the window title, erase (parts of) the screen, to move the cursor, and to style text.

To facilitate orderly shutdown, read operations time out in configurable increments of 0.1s. That suffices for simple polling but is slow when there is no input. If you need faster timeouts or integration with I/O notifications, use a dedicated polling thread with either an std::sync::mpsc queue or Unix domain socket.

Since terminal connections reconfigure the terminal, an application should go out of its way to always run Connection’s drop handler.

§Example

Prettytty’s connection-oriented interface makes interacting with the terminal a breeze:

// Open a terminal connection.
let tty = Connection::with_options(Options::default())?;

let pos = {
    let (mut input, mut output) = tty.io();

    // Move cursor, issue query for position.
    output.exec(MoveToColumn::<17>)?;
    output.exec(RequestCursorPosition)?;

    // Read and parse response.
    let response = input.read_sequence(
        RequestCursorPosition.control())?;
    RequestCursorPosition.parse(response)?
};

assert_eq!(pos.1, 17);

§Windows

Prettytty uses platform-specific APIs for configuring the terminal, notably for setting the correct mode. By contrast, commands and queries are implemented with ANSI escape sequences. Windows started supporting control sequences for styling output with Windows 10 version 1511 only. It started supporting queries for the current color theme with Windows Terminal 1.22 only. Hence, we strongly recommend using prettytty with Windows Terminal 1.22 or later.

Modules§

  • A library of useful terminal commands.
  • Helper module with this crate’s error type.
  • Helper module with the options for connecting to terminals.
  • Helpers for parsing and displaying byte strings.

Macros§

  • Combine several commands into a single new command.
  • Combine several SGR commands into a single new SGR command.

Structs§

Enums§

  • Control codes that start or end ANSI escape sequences.
  • A text or control sequence token.

Traits§

  • A command for the terminal.
  • A command that receives a response.
  • A scanner for UTF-8 characters and control sequences.
  • A command using select-graphic-rendition ANSI escape sequences.