[go: up one dir, main page]

Struct Buffer

Source
pub struct Buffer {
    pub area: Rect,
    pub content: Vec<Cell>,
}
Expand description

A buffer that maps to the desired content of the terminal after the draw call

No widget in the library interacts directly with the terminal. Instead each of them is required to draw their state to an intermediate buffer. It is basically a grid where each cell contains a grapheme, a foreground color and a background color. This grid will then be used to output the appropriate escape sequences and characters to draw the UI as the user has defined it.

§Examples:

use ratatui_core::buffer::{Buffer, Cell};
use ratatui_core::layout::{Position, Rect};
use ratatui_core::style::{Color, Style};

let mut buf = Buffer::empty(Rect {
    x: 0,
    y: 0,
    width: 10,
    height: 5,
});

// indexing using Position
buf[Position { x: 0, y: 0 }].set_symbol("A");
assert_eq!(buf[Position { x: 0, y: 0 }].symbol(), "A");

// indexing using (x, y) tuple (which is converted to Position)
buf[(0, 1)].set_symbol("B");
assert_eq!(buf[(0, 1)].symbol(), "x");

// getting an Option instead of panicking if the position is outside the buffer
let cell = buf.cell_mut(Position { x: 0, y: 2 })?;
cell.set_symbol("C");

let cell = buf.cell(Position { x: 0, y: 2 })?;
assert_eq!(cell.symbol(), "C");

buf.set_string(
    3,
    0,
    "string",
    Style::default().fg(Color::Red).bg(Color::White),
);
let cell = &buf[(5, 0)]; // cannot move out of buf, so we borrow it
assert_eq!(cell.symbol(), "r");
assert_eq!(cell.fg, Color::Red);
assert_eq!(cell.bg, Color::White);

Fields§

§area: Rect

The area represented by this buffer

§content: Vec<Cell>

The content of the buffer. The length of this Vec should always be equal to area.width * area.height

Implementations§

Source§

impl Buffer

Source

pub fn empty(area: Rect) -> Buffer

Returns a Buffer with all cells set to the default one

Source

pub fn filled(area: Rect, cell: Cell) -> Buffer

Returns a Buffer with all cells initialized with the attributes of the given Cell

Source

pub fn with_lines<'a, Iter>(lines: Iter) -> Buffer
where Iter: IntoIterator, <Iter as IntoIterator>::Item: Into<Line<'a>>,

Returns a Buffer containing the given lines

Source

pub fn content(&self) -> &[Cell]

Returns the content of the buffer as a slice

Source

pub const fn area(&self) -> &Rect

Returns the area covered by this buffer

Source

pub fn get(&self, x: u16, y: u16) -> &Cell

👎Deprecated: use Buffer[(x, y)] instead. To avoid panicking, use Buffer::cell((x, y)). Both methods take impl Into<Position>.

Returns a reference to the Cell at the given coordinates

Callers should use Buffer[] or Buffer::cell instead of this method.

Note: idiomatically methods named get usually return Option<&T>, but this method panics instead. This is kept for backwards compatibility. See cell for a safe alternative.

§Panics

Panics if the index is out of bounds.

Source

pub fn get_mut(&mut self, x: u16, y: u16) -> &mut Cell

👎Deprecated: use Buffer[(x, y)] instead. To avoid panicking, use Buffer::cell_mut((x, y)). Both methods take impl Into<Position>.

Returns a mutable reference to the Cell at the given coordinates.

Callers should use Buffer[] or Buffer::cell_mut instead of this method.

Note: idiomatically methods named get_mut usually return Option<&mut T>, but this method panics instead. This is kept for backwards compatibility. See cell_mut for a safe alternative.

§Panics

Panics if the position is outside the Buffer’s area.

Source

pub fn cell<P>(&self, position: P) -> Option<&Cell>
where P: Into<Position>,

Returns a reference to the Cell at the given position or None if the position is outside the Buffer’s area.

