From 0b1514d4965ce148b0ee0beccaac69fce660abb8 Mon Sep 17 00:00:00 2001 From: "Dr. Matthias Ratajczak" Date: Thu, 2 Mar 2023 17:28:56 +0100 Subject: [PATCH] refactor --- src/interval.rs | 2 +- src/pomodoro.rs | 70 ++++++++++++++++++++++++++----------------------- 2 files changed, 38 insertions(+), 34 deletions(-) diff --git a/src/interval.rs b/src/interval.rs index 833d54e..cdb834e 100644 --- a/src/interval.rs +++ b/src/interval.rs @@ -10,7 +10,7 @@ pub(crate) enum Interval { impl Interval { const FIVE_MINUTES: Duration = Duration::from_secs(5 * 60); const FIFTEEN_MINUTES: Duration = Duration::from_secs(15 * 60); - const TWENTY_FIVE_MINUTES: Duration = Duration::from_secs(25 * 60); + const TWENTY_FIVE_MINUTES: Duration = Duration::from_secs(5); pub(crate) fn default_sequence() -> [Self; 8] { [ diff --git a/src/pomodoro.rs b/src/pomodoro.rs index 5a9a28b..96c1167 100644 --- a/src/pomodoro.rs +++ b/src/pomodoro.rs @@ -62,50 +62,28 @@ impl Pomodoro { pub(crate) async fn main_loop(mut self) -> Result<()> { loop { - 'inner: loop { + 'current_interval: loop { self.show_status()?; - - tokio::select! ( - _ = sleep(ONE_SECOND) => { - if !self.paused { - self.remaining -= ONE_SECOND; - } - }, - message = self.receiver.recv() => { - if let Ok(m) = message{ - match m { - Message::Quit => { - return Ok(()); - }, - Message::TogglePause => { - self.toggle_pause(); - continue; - } - } - } else { - bail!(""); - } - } - ); + let should_quit = self.run_inner_tasks().await?; if self.remaining.is_zero() { - self.show_status()?; - break 'inner; + break 'current_interval; + } + + if should_quit { + return Ok(()); } } - self.next_interval(); - self.remaining = self.current_interval().get_duration(); - self.send_notification(self.current_interval().get_message())?; + let current_interval = self.next_interval(); + self.remaining = current_interval.get_duration(); + self.send_notification(current_interval.get_message())?; } } - fn next_interval(&mut self) { + fn next_interval(&mut self) -> Interval { self.interval_idx += 1; self.interval_idx %= self.intervals.len(); - } - - fn current_interval(&self) -> Interval { self.intervals[self.interval_idx] } @@ -115,6 +93,32 @@ impl Pomodoro { command.status()?; Ok(()) } + + async fn run_inner_tasks(&mut self) -> Result { + tokio::select! ( + _ = sleep(ONE_SECOND) => { + if !self.paused { + self.remaining = self.remaining.saturating_sub(ONE_SECOND); + } + return Ok(false); + }, + message = self.receiver.recv() => { + if let Ok(m) = message{ + match m { + Message::Quit => { + return Ok(true); + }, + Message::TogglePause => { + self.toggle_pause(); + return Ok(false); + } + } + } else { + bail!(""); + } + } + ) + } } fn format(dur: Duration) -> String {