Pomodoro (editable) (#11)

This commit is contained in:
Jens K. 2024-12-12 09:00:36 +01:00 committed by GitHub
parent 709224b31f
commit 4c38ac368e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 379 additions and 67 deletions

View File

@ -7,7 +7,7 @@ use crate::{
countdown::{Countdown, CountdownWidget},
footer::Footer,
header::Header,
pomodoro::Pomodoro,
pomodoro::{Pomodoro, PomodoroWidget},
timer::{Timer, TimerWidget},
},
};
@ -18,6 +18,7 @@ use ratatui::{
layout::{Constraint, Layout, Rect},
widgets::{StatefulWidget, Widget},
};
use std::time::Duration;
use tracing::debug;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -40,22 +41,27 @@ pub struct App {
show_menu: bool,
countdown: Countdown,
timer: Timer,
pomodoro: Pomodoro,
}
impl Default for App {
fn default() -> Self {
Self {
mode: Mode::Running,
content: Content::Countdown,
content: Content::Pomodoro,
show_menu: false,
countdown: Countdown::new(
"Countdown".into(),
Clock::<clock::Countdown>::new(
10 * 60 * 1000, /* 10min in milliseconds */
TICK_VALUE_MS,
Duration::from_secs(10 * 60 /* 10min */),
Duration::from_millis(TICK_VALUE_MS),
),
),
timer: Timer::new("Timer".into(), Clock::<clock::Timer>::new(0, TICK_VALUE_MS)),
timer: Timer::new(
"Timer".into(),
Clock::<clock::Timer>::new(Duration::ZERO, Duration::from_millis(TICK_VALUE_MS)),
),
pomodoro: Pomodoro::new(),
}
}
}
@ -68,10 +74,11 @@ impl App {
pub async fn run(&mut self, mut terminal: Terminal, mut events: Events) -> Result<()> {
while self.is_running() {
if let Some(event) = events.next().await {
// Pipe events into subviews and handle 'rest' events only
match self.content {
Content::Countdown => self.countdown.update(event.clone()),
Content::Timer => self.timer.update(event.clone()),
_ => {}
Content::Pomodoro => self.pomodoro.update(event.clone()),
};
match event {
Event::Render | Event::Resize => {
@ -89,6 +96,14 @@ impl App {
self.mode != Mode::Quit
}
fn is_edit_mode(&mut self) -> bool {
match self.content {
Content::Countdown => self.countdown.is_edit_mode(),
Content::Pomodoro => self.pomodoro.is_edit_mode(),
_ => false,
}
}
fn handle_key_event(&mut self, key: KeyEvent) {
debug!("Received key {:?}", key.code);
match key.code {
@ -97,6 +112,18 @@ impl App {
KeyCode::Char('t') => self.content = Content::Timer,
KeyCode::Char('p') => self.content = Content::Pomodoro,
KeyCode::Char('m') => self.show_menu = !self.show_menu,
KeyCode::Up => {
// TODO: Pipe events into subviews properly
if !self.is_edit_mode() {
self.show_menu = true
}
}
KeyCode::Down => {
// TODO: Pipe events into subviews properly
if !self.is_edit_mode() {
self.show_menu = false
}
}
_ => {}
};
}
@ -116,7 +143,7 @@ impl AppWidget {
match state.content {
Content::Timer => TimerWidget.render(area, buf, &mut state.timer),
Content::Countdown => CountdownWidget.render(area, buf, &mut state.countdown),
Content::Pomodoro => Pomodoro::new("Pomodoro".into()).render(area, buf),
Content::Pomodoro => PomodoroWidget.render(area, buf, &mut state.pomodoro),
};
}
}

View File

@ -1,4 +1,5 @@
pub static APP_NAME: &str = env!("CARGO_PKG_NAME");
// TODO: Grab those values from `Args`
pub static TICK_VALUE_MS: u64 = 1000 / 10; // 0.1 sec in milliseconds
pub static FPS_VALUE_MS: u64 = 1000 / 60; // 60 FPS in milliseconds

View File

@ -5,27 +5,45 @@ use strum::Display;
use ratatui::{
buffer::Buffer,
layout::{Constraint, Direction, Layout, Position, Rect},
widgets::StatefulWidget,
layout::{Constraint, Layout, Position, Rect, Size},
symbols,
widgets::{Block, Borders, StatefulWidget, Widget},
};
use crate::utils::center_horizontal;
#[derive(Debug, Copy, Clone, Display, PartialEq, Eq)]
pub enum Time {
Seconds,
Minutes,
// TODO: Handle hours
// Hours,
}
#[derive(Debug, Clone, Display, PartialEq, Eq)]
pub enum Mode {
Initial,
Tick,
Pause,
Editable(
Time,
Box<Mode>, /* previous mode before starting editing */
),
Done,
}
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone)]
pub struct Clock<T> {
initial_value: u64,
tick_value: u64,
current_value: u64,
initial_value: Duration,
tick_value: Duration,
current_value: Duration,
mode: Mode,
phantom: PhantomData<T>,
}
// TODO: Change it to 23:59:59 after supporting `hours`
const MAX_EDITABLE_DURATION: Duration = Duration::from_secs(60 * 60); // 1 hour
impl<T> Clock<T> {
pub fn toggle_pause(&mut self) {
self.mode = if self.mode == Mode::Tick {
@ -35,31 +53,134 @@ impl<T> Clock<T> {
}
}
pub fn toggle_edit(&mut self) {
self.mode = match self.mode.clone() {
Mode::Editable(_, prev) => {
let p = *prev;
// special cases: Should `Mode` be updated?
// 1. `Done` -> `Initial` ?
if p == Mode::Done && self.current_value.gt(&Duration::ZERO) {
Mode::Initial
}
// 2. `_` -> `Done` ?
else if p != Mode::Done && self.current_value.eq(&Duration::ZERO) {
Mode::Done
}
// 3. `_` -> `_` (no change)
else {
p
}
}
mode => Mode::Editable(Time::Minutes, Box::new(mode)),
};
}
pub fn edit_up(&mut self) {
self.current_value = match self.mode {
Mode::Editable(Time::Seconds, _) => {
if self
.current_value
// TODO: Change it to 24:59:59 after supporting `hours`
// At the meantime: < 59:59
.lt(&MAX_EDITABLE_DURATION.saturating_sub(Duration::from_secs(1)))
{
self.current_value.saturating_add(Duration::from_secs(1))
} else {
self.current_value
}
}
Mode::Editable(Time::Minutes, _) => {
if self
.current_value
// TODO: Change it to 24:59:00 after supporting `hours`
// At the meantime: < 59:00
.lt(&MAX_EDITABLE_DURATION.saturating_sub(Duration::from_secs(60)))
{
self.current_value.saturating_add(Duration::new(60, 0))
} else {
self.current_value
}
}
_ => self.current_value,
};
}
pub fn edit_down(&mut self) {
self.current_value = match self.mode {
Mode::Editable(Time::Seconds, _) => {
self.current_value.saturating_sub(Duration::new(1, 0))
}
Mode::Editable(Time::Minutes, _) => {
self.current_value.saturating_sub(Duration::new(60, 0))
}
_ => self.current_value,
};
}
pub fn get_mode(&mut self) -> Mode {
self.mode.clone()
}
pub fn is_edit_mode(&mut self) -> bool {
matches!(self.mode, Mode::Editable(_, _))
}
pub fn edit_mode(&mut self) -> Option<Time> {
match self.mode {
Mode::Editable(time, _) => Some(time),
_ => None,
}
}
pub fn edit_next(&mut self) {
self.mode = match self.mode.clone() {
Mode::Editable(Time::Seconds, prev) => Mode::Editable(Time::Minutes, prev),
Mode::Editable(Time::Minutes, prev) => Mode::Editable(Time::Seconds, prev),
_ => self.mode.clone(),
}
}
pub fn edit_prev(&mut self) {
// as same as editing `next` value
// TODO: Update it as soon as `hours` come into play
self.edit_next()
}
pub fn reset(&mut self) {
self.mode = Mode::Initial;
self.current_value = self.initial_value;
}
fn duration(&self) -> Duration {
Duration::from_millis(self.current_value)
self.current_value
}
fn hours(&self) -> u64 {
(self.duration().as_secs() / 60 / 60) % 60
}
fn minutes(&self) -> u64 {
self.duration().as_secs() / 60
(self.duration().as_secs() / 60) % 60
}
fn seconds(&self) -> u64 {
self.duration().as_secs() % 60
}
fn tenths(&self) -> u32 {
self.duration().subsec_millis() / 100
}
pub fn is_done(&mut self) -> bool {
self.mode == Mode::Done
}
}
impl<T> fmt::Display for Clock<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:02}:{:02}.{}",
"{:02}:{:02}:{:02}.{}",
self.hours(),
self.minutes(),
self.seconds(),
self.tenths()
@ -74,7 +195,7 @@ pub struct Countdown {}
pub struct Timer {}
impl Clock<Countdown> {
pub fn new(initial_value: u64, tick_value: u64) -> Self {
pub fn new(initial_value: Duration, tick_value: Duration) -> Self {
Self {
initial_value,
tick_value,
@ -91,18 +212,18 @@ impl Clock<Countdown> {
}
}
fn check_done(&mut self) {
if self.current_value == 0 {
pub fn check_done(&mut self) {
if self.current_value.is_zero() {
self.mode = Mode::Done;
}
}
}
impl Clock<Timer> {
pub fn new(initial_value: u64, tick_value: u64) -> Self {
pub fn new(initial_value: Duration, tick_value: Duration) -> Self {
Self {
initial_value,
tick_value,
current_value: 0,
current_value: Duration::ZERO,
mode: Mode::Initial,
phantom: PhantomData,
}
@ -125,6 +246,7 @@ impl Clock<Timer> {
const DIGIT_SYMBOL: &str = "";
const DIGIT_SIZE: usize = 5;
const EDIT_BORDER_HEIGHT: usize = 1;
#[rustfmt::skip]
const DIGIT_0: [u8; DIGIT_SIZE * DIGIT_SIZE] = [
@ -225,11 +347,17 @@ const DIGIT_ERROR: [u8; DIGIT_SIZE * DIGIT_SIZE] = [
1, 1, 1, 1, 1,
];
pub struct ClockWidget<T> {
pub struct ClockWidget<T>
where
T: std::fmt::Debug,
{
phantom: PhantomData<T>,
}
impl<T> ClockWidget<T> {
impl<T> ClockWidget<T>
where
T: std::fmt::Debug,
{
pub fn new() -> Self {
Self {
phantom: PhantomData,
@ -244,10 +372,14 @@ impl<T> ClockWidget<T> {
self.get_horizontal_lengths().iter().sum()
}
pub fn get_height(&self) -> u16 {
pub fn get_digit_height(&self) -> u16 {
DIGIT_SIZE as u16
}
pub fn get_height(&self) -> u16 {
self.get_digit_height() + (EDIT_BORDER_HEIGHT as u16)
}
fn render_number(number: u64, area: Rect, buf: &mut Buffer) {
let left = area.left();
let top = area.top();
@ -281,14 +413,13 @@ impl<T> ClockWidget<T> {
});
}
fn render_digit_pair(d: u64, area: Rect, buf: &mut Buffer) {
let h = Layout::new(
Direction::Horizontal,
Constraint::from_lengths([DIGIT_SIZE as u16, 2, DIGIT_SIZE as u16]),
)
.split(area);
fn render_digit_pair(d: u64, area: Rect, buf: &mut Buffer) -> Size {
let widths = [DIGIT_SIZE as u16, 2, DIGIT_SIZE as u16];
let h = Layout::horizontal(Constraint::from_lengths(widths)).split(area);
Self::render_number(d / 10, h[0], buf);
Self::render_number(d % 10, h[2], buf);
Size::new(widths.iter().sum(), area.height)
}
fn render_colon(area: Rect, buf: &mut Buffer) {
@ -320,28 +451,57 @@ impl<T> ClockWidget<T> {
}
}
}
fn render_edit_border(mode: Mode, width: u16, area: Rect, buf: &mut Buffer) {
match mode {
Mode::Editable(Time::Seconds, _) => {
let [_, h2] = Layout::horizontal([Constraint::Fill(0), Constraint::Length(width)])
.areas(area);
Block::new()
.borders(Borders::TOP)
.border_set(symbols::border::THICK)
.render(h2, buf);
}
Mode::Editable(Time::Minutes, _) => {
let [h1, _] = Layout::horizontal([Constraint::Length(width), Constraint::Fill(0)])
.areas(area);
Block::new()
.borders(Borders::TOP)
.border_set(symbols::border::THICK)
.render(h1, buf)
}
_ => Block::new()
.borders(Borders::TOP)
.border_set(symbols::border::EMPTY)
.render(area, buf),
}
}
}
impl<T> StatefulWidget for ClockWidget<T> {
impl<T> StatefulWidget for ClockWidget<T>
where
T: std::fmt::Debug,
{
type State = Clock<T>;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
// center
let [_, h, _] = Layout::horizontal([
Constraint::Fill(0),
Constraint::Length(self.get_width()),
Constraint::Fill(0),
])
.areas(area);
let h = center_horizontal(area, Constraint::Length(self.get_width()));
let [h1, h2, h3] = Layout::new(
Direction::Horizontal,
Constraint::from_lengths(self.get_horizontal_lengths()),
)
let [v1, v2] = Layout::vertical(Constraint::from_lengths([
self.get_digit_height(),
EDIT_BORDER_HEIGHT as u16,
]))
.areas(h);
Self::render_digit_pair(state.minutes(), h1, buf);
let [h1, h2, h3] =
Layout::horizontal(Constraint::from_lengths(self.get_horizontal_lengths())).areas(v1);
let size_digits = Self::render_digit_pair(state.minutes(), h1, buf);
Self::render_colon(h2, buf);
Self::render_digit_pair(state.seconds(), h3, buf);
Self::render_edit_border(state.mode.clone(), size_digits.width - 1, v2, buf);
}
}

View File

@ -23,6 +23,10 @@ impl Countdown {
pub const fn new(headline: String, clock: Clock<clock::Countdown>) -> Self {
Self { headline, clock }
}
pub fn is_edit_mode(&mut self) -> bool {
self.clock.is_edit_mode()
}
}
impl EventHandler for Countdown {
@ -48,17 +52,17 @@ impl StatefulWidget for CountdownWidget {
type State = Countdown;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let clock = ClockWidget::new();
let headline = Line::raw(state.headline.clone());
let headline = Line::raw(state.headline.to_uppercase());
let area = center(
area,
Constraint::Length(max(clock.get_width(), headline.width() as u16)),
Constraint::Length(clock.get_height() + 2),
Constraint::Length(clock.get_height() + 1 /* height of headline */),
);
let [v1, _, v2] =
Layout::vertical(Constraint::from_lengths([clock.get_height(), 1, 1])).areas(area);
let [v1, v2] =
Layout::vertical(Constraint::from_lengths([clock.get_height(), 1])).areas(area);
clock.render(v1, buf, &mut state.clock);
headline.centered().render(v2, buf);
headline.render(v2, buf);
}
}

View File

@ -1,37 +1,157 @@
use crate::{
constants::TICK_VALUE_MS,
events::{Event, EventHandler},
utils::center,
widgets::clock::{Clock, ClockWidget, Countdown},
};
use ratatui::{
buffer::Buffer,
crossterm::event::KeyCode,
layout::{Constraint, Layout, Rect},
style::Stylize,
text::Line,
widgets::Widget,
widgets::{StatefulWidget, Widget},
};
use std::cmp::max;
use std::time::Duration;
use strum::Display;
use crate::utils::center;
static PAUSE_MS: u64 = 5 * 60 * 1000; /* 5min in milliseconds */
static WORK_MS: u64 = 25 * 60 * 1000; /* 25min in milliseconds */
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, Display, Hash, Eq, PartialEq)]
enum Mode {
Work,
Pause,
}
#[derive(Debug, Clone)]
pub struct ClockMap {
work: Clock<Countdown>,
pause: Clock<Countdown>,
}
impl ClockMap {
fn get(&mut self, mode: &Mode) -> &mut Clock<Countdown> {
match mode {
Mode::Work => &mut self.work,
Mode::Pause => &mut self.pause,
}
}
}
#[derive(Debug, Clone)]
pub struct Pomodoro {
headline: String,
mode: Mode,
clock_map: ClockMap,
}
impl Pomodoro {
pub const fn new(headline: String) -> Self {
Self { headline }
pub fn new() -> Self {
Self {
mode: Mode::Work,
clock_map: ClockMap {
work: Clock::<Countdown>::new(
Duration::from_millis(WORK_MS),
Duration::from_millis(TICK_VALUE_MS),
),
pause: Clock::<Countdown>::new(
Duration::from_millis(PAUSE_MS),
Duration::from_millis(TICK_VALUE_MS),
),
},
}
}
fn get_clock(&mut self) -> &mut Clock<Countdown> {
self.clock_map.get(&self.mode)
}
pub fn next(&mut self) {
self.mode = match self.mode {
Mode::Pause => Mode::Work,
Mode::Work => Mode::Pause,
};
}
pub fn is_edit_mode(&mut self) -> bool {
self.get_clock().is_edit_mode()
}
}
impl Widget for Pomodoro {
fn render(self, area: Rect, buf: &mut Buffer) {
let headline = Line::raw(self.headline.clone());
impl EventHandler for Pomodoro {
fn update(&mut self, event: Event) {
match event {
Event::Tick => {
self.get_clock().tick();
}
Event::Key(key) => match key.code {
KeyCode::Char('s') => {
self.get_clock().toggle_pause();
}
KeyCode::Char('e') => {
self.get_clock().toggle_edit();
}
KeyCode::Left => {
if self.get_clock().is_edit_mode() {
self.get_clock().edit_next();
} else {
// `next` is acting as same as a `prev` function, we don't have
self.next();
}
}
KeyCode::Right => {
if self.get_clock().is_edit_mode() {
self.get_clock().edit_prev();
} else {
self.next();
}
}
KeyCode::Up => {
if self.get_clock().is_edit_mode() {
self.get_clock().edit_up();
}
}
KeyCode::Down => {
if self.get_clock().is_edit_mode() {
self.get_clock().edit_down();
}
}
KeyCode::Char('r') => {
self.get_clock().reset();
}
_ => {}
},
_ => {}
}
}
}
pub struct PomodoroWidget;
impl StatefulWidget for PomodoroWidget {
type State = Pomodoro;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let clock = ClockWidget::new();
let mode_str = Line::raw(
(if let Some(edit_mode) = state.get_clock().edit_mode() {
format!("{} > edit {}", state.mode, edit_mode)
} else {
format!("{} > {}", state.mode.clone(), state.get_clock().get_mode())
})
.to_uppercase(),
);
let area = center(
area,
Constraint::Length(headline.width() as u16),
Constraint::Length(3),
Constraint::Length(max(clock.get_width(), mode_str.width() as u16)),
Constraint::Length(clock.get_height() + 1 /* height of mode_str */),
);
let [v1, _, v2] = Layout::vertical(Constraint::from_lengths([1, 1, 1])).areas(area);
let [v1, v2] =
Layout::vertical(Constraint::from_lengths([clock.get_height(), 1])).areas(area);
headline.render(v2, buf);
Line::raw("SOON").centered().italic().render(v1, buf);
clock.render(v1, buf, state.get_clock());
mode_str.render(v2, buf);
}
}

View File

@ -47,17 +47,17 @@ impl StatefulWidget for &TimerWidget {
type State = Timer;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let clock = ClockWidget::new();
let headline = Line::raw(state.headline.clone());
let headline = Line::raw(state.headline.to_uppercase());
let area = center(
area,
Constraint::Length(max(clock.get_width(), headline.width() as u16)),
Constraint::Length(clock.get_height() + 2),
Constraint::Length(clock.get_height() + 1 /* height of headline */),
);
let [v1, _, v2] =
Layout::vertical(Constraint::from_lengths([clock.get_height(), 1, 1])).areas(area);
let [v1, v2] =
Layout::vertical(Constraint::from_lengths([clock.get_height(), 1])).areas(area);
clock.render(v1, buf, &mut state.clock);
headline.centered().render(v2, buf);
headline.render(v2, buf);
}
}