2024-01-24 19:50:18 +00:00
|
|
|
//! # [Ratatui] Colors_RGB example
|
|
|
|
//!
|
|
|
|
//! The latest version of this example is available in the [examples] folder in the repository.
|
|
|
|
//!
|
|
|
|
//! Please note that the examples are designed to be run against the `main` branch of the Github
|
|
|
|
//! repository. This means that you may not be able to compile with the latest release version on
|
|
|
|
//! crates.io, or the one that you have installed locally.
|
|
|
|
//!
|
|
|
|
//! See the [examples readme] for more information on finding examples that match the version of the
|
|
|
|
//! library you are using.
|
|
|
|
//!
|
|
|
|
//! [Ratatui]: https://github.com/ratatui-org/ratatui
|
|
|
|
//! [examples]: https://github.com/ratatui-org/ratatui/blob/main/examples
|
|
|
|
//! [examples readme]: https://github.com/ratatui-org/ratatui/blob/main/examples/README.md
|
|
|
|
|
2023-09-10 00:30:41 +00:00
|
|
|
/// This example shows the full range of RGB colors that can be displayed in the terminal.
|
|
|
|
///
|
|
|
|
/// Requires a terminal that supports 24-bit color (true color) and unicode.
|
2024-01-24 15:13:11 +00:00
|
|
|
///
|
|
|
|
/// This example also demonstrates how implementing the Widget trait on a mutable reference
|
|
|
|
/// allows the widget to update its state while it is being rendered. This allows the fps
|
|
|
|
/// widget to update the fps calculation and the colors widget to update a cached version of
|
|
|
|
/// the colors to render instead of recalculating them every frame.
|
|
|
|
///
|
|
|
|
/// This is an alternative to using the StatefulWidget trait and a separate state struct. It is
|
|
|
|
/// useful when the state is only used by the widget and doesn't need to be shared with other
|
|
|
|
/// widgets.
|
2023-09-10 00:30:41 +00:00
|
|
|
use std::{
|
2023-12-17 09:34:59 +00:00
|
|
|
io::stdout,
|
2024-01-24 15:13:11 +00:00
|
|
|
panic,
|
2023-12-17 09:34:59 +00:00
|
|
|
time::{Duration, Instant},
|
2023-09-10 00:30:41 +00:00
|
|
|
};
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
use color_eyre::{config::HookBuilder, eyre, Result};
|
2023-09-10 00:30:41 +00:00
|
|
|
use crossterm::{
|
|
|
|
event::{self, Event, KeyCode, KeyEventKind},
|
|
|
|
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
|
|
|
ExecutableCommand,
|
|
|
|
};
|
2023-12-17 09:34:59 +00:00
|
|
|
use palette::{convert::FromColorUnclamped, Okhsv, Srgb};
|
2024-01-24 18:34:10 +00:00
|
|
|
use ratatui::prelude::*;
|
2023-09-10 00:30:41 +00:00
|
|
|
|
2023-12-17 09:34:59 +00:00
|
|
|
#[derive(Debug, Default)]
|
2023-09-10 00:30:41 +00:00
|
|
|
struct App {
|
2024-01-24 15:13:11 +00:00
|
|
|
/// The current state of the app (running or quit)
|
|
|
|
state: AppState,
|
|
|
|
|
|
|
|
/// A widget that displays the current frames per second
|
|
|
|
fps_widget: FpsWidget,
|
|
|
|
|
|
|
|
/// A widget that displays the full range of RGB colors that can be displayed in the terminal.
|
|
|
|
colors_widget: ColorsWidget,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Default, PartialEq, Eq)]
|
|
|
|
enum AppState {
|
|
|
|
/// The app is running
|
|
|
|
#[default]
|
|
|
|
Running,
|
|
|
|
|
|
|
|
/// The user has requested the app to quit
|
|
|
|
Quit,
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
/// A widget that displays the current frames per second
|
2023-12-17 09:34:59 +00:00
|
|
|
#[derive(Debug)]
|
2024-01-24 15:13:11 +00:00
|
|
|
struct FpsWidget {
|
|
|
|
/// The number of elapsed frames that have passed - used to calculate the fps
|
2023-12-17 09:34:59 +00:00
|
|
|
frame_count: usize,
|
2024-01-24 15:13:11 +00:00
|
|
|
|
|
|
|
/// The last instant that the fps was calculated
|
2023-12-17 09:34:59 +00:00
|
|
|
last_instant: Instant,
|
2024-01-24 15:13:11 +00:00
|
|
|
|
|
|
|
/// The current frames per second
|
2023-12-17 09:34:59 +00:00
|
|
|
fps: Option<f32>,
|
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
/// A widget that displays the full range of RGB colors that can be displayed in the terminal.
|
|
|
|
///
|
|
|
|
/// This widget is animated and will change colors over time.
|
|
|
|
#[derive(Debug, Default)]
|
|
|
|
struct ColorsWidget {
|
|
|
|
/// The colors to render - should be double the height of the area as we render two rows of
|
|
|
|
/// pixels for each row of the widget using the half block character. This is computed any time
|
|
|
|
/// the size of the widget changes.
|
|
|
|
colors: Vec<Vec<Color>>,
|
2023-12-17 09:34:59 +00:00
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
/// the number of elapsed frames that have passed - used to animate the colors by shifting the
|
|
|
|
/// x index by the frame number
|
|
|
|
frame_count: usize,
|
2023-12-17 09:34:59 +00:00
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
fn main() -> Result<()> {
|
|
|
|
install_error_hooks()?;
|
|
|
|
let terminal = init_terminal()?;
|
|
|
|
App::default().run(terminal)?;
|
|
|
|
restore_terminal()?;
|
|
|
|
Ok(())
|
2023-12-17 09:34:59 +00:00
|
|
|
}
|
2023-09-10 00:30:41 +00:00
|
|
|
|
2023-12-17 09:34:59 +00:00
|
|
|
impl App {
|
2024-01-24 15:13:11 +00:00
|
|
|
/// Run the app
|
|
|
|
///
|
|
|
|
/// This is the main event loop for the app.
|
|
|
|
pub fn run(mut self, mut terminal: Terminal<impl Backend>) -> Result<()> {
|
|
|
|
while self.is_running() {
|
|
|
|
terminal.draw(|frame| frame.render_widget(&mut self, frame.size()))?;
|
|
|
|
self.handle_events()?;
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
fn is_running(&self) -> bool {
|
|
|
|
matches!(self.state, AppState::Running)
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
/// Handle any events that have occurred since the last time the app was rendered.
|
|
|
|
///
|
|
|
|
/// Currently, this only handles the q key to quit the app.
|
|
|
|
fn handle_events(&mut self) -> Result<()> {
|
|
|
|
// Ensure that the app only blocks for a period that allows the app to render at
|
|
|
|
// approximately 60 FPS (this doesn't account for the time to render the frame, and will
|
|
|
|
// also update the app immediately any time an event occurs)
|
|
|
|
let timeout = Duration::from_secs_f32(1.0 / 60.0);
|
|
|
|
if event::poll(timeout)? {
|
2023-09-10 00:30:41 +00:00
|
|
|
if let Event::Key(key) = event::read()? {
|
|
|
|
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
|
2024-01-24 15:13:11 +00:00
|
|
|
self.state = AppState::Quit;
|
2023-09-10 00:30:41 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
/// Implement the Widget trait for &mut App so that it can be rendered
|
|
|
|
///
|
|
|
|
/// This is implemented on a mutable reference so that the app can update its state while it is
|
|
|
|
/// being rendered. This allows the fps widget to update the fps calculation and the colors widget
|
|
|
|
/// to update the colors to render.
|
|
|
|
impl Widget for &mut App {
|
|
|
|
fn render(self, area: Rect, buf: &mut Buffer) {
|
|
|
|
use Constraint::*;
|
|
|
|
let [top, colors] = area.split(&Layout::vertical([Length(1), Min(0)]));
|
|
|
|
let [title, fps] = top.split(&Layout::horizontal([Min(0), Length(8)]));
|
|
|
|
Text::from("colors_rgb example. Press q to quit")
|
|
|
|
.centered()
|
|
|
|
.render(title, buf);
|
|
|
|
self.fps_widget.render(fps, buf);
|
|
|
|
self.colors_widget.render(colors, buf);
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
/// Default impl for FpsWidget
|
|
|
|
///
|
|
|
|
/// Manual impl is required because we need to initialize the last_instant field to the current
|
|
|
|
/// instant.
|
|
|
|
impl Default for FpsWidget {
|
2023-12-17 09:34:59 +00:00
|
|
|
fn default() -> Self {
|
|
|
|
Self {
|
|
|
|
frame_count: 0,
|
|
|
|
last_instant: Instant::now(),
|
|
|
|
fps: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-09-10 00:30:41 +00:00
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
/// Widget impl for FpsWidget
|
|
|
|
///
|
|
|
|
/// This is implemented on a mutable reference so that we can update the frame count and fps
|
|
|
|
/// calculation while rendering.
|
|
|
|
impl Widget for &mut FpsWidget {
|
|
|
|
fn render(self, area: Rect, buf: &mut Buffer) {
|
|
|
|
self.calculate_fps();
|
|
|
|
if let Some(fps) = self.fps {
|
|
|
|
let text = format!("{:.1} fps", fps);
|
|
|
|
Text::from(text).render(area, buf);
|
2023-12-17 09:34:59 +00:00
|
|
|
}
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
impl FpsWidget {
|
|
|
|
/// Update the fps calculation.
|
|
|
|
///
|
|
|
|
/// This updates the fps once a second, but only if the widget has rendered at least 2 frames
|
|
|
|
/// since the last calculation. This avoids noise in the fps calculation when rendering on slow
|
|
|
|
/// machines that can't render at least 2 frames per second.
|
|
|
|
fn calculate_fps(&mut self) {
|
|
|
|
self.frame_count += 1;
|
|
|
|
let elapsed = self.last_instant.elapsed();
|
|
|
|
if elapsed > Duration::from_secs(1) && self.frame_count > 2 {
|
|
|
|
self.fps = Some(self.frame_count as f32 / elapsed.as_secs_f32());
|
|
|
|
self.frame_count = 0;
|
|
|
|
self.last_instant = Instant::now();
|
|
|
|
}
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
2023-12-17 09:34:59 +00:00
|
|
|
}
|
2023-09-10 00:30:41 +00:00
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
/// Widget impl for ColorsWidget
|
|
|
|
///
|
|
|
|
/// This is implemented on a mutable reference so that we can update the frame count and store a
|
|
|
|
/// cached version of the colors to render instead of recalculating them every frame.
|
|
|
|
impl Widget for &mut ColorsWidget {
|
|
|
|
/// Render the widget
|
2023-12-17 09:34:59 +00:00
|
|
|
fn render(self, area: Rect, buf: &mut Buffer) {
|
2024-01-24 15:13:11 +00:00
|
|
|
self.setup_colors(area);
|
|
|
|
let colors = &self.colors;
|
2023-09-21 08:47:23 +00:00
|
|
|
for (xi, x) in (area.left()..area.right()).enumerate() {
|
2023-12-17 09:34:59 +00:00
|
|
|
// animate the colors by shifting the x index by the frame number
|
|
|
|
let xi = (xi + self.frame_count) % (area.width as usize);
|
2023-09-21 08:47:23 +00:00
|
|
|
for (yi, y) in (area.top()..area.bottom()).enumerate() {
|
2024-01-24 15:13:11 +00:00
|
|
|
// render a half block character for each row of pixels with the foreground color
|
|
|
|
// set to the color of the pixel and the background color set to the color of the
|
|
|
|
// pixel below it
|
2023-12-17 09:34:59 +00:00
|
|
|
let fg = colors[yi * 2][xi];
|
|
|
|
let bg = colors[yi * 2 + 1][xi];
|
2023-09-21 08:47:23 +00:00
|
|
|
buf.get_mut(x, y).set_char('▀').set_fg(fg).set_bg(bg);
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
|
|
|
}
|
2024-01-24 15:13:11 +00:00
|
|
|
self.frame_count += 1;
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
impl ColorsWidget {
|
|
|
|
/// Setup the colors to render.
|
|
|
|
///
|
|
|
|
/// This is called once per frame to setup the colors to render. It caches the colors so that
|
|
|
|
/// they don't need to be recalculated every frame.
|
|
|
|
fn setup_colors(&mut self, size: Rect) {
|
|
|
|
let Rect { width, height, .. } = size;
|
|
|
|
// double the height because each screen row has two rows of half block pixels
|
|
|
|
let height = height as usize * 2;
|
|
|
|
let width = width as usize;
|
|
|
|
// only update the colors if the size has changed since the last time we rendered
|
|
|
|
if self.colors.len() == height && self.colors[0].len() == width {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
self.colors = Vec::with_capacity(height);
|
|
|
|
for y in 0..height {
|
|
|
|
let mut row = Vec::with_capacity(width);
|
|
|
|
for x in 0..width {
|
|
|
|
let hue = x as f32 * 360.0 / width as f32;
|
|
|
|
let value = (height - y) as f32 / height as f32;
|
|
|
|
let saturation = Okhsv::max_saturation();
|
|
|
|
let color = Okhsv::new(hue, saturation, value);
|
|
|
|
let color = Srgb::<f32>::from_color_unclamped(color);
|
|
|
|
let color: Srgb<u8> = color.into_format();
|
|
|
|
let color = Color::Rgb(color.red, color.green, color.blue);
|
|
|
|
row.push(color);
|
|
|
|
}
|
|
|
|
self.colors.push(row);
|
2023-12-17 09:34:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
/// Install color_eyre panic and error hooks
|
|
|
|
///
|
|
|
|
/// The hooks restore the terminal to a usable state before printing the error message.
|
|
|
|
fn install_error_hooks() -> Result<()> {
|
2023-12-17 09:34:59 +00:00
|
|
|
let (panic, error) = HookBuilder::default().into_hooks();
|
|
|
|
let panic = panic.into_panic_hook();
|
|
|
|
let error = error.into_eyre_hook();
|
2024-01-24 15:13:11 +00:00
|
|
|
eyre::set_hook(Box::new(move |e| {
|
2023-12-17 09:34:59 +00:00
|
|
|
let _ = restore_terminal();
|
|
|
|
error(e)
|
|
|
|
}))?;
|
2024-01-24 15:13:11 +00:00
|
|
|
panic::set_hook(Box::new(move |info| {
|
2023-09-10 00:30:41 +00:00
|
|
|
let _ = restore_terminal();
|
2023-12-17 09:34:59 +00:00
|
|
|
panic(info)
|
2023-09-10 00:30:41 +00:00
|
|
|
}));
|
2023-12-17 09:34:59 +00:00
|
|
|
Ok(())
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
fn init_terminal() -> Result<Terminal<impl Backend>> {
|
2023-09-10 00:30:41 +00:00
|
|
|
enable_raw_mode()?;
|
|
|
|
stdout().execute(EnterAlternateScreen)?;
|
2023-12-17 09:34:59 +00:00
|
|
|
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
|
|
|
|
terminal.clear()?;
|
|
|
|
terminal.hide_cursor()?;
|
|
|
|
Ok(terminal)
|
2023-09-10 00:30:41 +00:00
|
|
|
}
|
|
|
|
|
2024-01-24 15:13:11 +00:00
|
|
|
fn restore_terminal() -> Result<()> {
|
2023-09-10 00:30:41 +00:00
|
|
|
disable_raw_mode()?;
|
|
|
|
stdout().execute(LeaveAlternateScreen)?;
|
|
|
|
Ok(())
|
|
|
|
}
|