support auto_quit flag for timer #26

This commit is contained in:
Jimmy Wu 2023-11-30 14:29:38 +08:00
parent dc5bcd672c
commit f616555fa2
3 changed files with 32 additions and 4 deletions

View file

@ -62,6 +62,10 @@ pub enum Mode {
#[clap(long = "paused", short = 'P', takes_value = false)]
paused: bool,
/// Auto quit when time is up
#[clap(long = "quit", short = 'Q', takes_value = false)]
auto_quit: bool,
/// Command to run when the timer ends
#[clap(long, short, multiple = true, allow_hyphen_values = true)]
execute: Vec<String>,
@ -164,6 +168,7 @@ impl App {
repeat,
no_millis,
paused,
auto_quit,
execute,
} => {
let format = if *no_millis {
@ -179,6 +184,7 @@ impl App {
*repeat,
format,
*paused,
*auto_quit,
execute.to_owned(),
));
}
@ -229,6 +235,13 @@ impl App {
handle_key(w, key);
}
}
pub fn is_ended(&self) -> bool {
if let Some(ref w) = self.timer {
return w.is_finished();
}
false
}
}
fn handle_key<T: Pause>(widget: &mut T, key: KeyCode) {

View file

@ -15,6 +15,7 @@ pub struct Timer {
pub durations: Vec<Duration>,
pub titles: Vec<String>,
pub execute: Vec<String>,
auto_quit: bool,
format: DurationFormat,
passed: Duration,
started_at: Option<DateTime<Local>>,
@ -31,6 +32,7 @@ impl Timer {
repeat: bool,
format: DurationFormat,
paused: bool,
auto_quit: bool,
execute: Vec<String>,
) -> Self {
Self {
@ -40,6 +42,7 @@ impl Timer {
titles,
repeat,
execute,
auto_quit,
format,
passed: Duration::zero(),
started_at: (!paused).then(Local::now),
@ -66,6 +69,10 @@ impl Timer {
(next_checkpoint - total_passed, idx)
}
pub(crate) fn is_finished(&self) -> bool {
return self.auto_quit && !self.execute_result.borrow().is_none();
}
}
fn execute(execute: &[String]) -> String {
@ -92,11 +99,15 @@ impl Widget for &Timer {
fn render(self, area: Rect, buf: &mut Buffer) {
let (remaining_time, idx) = self.remaining_time();
let time_str = if remaining_time < Duration::zero() {
if !self.execute.is_empty() && self.execute_result.borrow().is_none() {
if self.execute_result.borrow().is_none() {
if !self.execute.is_empty() {
let result = execute(&self.execute);
*self.execute_result.borrow_mut() = Some(result);
} else {
*self.execute_result.borrow_mut() = Some("".to_owned())
}
if (remaining_time.num_milliseconds()).abs() % 1000 < 500 {
}
if remaining_time.num_milliseconds().abs() % 1000 < 500 {
return;
} else {
format_duration(Duration::zero(), self.format)

View file

@ -26,6 +26,10 @@ fn run_app<B: Backend>(
let mut last_tick = Instant::now();
loop {
if app.is_ended() {
return Ok(());
}
terminal.draw(|f| app.ui(f))?;
let timeout = tick_rate