Skip to main content

TerminaBackend

Struct TerminaBackend 

Source
pub struct TerminaBackend<T>
where T: Terminal,
{ /* private fields */ }
Available on crate feature termina only.
Expand description

A Backend implementation that renders through a termina::Terminal.

TerminaBackend writes typed Termina escape sequences for drawing, cursor control, clearing, and terminal-size queries.

This backend does not automatically enable raw mode or switch to the alternate screen. Use Termina’s terminal APIs and typed escape sequences to configure those application-level modes before drawing.

§Example

use ratatui::Terminal;
use ratatui::backend::TerminaBackend;
use ratatui::termina::{PlatformTerminal, Terminal as _};

let mut output = PlatformTerminal::new()?;
output.enter_raw_mode()?;

let backend = TerminaBackend::new(output);
let mut terminal = Terminal::new(backend)?;

terminal.draw(|frame| {
    // -- snip --
})?;

Implementations§

Source§

impl<T> TerminaBackend<T>
where T: Terminal,

Source

pub const fn new(terminal: T) -> TerminaBackend<T>

Creates a backend that writes to the given Termina terminal.

Source

pub const fn terminal(&self) -> &T

Available on crate features unstable-backend-writer only.

Returns the wrapped terminal.

§Stability

This API is marked as unstable and is only available when the unstable-backend-writer crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time. The tracking issue is: https://github.com/ratatui/ratatui/pull/991.

Source

pub const fn terminal_mut(&mut self) -> &mut T

Available on crate features unstable-backend-writer only.

Returns the wrapped terminal as a mutable reference.

Direct writes can desynchronize Ratatui’s diffing buffers from the visible terminal. Clear the terminal or force a full redraw before relying on Ratatui’s next diff.

§Stability

This API is marked as unstable and is only available when the unstable-backend-writer crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time. The tracking issue is: https://github.com/ratatui/ratatui/pull/991.

Trait Implementations§

Source§

impl<T> Backend for TerminaBackend<T>
where T: Terminal,

Source§

type Error = Error

Error type associated with this Backend.
Source§

