Be more robust in restoring canonical mode

This commit is contained in:
Timothy Warren 2019-10-04 15:53:08 -04:00
parent 8825cdb058
commit 44a1d5ce9a
1 changed files with 25 additions and 3 deletions

View File

@ -22,6 +22,28 @@ lazy_static! {
pub static ref ORIGINAL_TERMIOS: Arc<Mutex<Termios>> = Arc::new(Mutex::new(get_termios(STDOUT_FILENO)));
}
struct OnExit<T: FnOnce() -> ()> {
destructor: Option<T>,
}
impl<T> OnExit<T> where T: FnOnce() -> () {
fn new(destructor: T) -> OnExit<T> {
OnExit {
destructor: Some(destructor),
}
}
}
impl<T> Drop for OnExit<T> 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(())
}