Created
March 4, 2023 10:54
-
-
Save BoolPurist/89c9ba1f001e8874dccf9eaa61071761 to your computer and use it in GitHub Desktop.
example for issue ratatui
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use crossterm::{ | |
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode}, | |
execute, | |
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, | |
}; | |
use std::{ | |
error::Error, | |
io, | |
time::{Duration, Instant}, | |
}; | |
use tui::{ | |
backend::{Backend, CrosstermBackend}, | |
layout::{Constraint, Direction, Layout}, | |
style::Color, | |
symbols::Marker, | |
widgets::{ | |
canvas::{Canvas, Line}, | |
Block, Borders, | |
}, | |
Frame, Terminal, | |
}; | |
fn main() -> Result<(), Box<dyn Error>> { | |
// setup terminal | |
enable_raw_mode()?; | |
let mut stdout = io::stdout(); | |
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?; | |
let backend = CrosstermBackend::new(stdout); | |
let mut terminal = Terminal::new(backend)?; | |
let tick_rate = Duration::from_millis(250); | |
let res = run_app(&mut terminal, tick_rate); | |
// restore terminal | |
disable_raw_mode()?; | |
execute!( | |
terminal.backend_mut(), | |
LeaveAlternateScreen, | |
DisableMouseCapture | |
)?; | |
terminal.show_cursor()?; | |
if let Err(err) = res { | |
println!("{:?}", err) | |
} | |
Ok(()) | |
} | |
fn run_app<B: Backend>(terminal: &mut Terminal<B>, tick_rate: Duration) -> io::Result<()> { | |
let mut last_tick = Instant::now(); | |
loop { | |
terminal.draw(|f| ui(f))?; | |
let timeout = tick_rate | |
.checked_sub(last_tick.elapsed()) | |
.unwrap_or_else(|| Duration::from_secs(0)); | |
if event::poll(timeout)? { | |
if let Event::Key(key) = event::read()? { | |
if let KeyCode::Char('q') = key.code { | |
return Ok(()); | |
} | |
} | |
} | |
if last_tick.elapsed() >= tick_rate { | |
last_tick = Instant::now(); | |
} | |
} | |
} | |
fn ui<B: Backend>(f: &mut Frame<B>) { | |
let chunks = Layout::default() | |
.direction(Direction::Horizontal) | |
.constraints([Constraint::Percentage(100)].as_ref()) | |
.split(f.size()); | |
let canvas = Canvas::default() | |
.block(Block::default().borders(Borders::ALL).title("World")) | |
.marker(Marker::Block) | |
.paint(|ctx| { | |
let horz_line = Line { | |
x1: 0., | |
y1: 0., | |
x2: 10., | |
y2: 0., | |
color: Color::Red, | |
}; | |
let vertical_line = Line { | |
x1: 50., | |
y1: 0., | |
x2: 50.0, | |
y2: 10., | |
color: Color::Blue, | |
}; | |
ctx.draw(&horz_line); | |
ctx.draw(&vertical_line); | |
}) | |
.x_bounds([-180.0, 180.0]) | |
.y_bounds([-90.0, 90.0]); | |
f.render_widget(canvas, chunks[0]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment