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,75 +4,88 @@ 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)?;
Ok(())
}
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(())
}
// Stop terminaling
restore()?;
Ok(())
}
fn init_terminal() -> Result<()> {
terminal::enable_raw_mode()?;
stdout().execute(terminal::EnterAlternateScreen)?;
Ok(())
}
fn init() -> Result<()> {
terminal::enable_raw_mode()?;
stdout().execute(terminal::EnterAlternateScreen)?;
Ok(())
}
fn restore_terminal() -> Result<()> {
stdout().execute(terminal::LeaveAlternateScreen)?;
terminal::disable_raw_mode()?;
Ok(())
}
fn quit(&mut self) {
self.quitting = true;
}
fn restore() -> Result<()> {
stdout().execute(terminal::LeaveAlternateScreen)?;
terminal::disable_raw_mode()?;
Ok(())
}
fn handle_events() -> Result<()> {
if poll(Duration::from_secs(0))? {
match read()? {
Event::Key(event) => match event.code {
KeyCode::Char('q') => {
panic!("Just quitting, in a way...");
},
KeyCode::Char('a') => {
print!("");
},
KeyCode::Left => {
stdout().execute(cursor::MoveLeft(1))?;
},
KeyCode::Right => {
stdout().execute(cursor::MoveRight(1))?;
},
KeyCode::Up => {
stdout().execute(cursor::MoveUp(1))?;
},
KeyCode::Down => {
stdout().execute(cursor::MoveDown(1))?;
fn handle_events(&mut self) -> Result<()> {
if poll(Duration::from_secs(0))? {
match read()? {
Event::Key(event) => match event.code {
KeyCode::Char('q') => {
self.quit();
},
KeyCode::Char('a') => {
print!("");
},
KeyCode::Left => {
stdout().execute(cursor::MoveLeft(1))?;
},
KeyCode::Right => {
stdout().execute(cursor::MoveRight(1))?;
},
KeyCode::Up => {
stdout().execute(cursor::MoveUp(1))?;
},
KeyCode::Down => {
stdout().execute(cursor::MoveDown(1))?;
},
_ => {}
},
_ => {}
},
_ => {}
}
}
Ok(())
}
Ok(())
}