From aecedfb4bee905f32504ee34d59e7fd4e8b1228c Mon Sep 17 00:00:00 2001 From: CrispyPin Date: Tue, 14 Mar 2023 14:04:21 +0100 Subject: [PATCH] add confirmation dialog on exit when there are unsaved changes --- src/editor.rs | 4 ++++ src/main.rs | 11 ++++++++++- src/util.rs | 10 ++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/editor.rs b/src/editor.rs index 03aa0f8..0ed2527 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -82,6 +82,10 @@ impl Editor { "*untitled".into() } + pub fn is_unsaved(&self) -> bool { + self.unsaved_changes + } + pub fn path(&self) -> Option<&PathBuf> { self.path.as_ref() } diff --git a/src/main.rs b/src/main.rs index 313b07e..76a7063 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,9 +17,9 @@ use std::{ mod clipboard; mod editor; mod util; -use crate::util::{color_highlight, color_reset}; use clipboard::Clipboard; use editor::Editor; +use util::{color_highlight, color_reset, read_yes_no}; fn main() { Navigator::new().run(); @@ -257,7 +257,16 @@ impl Navigator { } } + fn any_unsaved(&self) -> bool { + self.editors.iter().any(Editor::is_unsaved) + } + fn quit(&self) { + if self.any_unsaved() { + if !read_yes_no("Unsaved changes, quit anyway?", false) { + return; + } + } disable_raw_mode().unwrap(); execute!(stdout(), LeaveAlternateScreen, cursor::Show).unwrap(); exit(0); diff --git a/src/util.rs b/src/util.rs index c5b05a3..46fd3e4 100644 --- a/src/util.rs +++ b/src/util.rs @@ -7,6 +7,16 @@ use crossterm::{ }; use std::io::{stdout, Write}; +pub fn read_yes_no(prompt: &str, default: bool) -> bool { + let options = if default { "Y/n" } else { "y/N" }; + let prompt = format!("{prompt} [{options}]: "); + match read_line(&prompt).and_then(|s| s.chars().next()) { + Some('Y' | 'y') => true, + Some('N' | 'n') => false, + _ => default, + } +} + pub fn read_line(prompt: &str) -> Option { let mut response = String::new(); let size = terminal::size().unwrap();