This method accepts any value that can be converted to Position (e.g. (x, y) or Position::new(x, y)).

For a method that panics when the position is outside the buffer instead of returning None, use Buffer[].

§Examples
use ratatui_core::buffer::{Buffer, Cell};
use ratatui_core::layout::{Position, Rect};

let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 10));

assert_eq!(buffer.cell(Position::new(0, 0)), Some(&Cell::default()));
assert_eq!(buffer.cell(Position::new(10, 10)), None);
assert_eq!(buffer.cell((0, 0)), Some(&Cell::default()));
assert_eq!(buffer.cell((10, 10)), None);
Source

pub fn cell_mut<P>(&mut self, position: P) -> Option<&mut Cell>
where P: Into<Position>,

Returns a mutable reference to the Cell at the given position or None if the position is outside the Buffer’s area.

This method accepts any value that can be converted to Position (e.g. (x, y) or Position::new(x, y)).

For a method that panics when the position is outside the buffer instead of returning None, use Buffer[].

§Examples
use ratatui_core::buffer::{Buffer, Cell};
use ratatui_core::layout::{Position, Rect};
use ratatui_core::style::{Color, Style};
let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 10));

if let Some(cell) = buffer.cell_mut(Position::new(0, 0)) {
    cell.set_symbol("A");
}
if let Some(cell) = buffer.cell_mut((0, 0)) {
    cell.set_style(Style::default().fg(Color::Red));
}
Source

pub fn index_of(&self, x: u16, y: u16) -> usize

Returns the index in the Vec<Cell> for the given global (x, y) coordinates.

Global coordinates are offset by the Buffer’s area offset (x/y).

§Examples
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;

let buffer = Buffer::empty(Rect::new(200, 100, 10, 10));
// Global coordinates to the top corner of this buffer's area
assert_eq!(buffer.index_of(200, 100), 0);
§Panics

Panics when given an coordinate that is outside of this Buffer’s area.

use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;

let buffer = Buffer::empty(Rect::new(200, 100, 10, 10));
// Top coordinate is outside of the buffer in global coordinate space, as the Buffer's area
// starts at (200, 100).
buffer.index_of(0, 0); // Panics
Source

pub fn pos_of(&self, index: usize) -> (u16, u16)

Returns the (global) coordinates of a cell given its index

Global coordinates are offset by the Buffer’s area offset (x/y).

§Examples
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;

let rect = Rect::new(200, 100, 10, 10);
let buffer = Buffer::empty(rect);
assert_eq!(buffer.pos_of(0), (200, 100));
assert_eq!(buffer.pos_of(14), (204, 101));
§Panics

Panics when given an index that is outside the Buffer’s content.

use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;

let rect = Rect::new(0, 0, 10, 10); // 100 cells in total
let buffer = Buffer::empty(rect);
// Index 100 is the 101th cell, which lies outside of the area of this Buffer.
buffer.pos_of(100); // Panics
Source

pub fn set_string<T, S>(&mut self, x: u16, y: u16, string: T, style: S)
where T: AsRef<str>, S: Into<Style>,

Print a string, starting at the position (x, y)

Source

pub fn set_stringn<T, S>( &mut self, x: u16, y: u16, string: T, max_width: usize, style: S, ) -> (u16, u16)
where T: AsRef<str>, S: Into<Style>,

Print at most the first n characters of a string if enough space is available until the end of the line. Skips zero-width graphemes and control characters.

Use Buffer::set_string when the maximum amount of characters can be printed.

Source

