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 f78ca3f commit b8ca8e3
Show file tree
Hide file tree
Showing 19 changed files with 166 additions and 30 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ keywords = ["cli", "prompt", "console"]
console = "0.15"
fuzzy-matcher = "0.3"
itertools = "0.13"
lazy_static = "1.5.0"
once_cell = "1"
signal-hook = "0.3.17"
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
41 changes: 33 additions & 8 deletions examples/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,40 @@ 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");
return;
} else {
panic!("Error: {}", e);
Err(_) => "".to_string(),
// Err(e) => {
// if e.kind() == std::io::ErrorKind::Interrupted {
// println!("{}", e);
// return;
// } else {
// panic!("Error: {}", e);
// }
// }
};

loop {
println!("Chose an option: ");
let mut input = String::new();
println!("Q to quit");
println!("C to continue");
match std::io::stdin().read_line(&mut input) {
Ok(_) => match input.trim() {
"Q" | "q" => {
println!("Quitting...");
break;
}
"C" | "c" => {
println!("Continuing...");
}
_ => {
println!("Invalid option");
}
},
Err(e) => {
println!("Error: {}", e);
}
}
};
}
}
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());
}
6 changes: 5 additions & 1 deletion src/confirm.rs
Original file line number Diff line number Diff line change
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> {
// TODO

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 @@ -119,7 +122,7 @@ impl<'a> Confirm<'a> {
return self.handle_submit();
}
Key::Escape => {
self.clear()?;
self.term.show_cursor()?;
return Err(io::Error::new(io::ErrorKind::Interrupted, "user cancelled"));
}
_ => {}
Expand All @@ -130,6 +133,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
73 changes: 73 additions & 0 deletions src/ctrlc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use console::Term;
use lazy_static::lazy_static;
use signal_hook::{
consts::SIGINT,
iterator::{Handle, Signals},
};
use std::{
io::Error,
sync::{
atomic::{AtomicBool, Ordering},
Mutex, RwLock,
},
thread,
};

static INIT: AtomicBool = AtomicBool::new(false);
static INIT_LOCK: Mutex<()> = Mutex::new(());

lazy_static! {
static ref HANDLE: RwLock<Option<Handle>> = RwLock::new(None);
}

pub fn show_cursor_after_ctrlc(term: &Term) -> Result<Option<Handle>, Error> {
let t = term.clone();
set_ctrlc_handler(move || {
println!("Received Ctrl-C");
t.show_cursor().unwrap();
})
}

pub fn close_ctrlc_handle(handle: Option<Handle>) {
if let Some(handle) = handle {
handle.close();
}
}

pub fn set_ctrlc_handler<F>(mut handler: F) -> Result<Option<Handle>, Error>
where
F: FnMut() + 'static + Send,
{
let _guard = INIT_LOCK.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(move || handler())?;
{
let mut handle_guard = HANDLE.write().unwrap();
*handle_guard = Some(handle.clone());
}
Ok(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 sig in signals.forever() {
println!("Received signal {:?}", sig);
handler();
// we dont' break here and leave it
// to the user to close the handle
}
})?;
Ok(handle)
}
6 changes: 5 additions & 1 deletion src/dialog.rs
Original file line number Diff line number Diff line change
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> {
// TODO

self.term.hide_cursor()?;
loop {
self.clear()?;
let output = self.render()?;
Expand All @@ -149,7 +152,7 @@ impl<'a> Dialog<'a> {
return self.handle_submit();
}
Key::Escape => {
self.clear()?;
self.term.show_cursor()?;
return Err(io::Error::new(io::ErrorKind::Interrupted, "user cancelled"));
}
_ => {}
Expand All @@ -159,6 +162,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
7 changes: 6 additions & 1 deletion src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{
use console::{measure_text_width, Key, Term};
use termcolor::{Buffer, WriteColor};

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

/// Single line text input
Expand Down Expand Up @@ -153,6 +154,8 @@ impl<'a> Input<'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()?;
Expand All @@ -179,12 +182,14 @@ impl<'a> Input<'a> {
if self.err.is_none() {
self.term.show_cursor()?;
self.term.clear_to_end_of_screen()?;
ctrlc::close_ctrlc_handle(ctrlc_handle);
return self.handle_submit();
}
}
Key::Tab => self.handle_tab()?,
Key::Escape => {
self.clear()?;
self.term.show_cursor()?;
ctrlc::close_ctrlc_handle(ctrlc_handle);
return Err(io::Error::new(io::ErrorKind::Interrupted, "user cancelled"));
}
_ => {}
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub use spinner::SpinnerStyle;
pub use theme::Theme;

mod confirm;
mod ctrlc;
mod dialog;
mod input;
mod list;
Expand Down
4 changes: 3 additions & 1 deletion src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ impl<'a> List<'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) -> Result<(), io::Error> {
// TODO

loop {
self.clear()?;
let output = self.render()?;
Expand All @@ -148,7 +150,7 @@ impl<'a> List<'a> {
Key::ArrowRight | Key::Char('l') => self.handle_right()?,
Key::Char('/') if self.filterable => self.handle_start_filtering(),
Key::Escape => {
self.clear()?;
self.term.show_cursor()?;
return Err(io::Error::new(io::ErrorKind::Interrupted, "user cancelled"));
}
Key::Enter => {
Expand Down
Loading

0 comments on commit b8ca8e3

Please sign in to comment.