pub struct Terminal<B>where
B: Backend,{ /* private fields */ }
Expand description
An interface to interact and draw Frame
s on the user’s terminal.
This is the main entry point for Ratatui. It is responsible for drawing and maintaining the state of the buffers, cursor and viewport.
The Terminal
is generic over a Backend
implementation which is used to interface with
the underlying terminal library. The Backend
trait is implemented for three popular Rust
terminal libraries: Crossterm, Termion and Termwiz. See the backend
module for more
information.
The Terminal
struct maintains two buffers: the current and the previous.
When the widgets are drawn, the changes are accumulated in the current buffer.
At the end of each draw pass, the two buffers are compared, and only the changes
between these buffers are written to the terminal, avoiding any redundant operations.
After flushing these changes, the buffers are swapped to prepare for the next draw cycle.
The terminal also has a viewport which is the area of the terminal that is currently visible to
the user. It can be either fullscreen, inline or fixed. See Viewport
for more information.
Applications should detect terminal resizes and call Terminal::draw
to redraw the
application with the new size. This will automatically resize the internal buffers to match the
new size for inline and fullscreen viewports. Fixed viewports are not resized automatically.
§Examples
use std::io::stdout;
use ratatui::{backend::CrosstermBackend, widgets::Paragraph, Terminal};
let backend = CrosstermBackend::new(stdout());
let mut terminal = Terminal::new(backend)?;
terminal.draw(|frame| {
let area = frame.area();
frame.render_widget(Paragraph::new("Hello World!"), area);
})?;
Implementations§
source§impl<B> Terminal<B>where
B: Backend,
impl<B> Terminal<B>where
B: Backend,
sourcepub fn with_options(backend: B, options: TerminalOptions) -> Result<Self>
pub fn with_options(backend: B, options: TerminalOptions) -> Result<Self>
Creates a new Terminal
with the given Backend
and TerminalOptions
.
§Example
use std::io::stdout;
use ratatui::{backend::CrosstermBackend, layout::Rect, Terminal, TerminalOptions, Viewport};
let backend = CrosstermBackend::new(stdout());
let viewport = Viewport::Fixed(Rect::new(0, 0, 10, 10));
let terminal = Terminal::with_options(backend, TerminalOptions { viewport })?;
sourcepub fn get_frame(&mut self) -> Frame<'_>
pub fn get_frame(&mut self) -> Frame<'_>
Get a Frame object which provides a consistent view into the terminal state for rendering.
sourcepub fn current_buffer_mut(&mut self) -> &mut Buffer
pub fn current_buffer_mut(&mut self) -> &mut Buffer
Gets the current buffer as a mutable reference.
sourcepub fn backend_mut(&mut self) -> &mut B
pub fn backend_mut(&mut self) -> &mut B
Gets the backend as a mutable reference
sourcepub fn flush(&mut self) -> Result<()>
pub fn flush(&mut self) -> Result<()>
Obtains a difference between the previous and the current buffer and passes it to the current backend for drawing.
sourcepub fn resize(&mut self, area: Rect) -> Result<()>
pub fn resize(&mut self, area: Rect) -> Result<()>
Updates the Terminal so that internal buffers match the requested area.
Requested area will be saved to remain consistent when rendering. This leads to a full clear of the screen.
sourcepub fn autoresize(&mut self) -> Result<()>
pub fn autoresize(&mut self) -> Result<()>
Queries the backend for size and resizes if it doesn’t match the previous size.
Examples found in repository?
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
fn run(
terminal: &mut Terminal<impl Backend>,
workers: Vec<Worker>,
mut downloads: Downloads,
rx: mpsc::Receiver<Event>,
) -> Result<()> {
let mut redraw = true;
loop {
if redraw {
terminal.draw(|frame| draw(frame, &downloads))?;
}
redraw = true;
match rx.recv()? {
Event::Input(event) => {
if event.code == event::KeyCode::Char('q') {
break;
}
}
Event::Resize => {
terminal.autoresize()?;
}
Event::Tick => {}
Event::DownloadUpdate(worker_id, _download_id, progress) => {
let download = downloads.in_progress.get_mut(&worker_id).unwrap();
download.progress = progress;
redraw = false;
}
Event::DownloadDone(worker_id, download_id) => {
let download = downloads.in_progress.remove(&worker_id).unwrap();
terminal.insert_before(1, |buf| {
Paragraph::new(Line::from(vec![
Span::from("Finished "),
Span::styled(
format!("download {download_id}"),
Style::default().add_modifier(Modifier::BOLD),
),
Span::from(format!(
" in {}ms",
download.started_at.elapsed().as_millis()
)),
]))
.render(buf.area, buf);
})?;
match downloads.next(worker_id) {
Some(d) => workers[worker_id].tx.send(d).unwrap(),
None => {
if downloads.in_progress.is_empty() {
terminal.insert_before(1, |buf| {
Paragraph::new("Done !").render(buf.area, buf);
})?;
break;
}
}
};
}
};
}
Ok(())
}
sourcepub fn draw<F>(&mut self, render_callback: F) -> Result<CompletedFrame<'_>>
pub fn draw<F>(&mut self, render_callback: F) -> Result<CompletedFrame<'_>>
Draws a single frame to the terminal.
Returns a CompletedFrame
if successful, otherwise a std::io::Error
.
If the render callback passed to this method can fail, use try_draw
instead.
Applications should call draw
or try_draw
in a loop to continuously render the
terminal. These methods are the main entry points for drawing to the terminal.
This method will:
- autoresize the terminal if necessary
- call the render callback, passing it a
Frame
reference to render to - flush the current internal state by copying the current buffer to the backend
- move the cursor to the last known position if it was set during the rendering closure
- return a
CompletedFrame
with the current buffer and the area of the terminal
The CompletedFrame
returned by this method can be useful for debugging or testing
purposes, but it is often not used in regular applicationss.
The render callback should fully render the entire frame when called, including areas that are unchanged from the previous frame. This is because each frame is compared to the previous frame to determine what has changed, and only the changes are written to the terminal. If the render callback does not fully render the frame, the terminal will not be in a consistent state.
§Examples
use ratatui::{layout::Position, widgets::Paragraph};
// with a closure
terminal.draw(|frame| {
let area = frame.area();
frame.render_widget(Paragraph::new("Hello World!"), area);
frame.set_cursor_position(Position { x: 0, y: 0 });
})?;
// or with a function
terminal.draw(render)?;
fn render(frame: &mut ratatui::Frame) {
frame.render_widget(Paragraph::new("Hello World!"), frame.area());
}
Examples found in repository?
More examples
- examples/constraint-explorer.rs
- examples/demo2/app.rs
- examples/block.rs
- examples/calendar.rs
- examples/layout.rs
- examples/gauge.rs
- examples/line_gauge.rs
- examples/list.rs
- examples/hyperlink.rs
- examples/paragraph.rs
- examples/ratatui-logo.rs
- examples/tracing.rs
- examples/popup.rs
- examples/async.rs
- examples/panic.rs
- examples/chart.rs
- examples/sparkline.rs
- examples/flex.rs
- examples/canvas.rs
- examples/custom_widget.rs
- examples/table.rs
- examples/user_input.rs
- examples/scrollbar.rs
- examples/inline.rs
sourcepub fn try_draw<F, E>(
&mut self,
render_callback: F,
) -> Result<CompletedFrame<'_>>
pub fn try_draw<F, E>( &mut self, render_callback: F, ) -> Result<CompletedFrame<'_>>
Tries to draw a single frame to the terminal.
Returns Result::Ok
containing a CompletedFrame
if successful, otherwise
Result::Err
containing the std::io::Error
that caused the failure.
This is the equivalent of Terminal::draw
but the render callback is a function or
closure that returns a Result
instead of nothing.
Applications should call try_draw
or draw
in a loop to continuously render the
terminal. These methods are the main entry points for drawing to the terminal.
This method will:
- autoresize the terminal if necessary
- call the render callback, passing it a
Frame
reference to render to - flush the current internal state by copying the current buffer to the backend
- move the cursor to the last known position if it was set during the rendering closure
- return a
CompletedFrame
with the current buffer and the area of the terminal
The render callback passed to try_draw
can return any Result
with an error type that
can be converted into an std::io::Error
using the Into
trait. This makes it possible
to use the ?
operator to propagate errors that occur during rendering. If the render
callback returns an error, the error will be returned from try_draw
as an
std::io::Error
and the terminal will not be updated.
The CompletedFrame
returned by this method can be useful for debugging or testing
purposes, but it is often not used in regular applicationss.
The render callback should fully render the entire frame when called, including areas that are unchanged from the previous frame. This is because each frame is compared to the previous frame to determine what has changed, and only the changes are written to the terminal. If the render function does not fully render the frame, the terminal will not be in a consistent state.
§Examples
use std::io;
use ratatui::widgets::Paragraph;
// with a closure
terminal.try_draw(|frame| {
let value: u8 = "not a number".parse().map_err(io::Error::other)?;
let area = frame.area();
frame.render_widget(Paragraph::new("Hello World!"), area);
frame.set_cursor_position(Position { x: 0, y: 0 });
io::Result::Ok(())
})?;
// or with a function
terminal.try_draw(render)?;
fn render(frame: &mut ratatui::Frame) -> io::Result<()> {
let value: u8 = "not a number".parse().map_err(io::Error::other)?;
frame.render_widget(Paragraph::new("Hello World!"), frame.area());
Ok(())
}
sourcepub fn hide_cursor(&mut self) -> Result<()>
pub fn hide_cursor(&mut self) -> Result<()>
Hides the cursor.
sourcepub fn show_cursor(&mut self) -> Result<()>
pub fn show_cursor(&mut self) -> Result<()>
Shows the cursor.
sourcepub fn get_cursor(&mut self) -> Result<(u16, u16)>
👎Deprecated: the method get_cursor_position indicates more clearly what about the cursor to get
pub fn get_cursor(&mut self) -> Result<(u16, u16)>
Gets the current cursor position.
This is the position of the cursor after the last draw call and is returned as a tuple of
(x, y)
coordinates.
sourcepub fn set_cursor(&mut self, x: u16, y: u16) -> Result<()>
👎Deprecated: the method set_cursor_position indicates more clearly what about the cursor to set
pub fn set_cursor(&mut self, x: u16, y: u16) -> Result<()>
Sets the cursor position.
sourcepub fn get_cursor_position(&mut self) -> Result<Position>
pub fn get_cursor_position(&mut self) -> Result<Position>
Gets the current cursor position.
This is the position of the cursor after the last draw call.
sourcepub fn set_cursor_position<P: Into<Position>>(
&mut self,
position: P,
) -> Result<()>
pub fn set_cursor_position<P: Into<Position>>( &mut self, position: P, ) -> Result<()>
Sets the cursor position.
sourcepub fn clear(&mut self) -> Result<()>
pub fn clear(&mut self) -> Result<()>
Clear the terminal and force a full redraw on the next draw call.
sourcepub fn swap_buffers(&mut self)
pub fn swap_buffers(&mut self)
Clears the inactive buffer and swaps it with the current buffer
sourcepub fn size(&self) -> Result<Size>
pub fn size(&self) -> Result<Size>
Queries the real size of the backend.
Examples found in repository?
More examples
sourcepub fn insert_before<F>(&mut self, height: u16, draw_fn: F) -> Result<()>
pub fn insert_before<F>(&mut self, height: u16, draw_fn: F) -> Result<()>
Insert some content before the current inline viewport. This has no effect when the viewport is not inline.
The draw_fn
closure will be called to draw into a writable Buffer
that is height
lines tall. The content of that Buffer
will then be inserted before the viewport.
If the viewport isn’t yet at the bottom of the screen, inserted lines will push it towards the bottom. Once the viewport is at the bottom of the screen, inserted lines will scroll the area of the screen above the viewport upwards.
Before:
+---------------------+
| pre-existing line 1 |
| pre-existing line 2 |
+---------------------+
| viewport |
+---------------------+
| |
| |
+---------------------+
After inserting 2 lines:
+---------------------+
| pre-existing line 1 |
| pre-existing line 2 |
| inserted line 1 |
| inserted line 2 |
+---------------------+
| viewport |
+---------------------+
+---------------------+
After inserting 2 more lines:
+---------------------+
| pre-existing line 2 |
| inserted line 1 |
| inserted line 2 |
| inserted line 3 |
| inserted line 4 |
+---------------------+
| viewport |
+---------------------+
If more lines are inserted than there is space on the screen, then the top lines will go directly into the terminal’s scrollback buffer. At the limit, if the viewport takes up the whole screen, all lines will be inserted directly into the scrollback buffer.
§Examples
§Insert a single line before the current viewport
use ratatui::{
backend::TestBackend,
style::{Color, Style},
text::{Line, Span},
widgets::{Paragraph, Widget},
Terminal,
};
terminal.insert_before(1, |buf| {
Paragraph::new(Line::from(vec![
Span::raw("This line will be added "),
Span::styled("before", Style::default().fg(Color::Blue)),
Span::raw(" the current viewport"),
]))
.render(buf.area, buf);
});
Examples found in repository?
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
fn run(
terminal: &mut Terminal<impl Backend>,
workers: Vec<Worker>,
mut downloads: Downloads,
rx: mpsc::Receiver<Event>,
) -> Result<()> {
let mut redraw = true;
loop {
if redraw {
terminal.draw(|frame| draw(frame, &downloads))?;
}
redraw = true;
match rx.recv()? {
Event::Input(event) => {
if event.code == event::KeyCode::Char('q') {
break;
}
}
Event::Resize => {
terminal.autoresize()?;
}
Event::Tick => {}
Event::DownloadUpdate(worker_id, _download_id, progress) => {
let download = downloads.in_progress.get_mut(&worker_id).unwrap();
download.progress = progress;
redraw = false;
}
Event::DownloadDone(worker_id, download_id) => {
let download = downloads.in_progress.remove(&worker_id).unwrap();
terminal.insert_before(1, |buf| {
Paragraph::new(Line::from(vec![
Span::from("Finished "),
Span::styled(
format!("download {download_id}"),
Style::default().add_modifier(Modifier::BOLD),
),
Span::from(format!(
" in {}ms",
download.started_at.elapsed().as_millis()
)),
]))
.render(buf.area, buf);
})?;
match downloads.next(worker_id) {
Some(d) => workers[worker_id].tx.send(d).unwrap(),
None => {
if downloads.in_progress.is_empty() {
terminal.insert_before(1, |buf| {
Paragraph::new("Done !").render(buf.area, buf);
})?;
break;
}
}
};
}
};
}
Ok(())
}
Trait Implementations§
impl<B> Eq for Terminal<B>
impl<B> StructuralPartialEq for Terminal<B>where
B: Backend,
Auto Trait Implementations§
impl<B> Freeze for Terminal<B>where
B: Freeze,
impl<B> RefUnwindSafe for Terminal<B>where
B: RefUnwindSafe,
impl<B> Send for Terminal<B>where
B: Send,
impl<B> Sync for Terminal<B>where
B: Sync,
impl<B> Unpin for Terminal<B>where
B: Unpin,
impl<B> UnwindSafe for Terminal<B>where
B: UnwindSafe,
Blanket Implementations§
source§impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for Swhere
T: Real + Zero + Arithmetics + Clone,
Swp: WhitePoint<T>,
Dwp: WhitePoint<T>,
D: AdaptFrom<S, Swp, Dwp, T>,
impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for Swhere
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) -> Dwhere
M: TransformMatrix<T>,
fn adapt_into_using<M>(self, method: M) -> Dwhere
M: TransformMatrix<T>,
source§fn adapt_into(self) -> D
fn adapt_into(self) -> D
source§impl<T, C> ArraysFrom<C> for Twhere
C: IntoArrays<T>,
impl<T, C> ArraysFrom<C> for Twhere
C: IntoArrays<T>,
source§fn arrays_from(colors: C) -> T
fn arrays_from(colors: C) -> T
source§impl<T, C> ArraysInto<C> for Twhere
C: FromArrays<T>,
impl<T, C> ArraysInto<C> for Twhere
C: FromArrays<T>,
source§fn arrays_into(self) -> C
fn arrays_into(self) -> C
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<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for Uwhere
T: FromCam16Unclamped<WpParam, U>,
impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for Uwhere
T: FromCam16Unclamped<WpParam, U>,
source§type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar
type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar
parameters
when converting.source§fn cam16_into_unclamped(
self,
parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>,
) -> T
fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T
self
into C
, using the provided parameters.source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)source§impl<T, C> ComponentsFrom<C> for Twhere
C: IntoComponents<T>,
impl<T, C> ComponentsFrom<C> for Twhere
C: IntoComponents<T>,
source§fn components_from(colors: C) -> T
fn components_from(colors: C) -> T
source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.source§impl<T> FromAngle<T> for T
impl<T> FromAngle<T> for T
source§fn from_angle(angle: T) -> T
fn from_angle(angle: T) -> T
angle
.source§impl<T, U> FromStimulus<U> for Twhere
U: IntoStimulus<T>,
impl<T, U> FromStimulus<U> for Twhere
U: IntoStimulus<T>,
source§fn from_stimulus(other: U) -> T
fn from_stimulus(other: U) -> T
other
into Self
, while performing the appropriate scaling,
rounding and clamping.source§impl<T, U> IntoAngle<U> for Twhere
U: FromAngle<T>,
impl<T, U> IntoAngle<U> for Twhere
U: FromAngle<T>,
source§fn into_angle(self) -> U
fn into_angle(self) -> U
T
.source§impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for Uwhere
T: Cam16FromUnclamped<WpParam, U>,
impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for Uwhere
T: Cam16FromUnclamped<WpParam, U>,
source§type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar
type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar
parameters
when converting.source§fn into_cam16_unclamped(
self,
parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>,
) -> T
fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T
self
into C
, using the provided parameters.source§impl<T, U> IntoColor<U> for Twhere
U: FromColor<T>,
impl<T, U> IntoColor<U> for Twhere
U: FromColor<T>,
source§fn into_color(self) -> U
fn into_color(self) -> U
source§impl<T, U> IntoColorUnclamped<U> for Twhere
U: FromColorUnclamped<T>,
impl<T, U> IntoColorUnclamped<U> for Twhere
U: FromColorUnclamped<T>,
source§fn into_color_unclamped(self) -> U
fn into_color_unclamped(self) -> U
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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 moresource§impl<T> IntoStimulus<T> for T
impl<T> IntoStimulus<T> for T
source§fn into_stimulus(self) -> T
fn into_stimulus(self) -> T
self
into T
, while performing the appropriate scaling,
rounding and clamping.source§impl<T, C> TryComponentsInto<C> for Twhere
C: TryFromComponents<T>,
impl<T, C> TryComponentsInto<C> for Twhere
C: TryFromComponents<T>,
source§type Error = <C as TryFromComponents<T>>::Error
type Error = <C as TryFromComponents<T>>::Error
try_into_colors
fails to cast.source§fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>
fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>
source§impl<T, U> TryIntoColor<U> for Twhere
U: TryFromColor<T>,
impl<T, U> TryIntoColor<U> for Twhere
U: TryFromColor<T>,
source§fn try_into_color(self) -> Result<U, OutOfBounds<U>>
fn try_into_color(self) -> Result<U, OutOfBounds<U>>
OutOfBounds
error is returned which contains
the unclamped color. Read more