pub fn set_line( &mut self, x: u16, y: u16, line: &Line<'_>, max_width: u16, ) -> (u16, u16)

Print a line, starting at the position (x, y)

Source

pub fn set_span( &mut self, x: u16, y: u16, span: &Span<'_>, max_width: u16, ) -> (u16, u16)

Print a span, starting at the position (x, y)

Source

pub fn set_style<S>(&mut self, area: Rect, style: S)
where S: Into<Style>,

Set the style of all cells in the given area.

style accepts any type that is convertible to Style (e.g. Style, Color, or your own type that implements Into<Style>).

Source

pub fn resize(&mut self, area: Rect)

Resize the buffer so that the mapped area matches the given area and that the buffer length is equal to area.width * area.height

Source

pub fn reset(&mut self)

Reset all cells in the buffer

Source

pub fn merge(&mut self, other: &Buffer)

Merge an other buffer into this one

Source

pub fn diff<'a>(&self, other: &'a Buffer) -> Vec<(u16, u16, &'a Cell)>

Builds a minimal sequence of coordinates and Cells necessary to update the UI from self to other.

We’re assuming that buffers are well-formed, that is no double-width cell is followed by a non-blank cell.

§Multi-width characters handling:
(Index:) `01`
Prev:    `コ`
Next:    `aa`
Updates: `0: a, 1: a'
(Index:) `01`
Prev:    `a `
Next:    `コ`
Updates: `0: コ` (double width symbol at index 0 - skip index 1)
(Index:) `012`
Prev:    `aaa`
Next:    `aコ`
Updates: `0: a, 1: コ` (double width symbol at index 1 - skip index 2)

Trait Implementations§

Source§

impl Clone for Buffer

Source§

fn clone(&self) -> Buffer

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Buffer

Source§

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

Writes a debug representation of the buffer to the given formatter.

The format is like a pretty printed struct, with the following fields:

  • area: displayed as Rect { x: 1, y: 2, width: 3, height: 4 }
  • content: displayed as a list of strings representing the content of the buffer
  • styles: displayed as a list of: { x: 1, y: 2, fg: Color::Red, bg: Color::Blue, modifier: Modifier::BOLD } only showing a value when there is a change in style.
Source§

impl Default for Buffer

Source§

fn default() -> Buffer

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Buffer

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<Buffer, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Hash for Buffer

Source§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<P> Index<P> for Buffer
where P: Into<Position>,

Source§

fn index(&self, position: P) -> &<Buffer as Index<P>>::Output

Returns a reference to the Cell at the given position.

This method accepts any value that can be converted to Position (e.g. (x, y) or Position::new(x, y)).

§Panics

May panic if the given position is outside the buffer’s area. For a method that returns None instead of panicking, use Buffer::cell.

§Examples
use ratatui_core::buffer::{Buffer, Cell};
use ratatui_core::layout::{Position, Rect};

let buf = Buffer::empty(Rect::new(0, 0, 10, 10));
let cell = &buf[(0, 0)];
let cell = &buf[Position::new(0, 0)];
Source§

type Output = Cell

The returned type after indexing.
Source§

impl<P> IndexMut<P> for Buffer
where P: Into<Position>,

Source§

fn index_mut(&mut self, position: P) -> &mut <Buffer as Index<P>>::Output

Returns a mutable reference to the Cell at the given position.

This method accepts any value that can be converted to Position (e.g. (x, y) or Position::new(x, y)).

§Panics

May panic if the given position is outside the buffer’s area. For a method that returns None instead of panicking, use Buffer::cell_mut.

§Examples
use ratatui_core::buffer::{Buffer, Cell};
use ratatui_core::layout::{Position, Rect};

let mut buf = Buffer::empty(Rect::new(0, 0, 10, 10));
buf[(0, 0)].set_symbol("A");
buf[Position::new(0, 0)].set_symbol("B");
Source§

impl PartialEq for Buffer

Source§

fn eq(&self, other: &Buffer) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Buffer

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Buffer

Source§

impl StructuralPartialEq for Buffer

Auto Trait Implementations§

§

impl Freeze for Buffer

§

impl RefUnwindSafe for Buffer

§

impl Send for Buffer

§

impl Sync for Buffer

§

impl Unpin for Buffer

§

impl UnwindSafe for Buffer

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
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<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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<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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,