allow setting a custom exit handler

This commit is contained in:
Lutetium-Vanadium 2021-04-19 18:56:22 +05:30
parent cf98ff42ee
commit dd4a077bdf
3 changed files with 24 additions and 3 deletions

View File

@ -74,3 +74,8 @@ where
pub fn prompt(questions: Vec<Question>) -> error::Result<Answers> {
PromptModule::new(questions).prompt_all()
}
/// Sets the exit handler to call when CTRL+C is received
pub fn set_exit_handler(handler: fn() -> !) {
ui::set_exit_handler(handler);
}

View File

@ -8,4 +8,5 @@ edition = "2018"
[dependencies]
crossterm = "0.19.0"
lazy_static = "1.4.0"
unicode-segmentation = "1.7.1"

View File

@ -1,6 +1,6 @@
#![deny(missing_docs, rust_2018_idioms)]
//! A widget based cli ui rendering library
use std::{convert::TryFrom, io};
use std::{convert::TryFrom, io, sync::Mutex};
use crossterm::{
cursor, event, execute, queue,
@ -299,11 +299,26 @@ impl<P> Input<P> {
}
}
// FIXME: maybe allow this to be changed?
fn exit() -> ! {
lazy_static::lazy_static! {
static ref EXIT_HANDLER: Mutex<fn() -> !> = Mutex::new(default_exit);
}
/// Sets the exit handler to call when CTRL+C is received
pub fn set_exit_handler(handler: fn() -> !) {
*EXIT_HANDLER.lock().unwrap() = handler;
}
fn default_exit() -> ! {
std::process::exit(130);
}
fn exit() -> ! {
match EXIT_HANDLER.lock() {
Ok(exit) => exit(),
Err(_) => default_exit(),
}
}
/// Simple helper to make sure if the code panics in between, raw mode is disabled
struct RawMode {
_private: (),