Krolyxon
Commit 43502f8

Branches

Tags

Refs →

bench51cratesbench51-tuisrcuimod.rs

68 lines · 2.1 KB · Rust

1mod app;
2pub mod draw;
3mod syntax;
4
5use std::io;
6use std::path::PathBuf;
7use std::time::{Duration, Instant};
8
9use ratatui::crossterm::event::{
10 self, DisableMouseCapture, EnableMouseCapture, Event, KeyEventKind,
11};
12use ratatui::crossterm::execute;
13use ratatui::crossterm::terminal::{
14 EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
15};
16
17use app::App;
18
19const FRAME: Duration = Duration::from_millis(33);
20
21pub fn run(path: Option<PathBuf>, clock_mhz: f64) -> io::Result<()> {
22 let mut terminal = ratatui::init();
23 execute!(io::stdout(), EnableMouseCapture)?;
24 let mut app = App::new(path, clock_mhz);
25 let result = event_loop(&mut terminal, &mut app);
26 let _ = execute!(io::stdout(), DisableMouseCapture);
27 ratatui::restore();
28 result
29}
30
31fn event_loop(terminal: &mut ratatui::DefaultTerminal, app: &mut App) -> io::Result<()> {
32 let mut next_frame = Instant::now();
33 while !app.quit {
34 terminal.draw(|f| draw::draw(f, app))?;
35 // Wait for input until the next frame is due; while running, the
36 // simulation advances once per frame.
37 let timeout = next_frame.saturating_duration_since(Instant::now());
38 if event::poll(timeout)? {
39 match event::read()? {
40 Event::Key(k) if k.kind != KeyEventKind::Release => app.on_key(k),
41 Event::Mouse(m) => app.on_mouse(m),
42 _ => {}
43 }
44 }
45 if std::mem::take(&mut app.external_edit) {
46 suspend()?;
47 app.edit_externally();
48 resume(terminal)?;
49 }
50 if Instant::now() >= next_frame {
51 app.tick();
52 next_frame = Instant::now() + FRAME;
53 }
54 }
55 Ok(())
56}
57
58/// Hands the terminal back to the shell (for `$EDITOR`).
59fn suspend() -> io::Result<()> {
60 execute!(io::stdout(), DisableMouseCapture, LeaveAlternateScreen)?;
61 disable_raw_mode()
62}
63
64fn resume(terminal: &mut ratatui::DefaultTerminal) -> io::Result<()> {
65 enable_raw_mode()?;
66 execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?;
67 terminal.clear()
68}