Skip to content

Commit

Permalink
fix(panics): added panic hook to reset terminal in case of accident, …
Browse files Browse the repository at this point in the history
…fixes u16 overflow
  • Loading branch information
JeromeSchmied committed Feb 29, 2024
1 parent 3f65df6 commit e35017d
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 5 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,17 @@ clone the repo and run `cargo r`

![Sample][1]

## todos
## Todos

- [x] initial tui support
- [x] renaming on gh
- [x] error handling
- [x] publishing to crates.io

## Warning!

If your terminal is messed up by accident fix: on Mac, Linux: `reset`, on Windows: exit the app.

## Acknowledgements

The core of this app is adapted from the great [Rust-Wasm tutorial](https://rustwasm.github.io/docs/book/).
Expand Down
3 changes: 2 additions & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ impl App {
self.paused = !self.paused;
}
pub fn restart(&mut self) {
self.universe = shapes::get(self.wh(), self.i).unwrap();
self.universe =
shapes::get(self.wh(), self.i).expect("display area is too small to fit current shape");
}

pub fn tick(&mut self) {
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub struct Universe {
impl Universe {
/// Convert (x;y) to index
fn get_index(&self, row: u16, col: u16) -> usize {
(row * self.width + col) as usize
(row as u32 * self.width as u32 + col as u32) as usize
}

fn live_neighbour_count(&self, row: u16, col: u16) -> u8 {
Expand Down Expand Up @@ -104,7 +104,7 @@ impl Universe {
return Err(HandleError::TooBig);
}

let cells = (0..wh * wh).map(|_i| Cell::Dead).collect();
let cells = (0..wh as u32 * wh as u32).map(|_i| Cell::Dead).collect();
let mut univ = Universe {
cells,
width: wh,
Expand Down
11 changes: 10 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,18 @@ use ratatui::{
backend::{Backend, CrosstermBackend},
Terminal,
};
use std::io;
use std::{io, panic};

fn main() -> Result<(), Box<dyn std::error::Error>> {
// Define a custom panic hook to reset the terminal properties.
// This way, you won't have your terminal messed up if an unexpected error happens.
let panic_hook = panic::take_hook();
panic::set_hook(Box::new(move |panic| {
disable_raw_mode().expect("couldn't disable raw_mode");
execute!(io::stdout(), LeaveAlternateScreen).expect("couldn't leave alternate screen");
panic_hook(panic);
}));

// init terminal
enable_raw_mode()?;
execute!(io::stdout(), EnterAlternateScreen)?;
Expand Down

0 comments on commit e35017d

Please sign in to comment.