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