From 44a1d5ce9a229405f7b8667d2a34ee76b160d64c Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Fri, 4 Oct 2019 15:53:08 -0400 Subject: [PATCH] Be more robust in restoring canonical mode --- src/main.rs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 878a6a9..6162111 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,6 +22,28 @@ lazy_static! { pub static ref ORIGINAL_TERMIOS: Arc> = Arc::new(Mutex::new(get_termios(STDOUT_FILENO))); } +struct OnExit ()> { + destructor: Option, +} + +impl OnExit where T: FnOnce() -> () { + fn new(destructor: T) -> OnExit { + OnExit { + destructor: Some(destructor), + } + } +} + +impl Drop for OnExit where T: FnOnce() -> () { + fn drop(&mut self) { + if self.destructor.is_some() { + let option = self.destructor.take(); + let destructor = option.unwrap(); + destructor(); + } + } +} + fn main() -> Result<(), Error> { // Save existing Termios settings lazy_static::initialize(&ORIGINAL_TERMIOS); @@ -29,6 +51,9 @@ fn main() -> Result<(), Error> { // Disable canonical/"cooked" terminal mode enable_raw_mode(); + // Revert raw mode on exit + let _destructor = OnExit::new(disable_raw_mode); + // Initialize the editor let mut editor = Editor::new(); @@ -51,8 +76,5 @@ fn main() -> Result<(), Error> { } } - // Restore previous terminal flags before exit - disable_raw_mode(); - Ok(()) }