Restructuring code as "impl" + proper quitting

This commit is contained in:
Jarkko Toivanen 2024-07-31 23:02:51 +03:00
parent fa5cddb358
commit 5fc444519d
Signed by: jt
GPG key ID: 9151B109B73ECAD5

View file

@ -4,55 +4,67 @@ use crossterm::{
};
use std::panic;
use std::{
io::{stdout, Result, Write},
io::{stdout, Result, Write, Stdout},
time::Duration,
};
#[derive(Default)]
struct Nuudel {
quitting: bool,
cursorx: i32,
cursory: i32,
}
fn main() -> Result<()> {
// Setup panic handling
let default_panic = panic::take_hook();
panic::set_hook(Box::new(move |info| {
let _ = restore();
let _ = Nuudel::restore_terminal();
default_panic(info);
}));
// Start terminaling
init()?;
let mut stdout = stdout();
print!("Press Q to quit");
// Basic stuff
let mut nuudel = Nuudel::default();
Nuudel::init_terminal()?;
nuudel.run(&mut stdout())?;
Nuudel::restore_terminal()?;
// Main loop
let quitting = false;
while !quitting {
//stdout.execute(terminal::BeginSynchronizedUpdate)?;
handle_events()?;
stdout.flush()?;
//stdout.execute(terminal::EndSynchronizedUpdate)?;
}
// Stop terminaling
restore()?;
Ok(())
}
fn init() -> Result<()> {
impl Nuudel {
pub fn run(&mut self, stdout: &mut Stdout) -> Result<()> {
print!("Press Q to quit");
while !self.quitting {
self.handle_events()?;
stdout.flush()?;
}
Ok(())
}
fn init_terminal() -> Result<()> {
terminal::enable_raw_mode()?;
stdout().execute(terminal::EnterAlternateScreen)?;
Ok(())
}
fn restore() -> Result<()> {
fn restore_terminal() -> Result<()> {
stdout().execute(terminal::LeaveAlternateScreen)?;
terminal::disable_raw_mode()?;
Ok(())
}
fn quit(&mut self) {
self.quitting = true;
}
fn handle_events() -> Result<()> {
fn handle_events(&mut self) -> Result<()> {
if poll(Duration::from_secs(0))? {
match read()? {
Event::Key(event) => match event.code {
KeyCode::Char('q') => {
panic!("Just quitting, in a way...");
self.quit();
},
KeyCode::Char('a') => {
print!("");
@ -76,3 +88,4 @@ fn handle_events() -> Result<()> {
}
Ok(())
}
}