Skip to content
This repository was archived by the owner on Aug 6, 2023. It is now read-only.

Commit

Permalink
feat(terminal): add a read-only view of the terminal state after the …
Browse files Browse the repository at this point in the history
…draw call
  • Loading branch information
fdehau committed Jan 1, 2021
1 parent 67e996c commit 143cb40
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@
//! .title("Block")
//! .borders(Borders::ALL);
//! f.render_widget(block, size);
//! })
//! })?;
//! Ok(())
//! }
//! ```
//!
Expand Down Expand Up @@ -136,7 +137,8 @@
//! .title("Block 2")
//! .borders(Borders::ALL);
//! f.render_widget(block, chunks[1]);
//! })
//! })?;
//! Ok(())
//! }
//! ```
//!
Expand Down
13 changes: 11 additions & 2 deletions src/terminal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,13 @@ where
}
}

/// CompletedFrame represents the state of the terminal after all changes performed in the last
/// [`Terminal::draw`] call have been applied. Therefore, it is only valid until the next call to
/// [`Terminal::draw`].
pub struct CompletedFrame<'a> {
pub buffer: &'a Buffer,
}

impl<B> Drop for Terminal<B>
where
B: Backend,
Expand Down Expand Up @@ -247,7 +254,7 @@ where

/// Synchronizes terminal size, calls the rendering closure, flushes the current internal state
/// and prepares for the next draw call.
pub fn draw<F>(&mut self, f: F) -> io::Result<()>
pub fn draw<F>(&mut self, f: F) -> io::Result<CompletedFrame>
where
F: FnOnce(&mut Frame<B>),
{
Expand Down Expand Up @@ -279,7 +286,9 @@ where

// Flush
self.backend.flush()?;
Ok(())
Ok(CompletedFrame {
buffer: &self.buffers[1 - self.current],
})
}

pub fn hide_cursor(&mut self) -> io::Result<()> {
Expand Down
19 changes: 19 additions & 0 deletions tests/terminal.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::error::Error;
use tui::{
backend::{Backend, TestBackend},
widgets::Paragraph,
Terminal,
};

Expand All @@ -11,3 +13,20 @@ fn terminal_buffer_size_should_be_limited() {
assert_eq!(size.width, 255);
assert_eq!(size.height, 255);
}

#[test]
fn terminal_draw_returns_the_completed_frame() -> Result<(), Box<dyn Error>> {
let backend = TestBackend::new(10, 10);
let mut terminal = Terminal::new(backend)?;
let frame = terminal.draw(|f| {
let paragrah = Paragraph::new("Test");
f.render_widget(paragrah, f.size());
})?;
assert_eq!(frame.buffer.get(0, 0).symbol, "T");
let frame = terminal.draw(|f| {
let paragrah = Paragraph::new("test");
f.render_widget(paragrah, f.size());
})?;
assert_eq!(frame.buffer.get(0, 0).symbol, "t");
Ok(())
}

0 comments on commit 143cb40

Please sign in to comment.