Skip to content

Commit

Permalink
fix: ctrl-c doesn't restore cursor
Browse files Browse the repository at this point in the history
  • Loading branch information
roele committed Dec 18, 2024
1 parent 5d285c2 commit 1eb2e05
Show file tree
Hide file tree
Showing 20 changed files with 208 additions and 31 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ console = "0.15"
fuzzy-matcher = "0.3"
itertools = "0.13"
once_cell = "1"
signal-hook = "0.3"
termcolor = "1"

[dev-dependencies]
Expand Down
4 changes: 2 additions & 2 deletions examples/confirm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ fn main() {
.description("This will do a thing.")
.affirmative("Yes!")
.negative("No.");
let _ = match confirm.run() {
match confirm.run() {
Ok(confirm) => confirm,
Err(e) => {
if e.kind() == std::io::ErrorKind::Interrupted {
println!("Dialog was cancelled");
println!("{}", e);
false
} else {
panic!("Error: {}", e);
Expand Down
4 changes: 2 additions & 2 deletions examples/dialog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ fn main() {
DialogButton::new("Cancel"),
])
.selected_button(1);
let _ = match dialog.run() {
match dialog.run() {
Ok(value) => value,
Err(e) => {
if e.kind() == std::io::ErrorKind::Interrupted {
println!("Dialog was cancelled");
println!("{}", e);
return;
} else {
panic!("Error: {}", e);
Expand Down
4 changes: 2 additions & 2 deletions examples/input-password.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ fn main() {
.placeholder("Enter password")
.prompt("Password: ")
.password(true);
let _ = match input.run() {
match input.run() {
Ok(value) => value,
Err(e) => {
if e.kind() == std::io::ErrorKind::Interrupted {
println!("Input cancelled");
println!("{}", e);
return;
} else {
panic!("Error: {}", e);
Expand Down
4 changes: 2 additions & 2 deletions examples/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ fn main() {
"Zack Snyder",
])
.validation(notempty_minlen);
let _ = match input.run() {
match input.run() {
Ok(value) => value,
Err(e) => {
if e.kind() == std::io::ErrorKind::Interrupted {
println!("Input cancelled");
println!("{}", e);
return;
} else {
panic!("Error: {}", e);
Expand Down
2 changes: 1 addition & 1 deletion examples/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ fn main() {
Ok(_) => {}
Err(e) => {
if e.kind() == io::ErrorKind::Interrupted {
println!("Input cancelled");
println!("{}", e);
} else {
panic!("Error: {}", e);
}
Expand Down
4 changes: 2 additions & 2 deletions examples/multiselect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ fn main() {
.option(DemandOption::new("Cheese"))
.option(DemandOption::new("Vegan Cheese"))
.option(DemandOption::new("Nutella"));
let _ = match multiselect.run() {
match multiselect.run() {
Ok(toppings) => toppings,
Err(e) => {
if e.kind() == std::io::ErrorKind::Interrupted {
println!("Input cancelled");
println!("{}", e);
return;
} else {
panic!("Error: {}", e);
Expand Down
4 changes: 2 additions & 2 deletions examples/multiselect_huge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@ fn main() {
.option(DemandOption::new("Starburst"))
.option(DemandOption::new("Twizzlers"))
.option(DemandOption::new("Milk Duds"));
let _ = match multiselect.run() {
match multiselect.run() {
Ok(value) => value,
Err(e) => {
if e.kind() == std::io::ErrorKind::Interrupted {
println!("Input cancelled");
println!("{}", e);
return;
} else {
panic!("Error: {}", e);
Expand Down
4 changes: 2 additions & 2 deletions examples/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ fn main() {
.option(DemandOption::new("EG").label("Egypt"))
.option(DemandOption::new("SA").label("Saudi Arabia"))
.option(DemandOption::new("AE").label("United Arab Emirates"));
let _ = match ms.run() {
match ms.run() {
Ok(value) => value,
Err(e) => {
if e.kind() == std::io::ErrorKind::Interrupted {
println!("Input cancelled");
println!("{}", e);
return;
} else {
panic!("Error: {}", e);
Expand Down
20 changes: 17 additions & 3 deletions examples/themes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@ use std::env::args;

use demand::{Confirm, DemandOption, Input, MultiSelect, Theme};

fn handle_run<T>(result: Result<T, std::io::Error>) -> T {
match result {
Ok(value) => value,
Err(e) => {
if e.kind() == std::io::ErrorKind::Interrupted {
println!("{}", e);
std::process::exit(0);
} else {
panic!("Error: {}", e);
}
}
}
}

fn main() {
let theme = match args().nth(1).unwrap_or_default().as_str() {
"base16" => Theme::base16(),
Expand All @@ -16,7 +30,7 @@ fn main() {
.description("Please enter your e-mail address.")
.placeholder("[email protected]")
.theme(&theme);
i.run().expect("error running input");
handle_run(i.run());

let ms = MultiSelect::new("Interests")
.description("Select your interests")
Expand All @@ -31,12 +45,12 @@ fn main() {
.option(DemandOption::new("Travel"))
.option(DemandOption::new("Sports"))
.theme(&theme);
ms.run().expect("error running multi select");
handle_run(ms.run());

let c = Confirm::new("Confirm privacy policy")
.description("Do you accept the privacy policy?")
.affirmative("Yes")
.negative("No")
.theme(&theme);
c.run().expect("error running confirm");
handle_run(c.run());
}
12 changes: 10 additions & 2 deletions src/confirm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::io::Write;
use console::{Key, Term};
use termcolor::{Buffer, WriteColor};

use crate::theme;
use crate::theme::Theme;
use crate::{ctrlc, theme};

/// Select multiple options from a list
///
Expand Down Expand Up @@ -95,9 +95,12 @@ impl<'a> Confirm<'a> {
/// This function will block until the user submits the input. If the user cancels the input,
/// an error of type `io::ErrorKind::Interrupted` is returned.
pub fn run(mut self) -> io::Result<bool> {
let ctrlc_handle = ctrlc::show_cursor_after_ctrlc(&self.term)?;

let affirmative_char = self.affirmative.to_lowercase().chars().next().unwrap();
let negative_char = self.negative.to_lowercase().chars().next().unwrap();
self.term.clear_line()?;
self.term.hide_cursor()?;
loop {
self.clear()?;
let output = self.render()?;
Expand All @@ -109,17 +112,21 @@ impl<'a> Confirm<'a> {
Key::ArrowRight | Key::Char('l') => self.handle_right(),
Key::Char(c) if c == affirmative_char => {
self.selected = true;
ctrlc_handle.close();
return self.handle_submit();
}
Key::Char(c) if c == negative_char => {
self.selected = false;
ctrlc_handle.close();
return self.handle_submit();
}
Key::Enter => {
ctrlc_handle.close();
return self.handle_submit();
}
Key::Escape => {
self.clear()?;
self.term.show_cursor()?;
ctrlc_handle.close();
return Err(io::Error::new(io::ErrorKind::Interrupted, "user cancelled"));
}
_ => {}
Expand All @@ -130,6 +137,7 @@ impl<'a> Confirm<'a> {
fn handle_submit(mut self) -> io::Result<bool> {
self.term.clear_to_end_of_screen()?;
self.clear()?;
self.term.show_cursor()?;
let output = self.render_success()?;
self.term.write_all(output.as_bytes())?;
Ok(self.selected)
Expand Down
102 changes: 102 additions & 0 deletions src/ctrlc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
use console::Term;
use once_cell::sync::Lazy;
use signal_hook::{
consts::SIGINT,
iterator::{Handle, Signals},
};
use std::{
io::Error,
sync::{
atomic::{AtomicBool, Ordering},
Mutex, RwLock,
},
thread,
};

static MUTEX: Mutex<()> = Mutex::new(());
static INIT: AtomicBool = AtomicBool::new(false);
static HANDLE: Lazy<RwLock<CtrlcHandle>> = Lazy::new(|| RwLock::new(CtrlcHandle(None)));

#[derive(Clone)]
pub struct CtrlcHandle(Option<Handle>);

impl CtrlcHandle {
pub fn close(&self) {
if let Some(handle) = &self.0 {
handle.close();
}
}
}

/// Show cursor after Ctrl+C is pressed
///
/// The caller should call the close method of the returned handle to release the resources
///
/// # Arguments
///
/// * `term` - The terminal to show the cursor
///
/// # Returns
///
/// * `CtrlcHandle` - The handle to release the resources
///
/// # Errors
///
/// * `Error` - If failed to set the Ctrl+C handler
///
pub fn show_cursor_after_ctrlc(term: &Term) -> Result<CtrlcHandle, Error> {
let t = term.clone();
set_ctrlc_handler(move || {
let _ = t.show_cursor();
})
}

/// Set Ctrl+C handler
///
/// The caller should call the close method of the returned handle to release the resources
///
/// # Arguments
///
/// * `handler` - The handler to be called when Ctrl+C is pressed
///
/// # Returns
///
/// * `Result<Option<CtrlcHandle>, Error>` - The handle to release the resources
///
/// # Errors
/// * `Error` - If failed to set the Ctrl+C handler
///
pub fn set_ctrlc_handler<F>(handler: F) -> Result<CtrlcHandle, Error>
where
F: FnMut() + 'static + Send,
{
let _mutex = MUTEX.lock();
if INIT.load(Ordering::Relaxed) {
let handle_guard = HANDLE.read().unwrap();
return Ok(handle_guard.clone());
}
INIT.store(true, Ordering::Relaxed);

let handle = set_ctrlc_handler_internal(handler)?;
{
let mut handle_guard = HANDLE.write().unwrap();
*handle_guard = CtrlcHandle(Some(handle.clone()));
}
Ok(CtrlcHandle(Some(handle)))
}

fn set_ctrlc_handler_internal<F>(mut handler: F) -> Result<Handle, Error>
where
F: FnMut() + 'static + Send,
{
let mut signals = Signals::new([SIGINT])?;
let handle = signals.handle();
thread::Builder::new()
.name("ctrl-c".into())
.spawn(move || {
for _ in signals.forever() {
handler();
}
})?;
Ok(handle)
}
20 changes: 20 additions & 0 deletions src/ctrlc_stub.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use std::io::Error;

use console::Term;

pub struct CtrlcHandle(Option<()>);

impl CtrlcHandle {
pub fn close(&self) {}
}

pub fn show_cursor_after_ctrlc(_term: &Term) -> Result<CtrlcHandle, Error> {
Ok(CtrlcHandle(None))
}

pub fn set_ctrlc_handler<F>(handler: F) -> Result<CtrlcHandle, Error>
where
F: FnMut() + 'static + Send,
{
Ok(CtrlcHandle(None))
}
11 changes: 9 additions & 2 deletions src/dialog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::io::Write;
use console::{Key, Term};
use termcolor::{Buffer, WriteColor};

use crate::theme;
use crate::theme::Theme;
use crate::{ctrlc, theme};

#[derive(Clone, Debug, Default, PartialEq)]
/// A button to select in a dialog
Expand Down Expand Up @@ -131,6 +131,9 @@ impl<'a> Dialog<'a> {
/// This function will block until the user submits the input. If the user cancels the input,
/// an error of type `io::ErrorKind::Interrupted` is returned.
pub fn run(mut self) -> io::Result<String> {
let ctrlc_handle = ctrlc::show_cursor_after_ctrlc(&self.term)?;

self.term.hide_cursor()?;
loop {
self.clear()?;
let output = self.render()?;
Expand All @@ -143,13 +146,16 @@ impl<'a> Dialog<'a> {
Key::Char(c) if self.buttons.iter().any(|b| b.key == c) => {
self.selected_button_idx =
self.buttons.iter().position(|b| b.key == c).unwrap();
ctrlc_handle.close();
return self.handle_submit();
}
Key::Enter => {
ctrlc_handle.close();
return self.handle_submit();
}
Key::Escape => {
self.clear()?;
self.term.show_cursor()?;
ctrlc_handle.close();
return Err(io::Error::new(io::ErrorKind::Interrupted, "user cancelled"));
}
_ => {}
Expand All @@ -159,6 +165,7 @@ impl<'a> Dialog<'a> {

fn handle_submit(mut self) -> io::Result<String> {
self.clear()?;
self.term.show_cursor()?;
let output = self.render_success()?;
self.term.write_all(output.as_bytes())?;
let result = if !self.buttons.is_empty() {
Expand Down
Loading

0 comments on commit 1eb2e05

Please sign in to comment.