fn draw<'a, I>(&mut self, content: I) -> Result<(), Error>
where I: Iterator<Item = (u16, u16, &'a Cell)>,

Draw the given content to the terminal screen. Read more
Source§

fn hide_cursor(&mut self) -> Result<(), Error>

Hide the cursor on the terminal screen. Read more
Source§

fn show_cursor(&mut self) -> Result<(), Error>

Show the cursor on the terminal screen. Read more
Source§

fn get_cursor_position(&mut self) -> Result<Position, Error>

Get the current cursor position on the terminal screen. Read more
Source§

fn set_cursor_position<P>(&mut self, position: P) -> Result<(), Error>
where P: Into<Position>,

Set the cursor position on the terminal screen to the given x and y coordinates. Read more
Source§

fn clear(&mut self) -> Result<(), Error>

Clears all character cells in the terminal’s visible display area. Read more
Source§

fn clear_region(&mut self, clear_type: ClearType) -> Result<(), Error>

Clears a specific region of the terminal’s visible display area, as defined by ClearType. Read more
Source§

fn append_lines(&mut self, n: u16) -> Result<(), Error>

Insert n line breaks to the terminal screen. Read more
Source§

fn size(&self) -> Result<Size, Error>

Get the size of the terminal screen in columns/rows as a Size. Read more
Source§

fn window_size(&mut self) -> Result<WindowSize, Error>

Get the size of the terminal screen in columns/rows and pixels as a WindowSize. Read more
Source§

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

Flush any backend-buffered output to the terminal screen. Read more
Source§

fn scroll_region_up( &mut self, region: Range<u16>, amount: u16, ) -> Result<(), Error>

Available on crate feature scrolling-regions only.
Scroll a region of the screen upwards, where a region is specified by a (half-open) range of rows. Read more
Source§

fn scroll_region_down( &mut self, region: Range<u16>, amount: u16, ) -> Result<(), Error>

Available on crate feature scrolling-regions only.
Scroll a region of the screen downwards, where a region is specified by a (half-open) range of rows. Read more
Source§

fn get_cursor(&mut self) -> Result<(u16, u16), Self::Error>

👎Deprecated:

use get_cursor_position() instead which returns Result<Position>

Get the current cursor position on the terminal screen. Read more
Source§

fn set_cursor(&mut self, x: u16, y: u16) -> Result<(), Self::Error>

👎Deprecated:

use set_cursor_position((x, y)) instead which takes impl Into<Position>

Set the cursor position on the terminal screen to the given x and y coordinates. Read more
Source§

impl<T> Debug for TerminaBackend<T>
where T: Terminal + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<T> Write for TerminaBackend<T>
where T: Terminal,

Source§

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

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

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

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<T> Freeze for TerminaBackend<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for TerminaBackend<T>
where T: RefUnwindSafe,

§

impl<T> Send for TerminaBackend<T>
where T: Send,

§

impl<T> Sync for TerminaBackend<T>
where T: Sync,

§

impl<T> Unpin for TerminaBackend<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for TerminaBackend<T>
where T: UnsafeUnpin,

§

impl<T> UnwindSafe for TerminaBackend<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
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, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
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<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<W> DetectColors for W
where W: Write,

Source§

fn available_colors(&mut self) -> Result<u16, Error>

How many ANSI colors are supported (from 8 to 256)? Read more
Source§

impl<W> DetectCursorPos for W
where W: Write,

Source§

fn cursor_pos(&mut self) -> Result<(u16, u16), Error>

Get the (1,1)-based cursor position from the terminal.
Source§

impl<T> ExecutableCommand for T
where T: Write + ?Sized,

Source§

fn execute(&mut self, command: impl Command) -> Result<&mut T, Error>

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;
use crossterm::{ExecutableCommand, style::Print};

fn main() -> io::Result<()> {
     // will be executed directly
      io::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> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
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<W> IntoAlternateScreen for W
where W: Write,

Source§

fn into_alternate_screen(self) -> Result<AlternateScreen<Self>, Error>

Switch the terminal controlled by this writer to use the alternate screen. The terminal will be restored to the main screen when the AlternateScreen returned by this function is dropped.
Source§

impl<T, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> QueueableCommand for T
where T: Write + ?Sized,

Source§

fn queue(&mut self, command: impl Command) -> Result<&mut T, Error>

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::{self, Write};
use crossterm::{QueueableCommand, style::Print};

 fn main() -> io::Result<()> {
    let mut stdout = io::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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<W> SynchronizedUpdate for W
where W: Write + ?Sized,

Source§

fn sync_update<T>( &mut self, operations: impl FnOnce(&mut W) -> T, ) -> Result<T, Error>

Performs a set of actions within a synchronous update.

Updates will be suspended in the terminal, the function will be executed against self, updates will be resumed, and a flush will be performed.

§Arguments
  • Function

    A function that performs the operations that must execute in a synchronized update.

§Examples
use std::io;
use crossterm::{ExecutableCommand, SynchronizedUpdate, style::Print};

fn main() -> io::Result<()> {
    let mut stdout = io::stdout();

    stdout.sync_update(|stdout| {
        stdout.execute(Print("foo 1\n".to_string()))?;
        stdout.execute(Print("foo 2".to_string()))?;
        // The effects of the print command will not be present in the terminal
        // buffer, but not visible in the terminal.
        std::io::Result::Ok(())
    })?;

    // The effects of the commands will be visible.

    Ok(())

    // ==== Output ====
    // foo 1
    // foo 2
}
§Notes

This command is performed only using ANSI codes, and will do nothing on terminals that do not support ANSI codes, or this specific extension.

When rendering the screen of the terminal, the Emulator usually iterates through each visible grid cell and renders its current state. With applications updating the screen a at higher frequency this can cause tearing.

This mode attempts to mitigate that.

When the synchronization mode is enabled following render calls will keep rendering the last rendered state. The terminal Emulator keeps processing incoming text and sequences. When the synchronized update mode is disabled again the renderer may fetch the latest screen buffer state again, effectively avoiding the tearing effect by unintentionally rendering in the middle a of an application screen update.

Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
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.
Source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.