Add quit confirmation on unsaved changes

This commit is contained in:
Timothy Warren 2021-03-10 15:33:41 -05:00
parent 72e723ffa5
commit cf0c576284
1 changed files with 23 additions and 1 deletions

View File

@ -10,6 +10,7 @@ use termion::event::Key;
const STATUS_FG_COLOR: color::Rgb = color::Rgb(63, 63, 63);
const STATUS_BG_COLOR: color::Rgb = color::Rgb(239, 239, 239);
const VERSION: &str = env!("CARGO_PKG_VERSION");
const QUIT_TIMES: u8 = 3;
#[derive(Default)]
pub struct Position {
@ -42,6 +43,7 @@ pub struct Editor {
offset: Position,
document: Document,
status_message: StatusMessage,
quit_times: u8,
}
impl Editor {
@ -82,6 +84,7 @@ impl Editor {
cursor_position: Position::default(),
offset: Position::default(),
status_message: StatusMessage::from(initial_status),
quit_times: QUIT_TIMES,
}
}
@ -176,7 +179,20 @@ impl Editor {
fn process_keypress(&mut self) -> Result<(), std::io::Error> {
let pressed_key = Terminal::read_key()?;
match pressed_key {
Key::Ctrl('q') => self.should_quit = true,
Key::Ctrl('q') => {
if self.quit_times > 0 && self.document.is_dirty() {
self.status_message = StatusMessage::from(format!(
"WARNING! File has unsaved changes. Press Ctrl-Q {} more times to quit.",
self.quit_times
));
self.quit_times -= 1;
return Ok(());
}
self.should_quit = true
},
Key::Ctrl('s') => self.save(),
Key::Char(c) => {
self.document.insert(&self.cursor_position, c);
@ -202,6 +218,12 @@ impl Editor {
self.scroll();
// Reset quit confirmation count if not Ctrl-Q input
if self.quit_times < QUIT_TIMES {
self.quit_times = QUIT_TIMES;
self.status_message = StatusMessage::default();
}
Ok(())
}