Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better error message for empty language file, implement drop for State to disable raw mode and other modes #101

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 34 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod test;
mod ui;

use config::Config;
use std::ops::Drop;
use test::{results::Results, Test};

use crossterm::{
Expand Down Expand Up @@ -98,6 +99,10 @@ impl Opt {
.map(|f| f.data.into_owned())
})?;

if bytes.is_empty() {
panic!("Language file had not content.");
}

let mut rng = thread_rng();

let mut language: Vec<&str> = str::from_utf8(&bytes)
Expand Down Expand Up @@ -171,6 +176,17 @@ enum State {
}

impl State {
fn set_modes(&self) -> crossterm::Result<()> {
terminal::enable_raw_mode()?;
execute!(
io::stdout(),
cursor::Hide,
cursor::SavePosition,
terminal::EnterAlternateScreen,
)?;
Ok(())
}

fn render_into<B: ratatui::backend::Backend>(
&self,
terminal: &mut Terminal<B>,
Expand All @@ -192,6 +208,23 @@ impl State {
}
}

impl Drop for State {
fn drop(&mut self) {
let _ = terminal::disable_raw_mode().map_err(|err| {
eprintln!("Couldn't disable raw mode: {err}");
});
let _ = execute!(
io::stdout(),
cursor::RestorePosition,
cursor::Show,
terminal::LeaveAlternateScreen,
)
.map_err(|err| {
eprintln!("Couldn't restore default terminal settings: {err}");
});
}
}

fn main() -> crossterm::Result<()> {
let opt = Opt::from_args();
if opt.debug {
Expand All @@ -214,13 +247,6 @@ fn main() -> crossterm::Result<()> {
let backend = CrosstermBackend::new(io::stdout());
let mut terminal = Terminal::new(backend)?;

terminal::enable_raw_mode()?;
execute!(
io::stdout(),
cursor::Hide,
cursor::SavePosition,
terminal::EnterAlternateScreen,
)?;
terminal.clear()?;

let mut state = State::Test(Test::new(
Expand All @@ -229,6 +255,7 @@ fn main() -> crossterm::Result<()> {
),
!opt.no_backtrack,
));
state.set_modes()?;

state.render_into(&mut terminal, &config)?;
loop {
Expand Down Expand Up @@ -309,13 +336,5 @@ fn main() -> crossterm::Result<()> {
state.render_into(&mut terminal, &config)?;
}

terminal::disable_raw_mode()?;
execute!(
io::stdout(),
cursor::RestorePosition,
cursor::Show,
terminal::LeaveAlternateScreen,
)?;

Ok(())
}
Loading