49 Commits

Author SHA1 Message Date
jk
1d542799f6 start workflow by release/* branches only
but not by tags to avoid overriding releases.
2025-07-03 10:50:14 +02:00
jk
cc656b6ffe update CHANGELOG 2025-07-03 10:48:23 +02:00
jk
936d82eb94 bump v1.3.1 2025-07-03 10:48:05 +02:00
jk
5bc37f005f lint again
in addition to #88, especially 78f5269
2025-06-28 11:49:21 +02:00
Jens Krause
bfa40fd8f1 Rust 1.88.0 (#85)
* Rust 1.88.0

* nix flake update

* cargo upgrade

* lint

all `uninlined_format_args` related
@see https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args
2025-06-28 11:39:22 +02:00
Jens Krause
93a3cde396 Rust 1.87.0 (#84)
* Rust 1.87.0

* nix flake update

* update CHANGELOG

* cargo upgrade

name         old req compatible latest new req
====         ======= ========== ====== =======
color-eyre   0.6.2   0.6.5      0.6.5  0.6.5
tokio        1.41.1  1.45.1     1.45.1 1.45.1
tokio-stream 0.1.16  0.1.17     0.1.17 0.1.17
tokio-util   0.7.12  0.7.15     0.7.15 0.7.15
clap         4.5.23  4.5.39     4.5.39 4.5.39
time         0.3.37  0.3.41     0.3.41 0.3.41
notify-rust  4.11.4  4.11.7     4.11.7 4.11.7
thiserror    2.0.11  2.0.12     2.0.12 2.0.12
2025-06-09 17:00:31 +02:00
Jens Krause
d27587a44a fix(pomodoro): ctrl+r resets rounds + both clocks (#83) 2025-05-20 10:01:29 +02:00
Jens Krause
5f4c5bb8ed (pomodoro) reset active clock only (#82)
It reverts changes of cc35f20f3e
2025-05-13 11:00:56 +02:00
Jens Krause
44af71c01c (args) set content by given duration (#81) 2025-05-12 12:14:27 +02:00
Jens Krause
c370d3096b Prepare v1.3.0 (#80)
* Prepare v1.3.0
* readme: fix keybindings
* update changelog
2025-05-06 11:46:29 +02:00
jk
aae5c38cd6 fix(footer): hide option to save initial value
for timer. Available 4 pomodoro + countdown only.
2025-05-06 11:25:29 +02:00
jk
5ad09b9848 (demo) update menu 2025-05-02 12:52:35 +02:00
Jens Krause
52ed8267be (pomodoro/countdown) Change initial value (#79)
- While editing, an user can apply changes as a new initial value (pomodoro/countdown only).
- New keybinding: `[^s]save initial value` 
- Update keybinding: `[s]ave changes` (instead of `[Enter]`)
- Refactor event handling to re-structure `edit` / `non-edit` modes.
- Refactor footer to reflect latest keybindings
2025-05-02 12:39:26 +02:00
jk
6b068bbd09 fix(pomodoro) add empty line to keep content
centered vertically comparing to other views (which have one label below the clock only)

In addition to #75.
2025-04-30 14:27:30 +02:00
Jens Krause
c96432779a (readme) add keybindings + toc (#78)
* (readme) add keybindings + toc
* update LICENSE
2025-04-30 14:19:13 +02:00
Jens Krause
509cf73cdd (flake) use alsa-lib-with-plugins (#77)
by following an idea from @camuward mentioned here https://github.com/143mailliw/muzak/pull/28#issuecomment-2833601152

Incl. another `nix flake update`.
2025-04-30 12:12:03 +02:00
Jens Krause
e6291a3131 Update keybindings (#76)
* (pomodoro) reset both clocks at once

* quit app by pressing `q` only

* (countdown) enter/esc keybindings

* (timer) enter/esc keybindings

* (pomodoro) enter/esc keybindings

* update footer label

* fix(coundown): don't reset elapsed clock

while skipping editing changes

* fix(clock): order of actions matters for ESC

handling. Set `pause` instead of `initial` mode while toggeling back.

* fix(timer): order of actions matters (ESC key)

* (footer) update order, lowercase standard keys
2025-04-30 11:11:33 +02:00
Jens Krause
90d9988e7a (pomodoro) count WORK rounds (#75) 2025-04-29 16:20:02 +02:00
Jens Krause
028a067419 Prepare v1.2.1 (#74) 2025-04-17 12:26:13 +02:00
jk
675428cfb0 Update README 2025-04-17 08:31:40 +02:00
Jens Krause
28c5d7194c Rust 1.86.0 (#73) 2025-04-13 21:37:47 +02:00
Jens Krause
5b445afe25 fix(countdown): reset MET while editing by local time (#72) 2025-04-13 21:17:56 +02:00
jk
beb12d5ec2 just: run with args 2025-04-13 19:19:46 +02:00
Jens Krause
d9399eafc9 fix(countdown): Reset MET if countdown is set by cli arguments (#71)
* fix: Reset MET if countdown is set by args

* update CHANGELOG
2025-03-03 12:21:17 +01:00
Jens Krause
ffad78e093 fix(just): group commands (#70) 2025-02-26 14:58:54 +01:00
jk
e7a5a1b2da exclude files for packaging 2025-02-26 12:31:18 +01:00
Jens Krause
6f0df4d488 Prepare v1.2.0 (#69)
* prepare v1.2.0

* update README

* update justfile
2025-02-26 12:11:54 +01:00
Jens Krause
3d9b235f12 Rust 1.85.0 + Rust 2024 Edition (#68)
- Add `rust-toolchain.toml`
- Refactor `flake` to consider `rust-toolchain.toml`, especially Rust version
- `just`: Add run-sound command
- Ignore sound files
- Format
2025-02-25 20:30:20 +01:00
jk
e094d7d81b feat(logging): add --log arg to enable logs
and/or to pass a custom log directory.
2025-02-06 20:33:52 +01:00
Jens Krause
843c4d019d set_panic_hook (#67) 2025-02-06 11:16:04 +01:00
Jens Krause
e95ecb9e9c feat(notification): Animate (blink) clock entering done mode (#65)
Optional.
2025-02-05 19:29:56 +01:00
Jens Krause
886deb3311 fix(notification): remove callbacks in favour of mpsc messaging (#64) 2025-02-05 13:35:24 +01:00
Jens Krause
7ff167368d --features sound (#63)
to enable `sound` notification for local builds only. Needed to avoid
endless issues by building the app for different platforms. Sound
support can be hard.
2025-02-04 17:39:50 +01:00
Jens Krause
a54b1b409a feat(clock): sound notification (experimental) (#62) 2025-02-04 17:28:41 +01:00
Jens Krause
8f50bc5fc6 AppEvent (#61)
Extend `events` to provide a `mpsc` channel to send `AppEvent`'s from
anywhere in the app straight to the `App`.
2025-02-04 15:05:02 +01:00
Jens Krause
d3c436da0b feat: native desktop notifications (experimental) (#59)
* desktop notification by entering `Mode::DONE` for `countdown` and `pomodoro`

* remove redundant `on_done_called` check

* remove build warning (release only)

* log notification errors

* cli arg to enable desktop notifications

* persistant notification settings

* ctrl shortcut

* update changelog

* max timer notification
2025-01-28 19:28:34 +01:00
jk
97787f718d remove editor settings (zed) 2025-01-26 18:49:14 +01:00
Jens Krause
557fcf95f0 Prepare v1.1.0 (#58) 2025-01-22 10:55:20 +01:00
Jens Krause
ec18da0664 fix(ci): remove magic nix cache action (#57) 2025-01-22 09:56:28 +01:00
Jens Krause
59c99f4f5c fix(build): statically linked binaries for linux (#55) 2025-01-22 09:43:51 +01:00
Jens Krause
6d2bf5ac09 Edit countdown by local time (#49) 2025-01-13 18:44:56 +01:00
Jens Krause
b1efb1eb62 rust 1.84, update deps (#48)
- `nix flake update`
- `cargo update`
2025-01-11 16:48:37 +01:00
Jens Krause
4ee5d7b4e9 Prepare v1.0.0 (#47)
* update README
* update CHANGELOG
* update demo
* bump v1.0.0
2025-01-10 16:36:57 +01:00
Jens Krause
9ea9f88266 feat(countdown): persist elapsed time (#46) 2025-01-10 16:01:03 +01:00
Jens Krause
c8af76c9e5 feat(countdown): rocket countdown (#45) 2025-01-08 18:52:18 +01:00
Jens Krause
468b4a5abf simplify style settings, improve naming (#44)
* simplify style settings by passing `style` directly to Widgets. No need to store it in `state` of widgets.
* remove unneeded things
* naming (state vs. widgets)
2025-01-07 19:02:57 +01:00
Jens Krause
8603a823e4 fix(footer): 12-hour format incl. tests (#43) 2025-01-06 19:22:02 +01:00
Jens Krause
94bdeeab11 feat(footer): show local time (#42) 2025-01-06 18:31:22 +01:00
Orhun Parmaksız
66c6d7fc46 docs: Add instructions for installing from the AUR (#41) 2025-01-06 09:06:15 +01:00
45 changed files with 4057 additions and 794 deletions

View File

@@ -12,7 +12,6 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main - uses: DeterminateSystems/nix-installer-action@main
- uses: DeterminateSystems/magic-nix-cache-action@main
- name: Check formatting - name: Check formatting
run: nix develop --command cargo fmt --all -- --check run: nix develop --command cargo fmt --all -- --check
- name: Run clippy - name: Run clippy
@@ -25,7 +24,6 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main - uses: DeterminateSystems/nix-installer-action@main
- uses: DeterminateSystems/magic-nix-cache-action@main
- name: Run tests - name: Run tests
run: nix develop --command cargo test run: nix develop --command cargo test
@@ -34,6 +32,5 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main - uses: DeterminateSystems/nix-installer-action@main
- uses: DeterminateSystems/magic-nix-cache-action@main
- name: Build project - name: Build project
run: nix build .#timr run: nix build .#timr

View File

@@ -4,8 +4,6 @@ on:
push: push:
branches: branches:
- "release/**" - "release/**"
tags:
- "v*"
jobs: jobs:
get-version: get-version:
@@ -31,7 +29,7 @@ jobs:
- os: ubuntu-latest - os: ubuntu-latest
os_target: linux os_target: linux
binary_name: timr-tui binary_name: timr-tui
arch: x86_64 # `x86_64` by default arch: x86_64 # based on target 'x86_64-unknown-linux-musl' defined by `CARGO_BUILD_TARGET` in flake.nix
- os: ubuntu-latest - os: ubuntu-latest
os_target: windows os_target: windows
binary_name: timr-tui.exe binary_name: timr-tui.exe
@@ -43,14 +41,17 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main - uses: DeterminateSystems/nix-installer-action@main
- uses: DeterminateSystems/magic-nix-cache-action@main
- name: Build (windows) - name: Build (windows)
if: matrix.os_target == 'windows' if: matrix.os_target == 'windows'
run: nix build .#windows run: nix build .#windows
- name: Build (linux/macos) - name: Build (linux)
if: matrix.os_target != 'windows' if: matrix.os_target == 'linux'
run: nix build .#linuxStatic
- name: Build (macos)
if: matrix.os_target == 'macos'
run: nix build run: nix build
- name: Copy artifact - name: Copy artifact

3
.gitignore vendored
View File

@@ -18,3 +18,6 @@ result/**/*
#.idea/ #.idea/
# #
.direnv .direnv
# ignore (possible) sound files
**/*.{mp3,wav}

View File

@@ -1 +1,2 @@
style_edition = "2024"
reorder_imports = true reorder_imports = true

View File

@@ -1,30 +0,0 @@
// Folder-specific settings
//
// For a full list of overridable settings, and general information on folder-specific settings,
// see the documentation: https://zed.dev/docs/configuring-zed#settings-files
{
"format_on_save": "on",
"formatter": "language_server",
"lsp": {
"rust-analyzer": {
"initialization_options": {
"check": {
"command": "clippy" // rust-analyzer.check.command (default: "check")
}
}
}
},
"languages": {
"Nix": {
"formatter": {
"external": {
"command": "alejandra",
"arguments": [
"-q"
]
}
},
"format_on_save": "on"
}
}
}

View File

@@ -1,5 +1,89 @@
# Changelog # Changelog
## v1.3.1 - 2025-07-03
### Features
- (args) set `content` by given duration [#81](https://github.com/sectore/timr-tui/pull/81)
### Fixes
- (pomodoro) `ctrl+r` resets rounds AND both clocks [#83](https://github.com/sectore/timr-tui/pull/83)
- (pomodoro) reset active clock only [#82](https://github.com/sectore/timr-tui/pull/82)
### Misc.
- (deps) Rust 1.88.0 [#85](https://github.com/sectore/timr-tui/pull/85)
## v1.3.0 - 2025-05-06
###
- (pomodoro) Count WORK rounds [#75](https://github.com/sectore/timr-tui/pull/75), [6b068bb](https://github.com/sectore/timr-tui/commit/6b068bbd094d9ec1a36b47598fadfc71296d9590)
- (pomodoro/countdown) Change initial value [#79](https://github.com/sectore/timr-tui/pull/79), [aae5c38](https://github.com/sectore/timr-tui/commit/aae5c38cd6a666d5ba418b12fb67879a2146b9a2)
### Changes
- Update keybindings [#76](https://github.com/sectore/timr-tui/pull/76)
### Misc.
- (flake) use alsa-lib-with-plugins [#77](https://github.com/sectore/timr-tui/pull/77)
- (readme) add keybindings + toc [#78](https://github.com/sectore/timr-tui/pull/78)
## v1.2.1 - 2025-04-17
### Fixes
- (countdown) Reset `Mission Elapsed Time (MET)` if `countdown` is set by _cli arguments_ [#71](https://github.com/sectore/timr-tui/pull/71)
- (countdown) Reset `Mission Elapsed Time (MET)` while setting `countdown` by _local time_ [#72](https://github.com/sectore/timr-tui/pull/72)
### Misc.
- (deps) Use latest `Rust 1.86` [#73](https://github.com/sectore/timr-tui/pull/73)
- (cargo) Exclude files for packaging [e7a5a1b](https://github.com/sectore/timr-tui/commit/e7a5a1b2da7a7967f2602a0b92f391ac768ca638)
- (just) `group` commands [#70](https://github.com/sectore/timr-tui/pull/70)
## v1.2.0 - 2025-02-26
### Features
- (notification) Clock animation (blink) by reaching `done` mode (optional) [#65](https://github.com/sectore/timr-tui/pull/65)
- (notification) Native desktop notification (optional, experimental) [#59](https://github.com/sectore/timr-tui/pull/59)
- (notification) Sound notification (optional, experimental, available in local build only) [#62](https://github.com/sectore/timr-tui/pull/62)
- (logging) Add `--log` arg to enable logs [e094d7d](https://github.com/sectore/timr-tui/commit/e094d7d81b99f58f0d3bc50124859a4e1f6dbe4f)
### Misc.
- (refactor) Extend event handling for using a `mpsc` channel to send `AppEvent`'s from anywhere. [#61](https://github.com/sectore/timr-tui/pull/61)
- (extension) Use `set_panic_hook` for better error handling [#67](https://github.com/sectore/timr-tui/pull/67)
- (deps) Use latest `Rust 1.85` and `Rust 2024 Edition`. Refactor `flake` to consider `rust-toolchain.toml` etc. [#68](https://github.com/sectore/timr-tui/pull/68)
## v1.1.0 - 2025-01-22
### Features
- (countdown) Edit countdown by local time [#49](https://github.com/sectore/timr-tui/pull/49)
### Fixes
- (ci) Build statically linked binaries for Linux [#55](https://github.com/sectore/timr-tui/pull/55)
- (ci) Remove magic nix cache action (#57) [#56](https://github.com/sectore/timr-tui/issues/56)
### Misc.
- (deps) Latest Rust 1.84, update deps [#48](https://github.com/sectore/timr-tui/pull/48)
## v1.0.0 - 2025-01-10
Happy `v1.0.0` 🎉
### Features
- (countdown) Mission Elapsed Time ([MET](https://en.wikipedia.org/wiki/Mission_Elapsed_Time)). [#45](https://github.com/sectore/timr-tui/pull/45), [#46](https://github.com/sectore/timr-tui/pull/46)
- (footer) Local time. Optional and with custom formats. [#42](https://github.com/sectore/timr-tui/pull/42), [#43](https://github.com/sectore/timr-tui/pull/43)
- (docs) More installation instructions: Cargo, AUR (Arch Linux) [#41](https://github.com/sectore/timr-tui/pull/41), pre-built release binaries (Linux, macOS, Windows) [#47](https://github.com/sectore/timr-tui/pull/47)
## v0.9.0 - 2025-01-03 ## v0.9.0 - 2025-01-03
Initial version. Initial version.
@@ -8,5 +92,6 @@ Initial version.
- Add `Pomodoro`, `Timer`, `Countdown` - Add `Pomodoro`, `Timer`, `Countdown`
- Persist application state - Persist application state
- Change styles - Custom styles for digits
- Toggle deciseconds
- CLI - CLI

1915
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,28 +1,41 @@
[package] [package]
name = "timr-tui" name = "timr-tui"
version = "0.9.0" version = "1.3.1"
description = "TUI to organize your time: Pomodoro, Countdown, Timer." description = "TUI to organize your time: Pomodoro, Countdown, Timer."
edition = "2021" edition = "2024"
rust-version = "1.82.0" # Reminder: Always keep `channel` in `rust-toolchain.toml` in sync with `rust-version`.
rust-version = "1.88.0"
homepage = "https://github.com/sectore/timr-tui" homepage = "https://github.com/sectore/timr-tui"
repository = "https://github.com/sectore/timr-tui" repository = "https://github.com/sectore/timr-tui"
readme = "README.md" readme = "README.md"
license = "MIT" license = "MIT"
keywords = ["tui", "timer", "countdown", "pomodoro"] keywords = ["tui", "timer", "countdown", "pomodoro"]
categories = ["command-line-utilities"] categories = ["command-line-utilities"]
exclude = [".github/*", "demo/*.tape", "result/*", "*.mp3"]
[dependencies] [dependencies]
ratatui = "0.29.0" ratatui = "0.29.0"
crossterm = { version = "0.28.1", features = ["event-stream", "serde"] } crossterm = { version = "0.28.1", features = ["event-stream", "serde"] }
color-eyre = "0.6.2" color-eyre = "0.6.5"
futures = "0.3" futures = "0.3"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
strum = { version = "0.26.3", features = ["derive"] } strum = { version = "0.26.3", features = ["derive"] }
tokio = { version = "1.41.1", features = ["full"] } tokio = { version = "1.45.1", features = ["full"] }
tokio-stream = "0.1.16" tokio-stream = "0.1.17"
tokio-util = "0.7.12" tokio-util = "0.7.15"
tracing = "0.1.41" tracing = "0.1.41"
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] } tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
directories = "5.0.1" directories = "5.0.1"
clap = { version = "4.5.23", features = ["derive"] } clap = { version = "4.5.40", features = ["derive"] }
time = { version = "0.3.41", features = ["formatting", "local-offset"] }
notify-rust = "4.11.7"
rodio = { version = "0.20.1", features = [
"symphonia-mp3",
"symphonia-wav",
], default-features = false, optional = true }
thiserror = { version = "2.0.12", optional = true }
[features]
sound = ["dep:rodio", "dep:thiserror"]

View File

@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2024 Jens K. Copyright (c) 2024-2025 Jens Krause
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

195
README.md
View File

@@ -6,11 +6,22 @@ TUI to organize your time: Pomodoro, Countdown, Timer.
- `[c]ountdown` Use it for your workout, yoga session, meditation, handstand or whatever. - `[c]ountdown` Use it for your workout, yoga session, meditation, handstand or whatever.
- `[p]omodoro` Organize your working time to be focused all the time by following the [Pomodoro Technique](https://en.wikipedia.org/wiki/Pomodoro_Technique). - `[p]omodoro` Organize your working time to be focused all the time by following the [Pomodoro Technique](https://en.wikipedia.org/wiki/Pomodoro_Technique).
It's built with [`Ratatui`](https://ratatui.rs/) written in [Rust 🦀](https://www.rust-lang.org/). Built with [Ratatui](https://ratatui.rs/) / [Rust 🦀](https://www.rust-lang.org/).
# Table of Contents
- [Preview](./#preview)
- [CLI](./#cli)
- [Keybindings](./#keybindings)
- [Installation](./#installation)
- [Development](./#development)
- [Misc](./#misc)
- [License](./#license)
# Preview # Preview
_Side note:_ Theme colors depend on your terminal preferences. _(theme depends on your terminal preferences)_
## Pomodoro ## Pomodoro
@@ -48,6 +59,18 @@ _Side note:_ Theme colors depend on your terminal preferences.
<img alt="menu" src="demo/menu.gif" /> <img alt="menu" src="demo/menu.gif" />
</a> </a>
## Local time (footer)
<a href="demo/local-time.gif">
<img alt="menu" src="demo/local-time.gif" />
</a>
## Mission Elapsed Time ([MET](https://en.wikipedia.org/wiki/Mission_Elapsed_Time))
<a href="demo/countdown-met.gif">
<img alt="menu" src="demo/countdown-met.gif" />
</a>
# CLI # CLI
```sh ```sh
@@ -56,33 +79,114 @@ timr-tui --help
Usage: timr-tui [OPTIONS] Usage: timr-tui [OPTIONS]
Options: Options:
-c, --countdown <COUNTDOWN> Countdown time to start from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss' [default: 10:00] -c, --countdown <COUNTDOWN> Countdown time to start from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss'
-w, --work <WORK> Work time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss' [default: 25:00] -w, --work <WORK> Work time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss'
-p, --pause <PAUSE> Pause time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss' [default: 5:00] -p, --pause <PAUSE> Pause time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss'
-d, --decis Wether to show deciseconds or not. [default: false] -d, --decis Show deciseconds.
-m, --mode <MODE> Mode to start with. [possible values: countdown, timer, pomodoro] [default: timer] -m, --mode <MODE> Mode to start with. [possible values: countdown, timer, pomodoro]
--menu Whether to open the menu or not. -s, --style <STYLE> Style to display time with. [possible values: full, light, medium, dark, thick, cross, braille]
-s, --style <STYLE> Style to display time with. [possible values: full, light, medium, dark, thick, cross, braille] [default: full] --menu Open the menu.
-r, --reset Reset stored values to default. -r, --reset Reset stored values to default values.
-n, --notification <NOTIFICATION> Toggle desktop notifications. Experimental. [possible values: on, off]
--blink <BLINK> Toggle blink mode to animate a clock when it reaches its finished mode. [possible values: on, off]
--log [<LOG>] Directory to store log file. If not set, standard application log directory is used (check README for details).
-h, --help Print help -h, --help Print help
-V, --version Print version -V, --version Print version
``` ```
Extra option (if `--features sound` is enabled by local build only):
```sh
--sound <SOUND> Path to sound file (.mp3 or .wav) to play as notification. Experimental.
```
# Keybindings
## Menu
| Key | Description |
| --- | --- |
| <kbd>↑</kbd> / <kbd>↓</kbd> or <kbd>m</kbd> | Toggle menu |
## Screens
| Key | Description |
| --- | --- |
| <kbd>p</kbd> | Pomodoro |
| <kbd>c</kbd> | Countdown |
| <kbd>t</kbd> | Timer |
## Controls
| Key | Description |
| --- | --- |
| <kbd>s</kbd> | start |
| <kbd>r</kbd> | reset |
| <kbd>e</kbd> | enter edit mode |
| <kbd>q</kbd> | quit |
**In `edit` mode only:**
| Key | Description |
| --- | --- |
| <kbd>s</kbd> | save changes |
| <kbd>Esc</kbd> | skip changes |
| <kbd>←</kbd> or <kbd>→</kbd> | change selection |
| <kbd>↑</kbd> | edit to go up |
| <kbd>↓</kbd> | edit to go down |
**In `Pomodoro` screen only**
| Key | Description |
| --- | --- |
| <kbd>←</kbd> or <kbd>→</kbd> | switch work/pause |
| <kbd>^r</kbd> | reset round |
| <kbd>^s</kbd> | save initial value |
**In `Countdown` screen only:**
| Key | Description |
| --- | --- |
| <kbd>^e</kbd> | edit by local time |
| <kbd>^s</kbd> | save initial value |
## Appearance
| Key | Description |
| --- | --- |
| <kbd>,</kbd> | toggle styles |
| <kbd>.</kbd> | toggle deciseconds |
| <kbd>:</kbd> | toggle local time in footer |
# Installation # Installation
From [crates.io](https://crates.io/crates/timr-tui) run: ## Cargo
### From [crates.io](https://crates.io/crates/timr-tui)
```sh ```sh
cargo install timr-tui cargo install timr-tui
``` ```
Latest version from git repository: ### From GitHub repository
```sh ```sh
cargo install --git https://github.com/sectore/timr-tui cargo install --git https://github.com/sectore/timr-tui
``` ```
# Build from source 🔧 ## Arch Linux
Install [from the AUR](https://aur.archlinux.org/packages/timr/):
```sh
paru -S timr
```
## Release binaries
Pre-built artifacts are available to download from [latest GitHub release](https://github.com/sectore/timr-tui/releases).
# Development
## Requirements ## Requirements
@@ -92,7 +196,6 @@ cargo install --git https://github.com/sectore/timr-tui
If you have [`direnv`](https://direnv.net) installed, run `direnv allow` once to install dependencies. In other case run `nix develop`. If you have [`direnv`](https://direnv.net) installed, run `direnv allow` once to install dependencies. In other case run `nix develop`.
### Non Nix users ### Non Nix users
- [`Rust`](https://www.rust-lang.org/learn/get-started) - [`Rust`](https://www.rust-lang.org/learn/get-started)
@@ -103,34 +206,62 @@ If you have [`direnv`](https://direnv.net) installed, run `direnv allow` once to
### Commands ### Commands
```sh ```sh
just --list just
Available recipes: Available recipes:
build # build app default # list commands
b # alias for `build`
default [build]
format # format files build # build app [alias: b]
f # alias for `format`
lint # lint [demo]
l # alias for `lint` demo-blink # build demo: blink animation [alias: db]
run # run app demo-countdown # build demo: countdown [alias: dc]
r # alias for `run` demo-countdown-met # build demo: countdown + met [alias: dcm]
test # run tests demo-decis # build demo: deciseconds [alias: dd]
t # alias for `test` demo-local-time # build demo: local time [alias: dlt]
demo-menu # build demo: menu [alias: dm]
demo-pomodoro # build demo: pomodoro [alias: dp]
demo-rocket-countdown # build demo: rocket countdown [alias: drc]
demo-style # build demo: styles [alias: ds]
demo-timer # build demo: timer [alias: dt]
[dev]
run # run app [alias: r]
run-args args # run app with arguments. It expects arguments as a string (e.g. "-c 5:00"). [alias: ra]
run-sound path # run app while sound feature is enabled. It expects a path to a sound file. [alias: rs]
run-sound-args path args # run app while sound feature is enabled by adding a path to a sound file and other arguments as string (e.g. "-c 5:00"). [alias: rsa]
[misc]
format # format files [alias: f]
lint # lint [alias: l]
[test]
test # run tests [alias: t]
``` ```
### Build ### Build
- Linux - Linux
```sh ```sh
nix build nix build
# or for bulding w/ statically linked binaries
nix build .#linuxStatic
``` ```
- Windows (cross-compilation) - Windows (cross-compilation)
```sh ```sh
nix build .#windows nix build .#windows
``` ```
### Run tests
```sh
cargo test
```
# Misc. # Misc.
## Persistant app state ## Persistant app state
@@ -148,13 +279,21 @@ C:/Users/{user}/AppData/Local/timr-tui/data/app.data
## Logs ## Logs
In `debug` mode only. Locations: To get log output, start the app by passing `--log` to `timr-tui`. See [CLI](./#cli) for details.
Logs will be stored in an `app.log` file at following locations:
```sh ```sh
# Linux # Linux
~/.local/state/timr/logs/app.log ~/.local/state/timr-tui/logs/app.log
# macOS # macOS
/Users/{user}/Library/Application Support/timr-tui/logs/app.log /Users/{user}/Library/Application Support/timr-tui/logs/app.log
# `Windows` # `Windows`
C:/Users/{user}/AppData/Local/timr-tui/logs/app.log C:/Users/{user}/AppData/Local/timr-tui/logs/app.log
``` ```
Optional: You can use a custom directory by passing it via `--log` arg.
# License
[MIT License](./LICENSE)

BIN
demo/blink.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

23
demo/blink.tape Normal file
View File

@@ -0,0 +1,23 @@
Output demo/blink.gif
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
Set Theme "nord-light"
Set FontSize 14
Set Width 800
Set Height 400
Set Padding 0
Set Margin 1
# --- START ---
Set LoopOffset 4
Hide
# countdown 1.0s
Type "cargo run -- -r -m countdown -d -c 1 --blink=on"
Enter
Sleep 0.2
Type "m"
Type ":::"
Show
Type "s"
Sleep 4

BIN
demo/countdown-met.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

22
demo/countdown-met.tape Normal file
View File

@@ -0,0 +1,22 @@
Output demo/countdown-met.gif
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
Set Theme "iceberg-light"
Set FontSize 14
Set Width 800
Set Height 400
Set Padding 0
Set Margin 1
# --- START ---
Set LoopOffset 4
Hide
Type "cargo run -- -m c -c 3"
Enter
Sleep 0.2
Show
Type "s"
Sleep 6
Type "r"
Sleep 1

BIN
demo/local-time.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

22
demo/local-time.tape Normal file
View File

@@ -0,0 +1,22 @@
Output demo/local-time.gif
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
Set Theme "AtomOneLight"
Set FontSize 14
Set Width 800
Set Height 400
Set Padding 0
Set Margin 1
# --- START ---
Set LoopOffset 4
Hide
Type "cargo run -- -m c"
Enter
Sleep 0.2
Show
Sleep 1
# --- toggle local time ---
Type@1.5s ":::"
Sleep 1.5

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 130 KiB

View File

@@ -12,19 +12,15 @@ Set Margin 1
# --- START --- # --- START ---
Set LoopOffset 4 Set LoopOffset 4
Hide Hide
Type "cargo run -- -r -m p" Type "cargo run -- -r -m p --menu"
Enter Enter
Sleep 0.2 Type@200ms "m"
Show Show
# --- STYLES --- # --- STYLES ---
Sleep 0.5 Sleep 0.3s
Type "m" Type@0.3s "m"
Sleep 0.5 Type@0.3s "t"
Type@0.5s "t" Type@0.3s "c"
Type@0.5s "c" Type@0.3s "p"
Type@0.5s "p" Type@0.3s "e"
Type@0.5s "e" Escape@0.3s
Right@0.5s
Left@0.5s
Type@0.5s "e"
Sleep 0.5

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

After

Width:  |  Height:  |  Size: 174 KiB

View File

@@ -10,9 +10,8 @@ Set Padding 0
Set Margin 1 Set Margin 1
# --- START --- # --- START ---
Set LoopOffset 4
Hide Hide
Type "cargo run -- -r -d -m p" Type "cargo run -- -d -m p --blink on"
Enter Enter
Sleep 0.2 Sleep 0.2
Show Show
@@ -25,7 +24,7 @@ Sleep 0.2
Down@30ms 80 Down@30ms 80
Sleep 100ms Sleep 100ms
Type "e" Type "e"
Sleep 3 Sleep 4
# --- POMODORO PAUSE --- # --- POMODORO PAUSE ---
Right Right
Sleep 0.5 Sleep 0.5
@@ -36,4 +35,4 @@ Sleep 0.2
Down@30ms 60 Down@30ms 60
Sleep 100ms Sleep 100ms
Type "e" Type "e"
Sleep 3 Sleep 4

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

24
flake.lock generated
View File

@@ -2,11 +2,11 @@
"nodes": { "nodes": {
"crane": { "crane": {
"locked": { "locked": {
"lastModified": 1733286231, "lastModified": 1750266157,
"narHash": "sha256-mlIDSv1/jqWnH8JTiOV7GMUNPCXL25+6jmD+7hdxx5o=", "narHash": "sha256-tL42YoNg9y30u7zAqtoGDNdTyXTi8EALDeCB13FtbQA=",
"owner": "ipetkov", "owner": "ipetkov",
"repo": "crane", "repo": "crane",
"rev": "af1556ecda8bcf305820f68ec2f9d77b41d9cc80", "rev": "e37c943371b73ed87faf33f7583860f81f1d5a48",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -23,11 +23,11 @@
"rust-analyzer-src": "rust-analyzer-src" "rust-analyzer-src": "rust-analyzer-src"
}, },
"locked": { "locked": {
"lastModified": 1732689334, "lastModified": 1751092526,
"narHash": "sha256-yKI1KiZ0+bvDvfPTQ1ZT3oP/nIu3jPYm4dnbRd6hYg4=", "narHash": "sha256-vmbu97JXqr9/sTWR5XRh646jkp8a0J9m0o6JIQTdjE4=",
"owner": "nix-community", "owner": "nix-community",
"repo": "fenix", "repo": "fenix",
"rev": "a8a983027ca02b363dfc82fbe3f7d9548a8d3dce", "rev": "6643d56d9a78afa157b577862c220298c09b891d",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -56,11 +56,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1733212471, "lastModified": 1750776420,
"narHash": "sha256-M1+uCoV5igihRfcUKrr1riygbe73/dzNnzPsmaLCmpo=", "narHash": "sha256-/CG+w0o0oJ5itVklOoLbdn2dGB0wbZVOoDm4np6w09A=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "55d15ad12a74eb7d4646254e13638ad0c4128776", "rev": "30a61f056ac492e3b7cdcb69c1e6abdcf00e39cf",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -81,11 +81,11 @@
"rust-analyzer-src": { "rust-analyzer-src": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1732633904, "lastModified": 1750871759,
"narHash": "sha256-7VKcoLug9nbAN2txqVksWHHJplqK9Ou8dXjIZAIYSGc=", "narHash": "sha256-hMNZXMtlhfjQdu1F4Fa/UFiMoXdZag4cider2R9a648=",
"owner": "rust-lang", "owner": "rust-lang",
"repo": "rust-analyzer", "repo": "rust-analyzer",
"rev": "8d5e91c94f80c257ce6dbdfba7bd63a5e8a03fa6", "rev": "317542c1e4a3ec3467d21d1c25f6a43b80d83e7d",
"type": "github" "type": "github"
}, },
"original": { "original": {

View File

@@ -1,7 +1,5 @@
{ {
inputs = { inputs = {
# Disable `nixos-unstable` for now, it introduced some `VScode` related errors:
# error: function 'buildVscodeExtension' called without required argument 'pname'
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils"; flake-utils.url = "github:numtide/flake-utils";
crane.url = "github:ipetkov/crane"; crane.url = "github:ipetkov/crane";
@@ -20,34 +18,40 @@
}: }:
flake-utils.lib.eachDefaultSystem (system: let flake-utils.lib.eachDefaultSystem (system: let
pkgs = nixpkgs.legacyPackages.${system}; pkgs = nixpkgs.legacyPackages.${system};
# Using stable toolchain as base
toolchain = with fenix.packages.${system}; toolchain =
combine [ fenix.packages.${system}.fromToolchainFile
minimal.rustc {
minimal.cargo file = ./rust-toolchain.toml;
targets.x86_64-pc-windows-gnu.latest.rust-std # sha256 = nixpkgs.lib.fakeSha256;
]; sha256 = "sha256-Qxt8XAuaUR2OMdKbN4u8dBJOhSHxS+uS06Wl9+flVEk=";
};
craneLib = (crane.mkLib pkgs).overrideToolchain toolchain; craneLib = (crane.mkLib pkgs).overrideToolchain toolchain;
# Common build inputs for both native and cross compilation
commonArgs = { commonArgs = {
src = craneLib.cleanCargoSource ./.; src = craneLib.cleanCargoSource ./.;
cargoArtifacts = craneLib.buildDepsOnly { strictDeps = true;
src = craneLib.cleanCargoSource ./.;
};
doCheck = false; # skip tests during nix build doCheck = false; # skip tests during nix build
}; };
cargoArtifacts = craneLib.buildDepsOnly commonArgs;
# Native build # Native build
timr = craneLib.buildPackage commonArgs; timr = craneLib.buildPackage commonArgs;
# Linux build w/ statically linked binaries
staticLinuxBuild = craneLib.buildPackage (commonArgs
// {
inherit cargoArtifacts;
CARGO_BUILD_TARGET = "x86_64-unknown-linux-musl";
CARGO_BUILD_RUSTFLAGS = "-C target-feature=+crt-static";
});
# Windows cross-compilation build # Windows cross-compilation build
# @see https://crane.dev/examples/cross-windows.html # @see https://crane.dev/examples/cross-windows.html
crossBuild = craneLib.buildPackage { windowsBuild = craneLib.buildPackage {
src = craneLib.cleanCargoSource ./.; inherit (commonArgs) src strictDeps doCheck;
strictDeps = true;
doCheck = false;
CARGO_BUILD_TARGET = "x86_64-pc-windows-gnu"; CARGO_BUILD_TARGET = "x86_64-pc-windows-gnu";
@@ -68,24 +72,28 @@
packages = { packages = {
inherit timr; inherit timr;
default = timr; default = timr;
windows = crossBuild; linuxStatic = staticLinuxBuild;
windows = windowsBuild;
}; };
# Development shell with all necessary tools devShells.default = with nixpkgs.legacyPackages.${system};
devShell = with nixpkgs.legacyPackages.${system}; craneLib.devShell {
mkShell { packages =
buildInputs = with fenix.packages.${system}.stable; [ [
rust-analyzer
clippy
rustfmt
toolchain toolchain
pkgs.just pkgs.just
pkgs.nixd pkgs.nixd
pkgs.alejandra pkgs.alejandra
]
# some extra pkgs needed to play sound on Linux
++ lib.optionals stdenv.isLinux [
pkgs.pkg-config
(pkgs.alsa-lib-with-plugins.override {
plugins = [pkgs.alsa-plugins pkgs.pipewire];
})
]; ];
inherit (commonArgs) src; inherit (commonArgs) src;
RUST_SRC_PATH = "${toolchain}/lib/rustlib/src/rust/library";
}; };
}); });
} }

View File

@@ -2,64 +2,135 @@
set unstable := true set unstable := true
# list commands
default: default:
@just --list @just --list
alias b := build alias b := build
alias f := format
alias l := lint
alias t := test
alias r := run
# build app # build app
[group('build')]
build: build:
cargo build cargo build
alias t := test
# run tests # run tests
[group('test')]
test: test:
cargo test cargo test
alias f := format
# format files # format files
[group('misc')]
format: format:
just --fmt just --fmt
cargo fmt cargo fmt
alias l := lint
# lint # lint
[group('misc')]
lint: lint:
cargo clippy --no-deps cargo clippy --no-deps
alias r := run
# run app # run app
[group('dev')]
run: run:
cargo run cargo run
alias ra := run-args
# run app with arguments. It expects arguments as a string (e.g. "-c 5:00").
[group('dev')]
run-args args:
cargo run -- {{ args }}
alias rs := run-sound
# run app while sound feature is enabled. It expects a path to a sound file.
[group('dev')]
run-sound path:
cargo run --features sound -- --sound={{ path }}
alias rsa := run-sound-args
# run app while sound feature is enabled by adding a path to a sound file and other arguments as string (e.g. "-c 5:00").
[group('dev')]
run-sound-args path args:
cargo run --features sound -- --sound={{ path }} {{ args }}
# demos # demos
alias dp := demo-pomodoro alias dp := demo-pomodoro
# build demo: pomodoro
[group('demo')]
demo-pomodoro: demo-pomodoro:
vhs demo/pomodoro.tape vhs demo/pomodoro.tape
alias dt := demo-timer alias dt := demo-timer
# build demo: timer
[group('demo')]
demo-timer: demo-timer:
vhs demo/timer.tape vhs demo/timer.tape
alias dc := demo-countdown alias dc := demo-countdown
# build demo: countdown
[group('demo')]
demo-countdown: demo-countdown:
vhs demo/countdown.tape vhs demo/countdown.tape
alias dcm := demo-countdown-met
# build demo: countdown + met
[group('demo')]
demo-countdown-met:
vhs demo/countdown-met.tape
alias ds := demo-style alias ds := demo-style
# build demo: styles
[group('demo')]
demo-style: demo-style:
vhs demo/style.tape vhs demo/style.tape
alias dd := demo-decis alias dd := demo-decis
# build demo: deciseconds
[group('demo')]
demo-decis: demo-decis:
vhs demo/decis.tape vhs demo/decis.tape
alias dm := demo-menu alias dm := demo-menu
# build demo: menu
[group('demo')]
demo-menu: demo-menu:
vhs demo/menu.tape vhs demo/menu.tape
alias dlt := demo-local-time
# build demo: local time
[group('demo')]
demo-local-time:
vhs demo/local-time.tape
alias drc := demo-rocket-countdown
# build demo: rocket countdown
[group('demo')]
demo-rocket-countdown:
vhs demo/met.tape
alias db := demo-blink
# build demo: blink animation
[group('demo')]
demo-blink:
vhs demo/blink.tape

6
rust-toolchain.toml Normal file
View File

@@ -0,0 +1,6 @@
[toolchain]
# Reminder: Always keep `rust-version` in `Cargo.toml` in sync with `channel`.
channel = "1.88.0"
components = ["clippy", "rustfmt", "rust-src", "rust-analyzer"]
targets = ["x86_64-pc-windows-gnu", "x86_64-unknown-linux-musl"]
profile = "minimal"

View File

@@ -1,19 +1,23 @@
use crate::{ use crate::{
args::Args, args::Args,
common::{Content, Style}, common::{AppEditMode, AppTime, AppTimeFormat, ClockTypeId, Content, Style, Toggle},
constants::TICK_VALUE_MS, constants::TICK_VALUE_MS,
events::{Event, EventHandler, Events}, events::{self, TuiEventHandler},
storage::AppStorage, storage::AppStorage,
terminal::Terminal, terminal::Terminal,
widgets::{ widgets::{
clock::{self, Clock, ClockArgs}, clock::{self, ClockState, ClockStateArgs},
countdown::{Countdown, CountdownWidget}, countdown::{Countdown, CountdownState, CountdownStateArgs},
footer::Footer, footer::{Footer, FooterState},
header::Header, header::Header,
pomodoro::{Mode as PomodoroMode, Pomodoro, PomodoroArgs, PomodoroWidget}, pomodoro::{Mode as PomodoroMode, PomodoroState, PomodoroStateArgs, PomodoroWidget},
timer::{Timer, TimerWidget}, timer::{Timer, TimerState},
}, },
}; };
#[cfg(feature = "sound")]
use crate::sound::Sound;
use color_eyre::Result; use color_eyre::Result;
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
@@ -21,8 +25,10 @@ use ratatui::{
layout::{Constraint, Layout, Rect}, layout::{Constraint, Layout, Rect},
widgets::{StatefulWidget, Widget}, widgets::{StatefulWidget, Widget},
}; };
use std::path::PathBuf;
use std::time::Duration; use std::time::Duration;
use tracing::debug; use time::OffsetDateTime;
use tracing::{debug, error};
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode { enum Mode {
@@ -30,43 +36,81 @@ enum Mode {
Quit, Quit,
} }
#[derive(Debug)]
pub struct App { pub struct App {
content: Content, content: Content,
mode: Mode, mode: Mode,
show_menu: bool, notification: Toggle,
countdown: Countdown, blink: Toggle,
timer: Timer, #[allow(dead_code)] // w/ `--features sound` available only
pomodoro: Pomodoro, sound_path: Option<PathBuf>,
app_time: AppTime,
countdown: CountdownState,
timer: TimerState,
pomodoro: PomodoroState,
style: Style, style: Style,
with_decis: bool, with_decis: bool,
footer: FooterState,
} }
pub struct AppArgs { pub struct AppArgs {
pub style: Style, pub style: Style,
pub with_decis: bool, pub with_decis: bool,
pub notification: Toggle,
pub blink: Toggle,
pub show_menu: bool, pub show_menu: bool,
pub app_time_format: AppTimeFormat,
pub content: Content, pub content: Content,
pub pomodoro_mode: PomodoroMode, pub pomodoro_mode: PomodoroMode,
pub pomodoro_round: u64,
pub initial_value_work: Duration, pub initial_value_work: Duration,
pub current_value_work: Duration, pub current_value_work: Duration,
pub initial_value_pause: Duration, pub initial_value_pause: Duration,
pub current_value_pause: Duration, pub current_value_pause: Duration,
pub initial_value_countdown: Duration, pub initial_value_countdown: Duration,
pub current_value_countdown: Duration, pub current_value_countdown: Duration,
pub elapsed_value_countdown: Duration,
pub current_value_timer: Duration, pub current_value_timer: Duration,
pub app_tx: events::AppEventTx,
pub sound_path: Option<PathBuf>,
} }
/// Getting `AppArgs` by merging `Args` and `AppStorage`. pub struct FromAppArgs {
/// `Args` wins btw. pub args: Args,
impl From<(Args, AppStorage)> for AppArgs { pub stg: AppStorage,
fn from((args, stg): (Args, AppStorage)) -> Self { pub app_tx: events::AppEventTx,
AppArgs { }
/// Creates an `App` by merging `Args` and `AppStorage` (`Args` wins)
/// and adding `AppEventTx`
impl From<FromAppArgs> for App {
fn from(args: FromAppArgs) -> Self {
let FromAppArgs { args, stg, app_tx } = args;
App::new(AppArgs {
with_decis: args.decis || stg.with_decis, with_decis: args.decis || stg.with_decis,
show_menu: args.menu || stg.show_menu, show_menu: args.menu || stg.show_menu,
content: args.mode.unwrap_or(stg.content), notification: args.notification.unwrap_or(stg.notification),
blink: args.blink.unwrap_or(stg.blink),
app_time_format: stg.app_time_format,
// Check args to set a possible mode to start with.
content: match args.mode {
Some(mode) => mode,
// check other args (especially durations)
None => {
if args.work.is_some() || args.pause.is_some() {
Content::Pomodoro
} else if args.countdown.is_some() {
Content::Countdown
}
// in other case just use latest stored state
else {
stg.content
}
}
},
style: args.style.unwrap_or(stg.style), style: args.style.unwrap_or(stg.style),
pomodoro_mode: stg.pomodoro_mode, pomodoro_mode: stg.pomodoro_mode,
pomodoro_round: stg.pomodoro_count,
initial_value_work: args.work.unwrap_or(stg.inital_value_work), initial_value_work: args.work.unwrap_or(stg.inital_value_work),
// invalidate `current_value_work` if an initial value is set via args // invalidate `current_value_work` if an initial value is set via args
current_value_work: args.work.unwrap_or(stg.current_value_work), current_value_work: args.work.unwrap_or(stg.current_value_work),
@@ -76,9 +120,26 @@ impl From<(Args, AppStorage)> for AppArgs {
initial_value_countdown: args.countdown.unwrap_or(stg.inital_value_countdown), initial_value_countdown: args.countdown.unwrap_or(stg.inital_value_countdown),
// invalidate `current_value_countdown` if an initial value is set via args // invalidate `current_value_countdown` if an initial value is set via args
current_value_countdown: args.countdown.unwrap_or(stg.current_value_countdown), current_value_countdown: args.countdown.unwrap_or(stg.current_value_countdown),
elapsed_value_countdown: match args.countdown {
// reset value if countdown is set by arguments
Some(_) => Duration::ZERO,
None => stg.elapsed_value_countdown,
},
current_value_timer: stg.current_value_timer, current_value_timer: stg.current_value_timer,
app_tx,
#[cfg(feature = "sound")]
sound_path: args.sound,
#[cfg(not(feature = "sound"))]
sound_path: None,
})
} }
} }
fn get_app_time() -> AppTime {
match OffsetDateTime::now_local() {
Ok(t) => AppTime::Local(t),
Err(_) => AppTime::Utc(OffsetDateTime::now_utc()),
}
} }
impl App { impl App {
@@ -86,66 +147,166 @@ impl App {
let AppArgs { let AppArgs {
style, style,
show_menu, show_menu,
app_time_format,
initial_value_work, initial_value_work,
initial_value_pause, initial_value_pause,
initial_value_countdown, initial_value_countdown,
current_value_work, current_value_work,
current_value_pause, current_value_pause,
current_value_countdown, current_value_countdown,
elapsed_value_countdown,
current_value_timer, current_value_timer,
content, content,
with_decis, with_decis,
pomodoro_mode, pomodoro_mode,
pomodoro_round,
notification,
blink,
sound_path,
app_tx,
} = args; } = args;
let app_time = get_app_time();
Self { Self {
mode: Mode::Running, mode: Mode::Running,
notification,
blink,
sound_path,
content, content,
show_menu, app_time,
style, style,
with_decis, with_decis,
countdown: Countdown::new(Clock::<clock::Countdown>::new(ClockArgs { countdown: CountdownState::new(CountdownStateArgs {
initial_value: initial_value_countdown, initial_value: initial_value_countdown,
current_value: current_value_countdown, current_value: current_value_countdown,
tick_value: Duration::from_millis(TICK_VALUE_MS), elapsed_value: elapsed_value_countdown,
style, app_time,
with_decis, with_decis,
})), app_tx: app_tx.clone(),
timer: Timer::new(Clock::<clock::Timer>::new(ClockArgs { }),
timer: TimerState::new(
ClockState::<clock::Timer>::new(ClockStateArgs {
initial_value: Duration::ZERO, initial_value: Duration::ZERO,
current_value: current_value_timer, current_value: current_value_timer,
tick_value: Duration::from_millis(TICK_VALUE_MS), tick_value: Duration::from_millis(TICK_VALUE_MS),
style,
with_decis, with_decis,
})), app_tx: Some(app_tx.clone()),
pomodoro: Pomodoro::new(PomodoroArgs { })
.with_name("Timer".to_owned()),
),
pomodoro: PomodoroState::new(PomodoroStateArgs {
mode: pomodoro_mode, mode: pomodoro_mode,
initial_value_work, initial_value_work,
current_value_work, current_value_work,
initial_value_pause, initial_value_pause,
current_value_pause, current_value_pause,
style,
with_decis, with_decis,
round: pomodoro_round,
app_tx: app_tx.clone(),
}), }),
footer: FooterState::new(show_menu, app_time_format),
} }
} }
pub async fn run(mut self, mut terminal: Terminal, mut events: Events) -> Result<Self> { pub async fn run(
while self.is_running() { mut self,
if let Some(event) = events.next().await { terminal: &mut Terminal,
mut events: events::Events,
) -> Result<Self> {
// Closure to handle `KeyEvent`'s
let handle_key_event = |app: &mut Self, key: KeyEvent| {
debug!("Received key {:?}", key.code);
match key.code {
KeyCode::Char('q') => app.mode = Mode::Quit,
KeyCode::Char('c') => app.content = Content::Countdown,
KeyCode::Char('t') => app.content = Content::Timer,
KeyCode::Char('p') => app.content = Content::Pomodoro,
// toogle app time format
KeyCode::Char(':') => app.footer.toggle_app_time_format(),
// toogle menu
KeyCode::Char('m') => app.footer.set_show_menu(!app.footer.get_show_menu()),
KeyCode::Char(',') => {
app.style = app.style.next();
}
KeyCode::Char('.') => {
app.with_decis = !app.with_decis;
// update clocks
app.timer.set_with_decis(app.with_decis);
app.countdown.set_with_decis(app.with_decis);
app.pomodoro.set_with_decis(app.with_decis);
}
KeyCode::Up => app.footer.set_show_menu(true),
KeyCode::Down => app.footer.set_show_menu(false),
_ => {}
};
};
// Closure to handle `TuiEvent`'s
let mut handle_tui_events = |app: &mut Self, event: events::TuiEvent| -> Result<()> {
if matches!(event, events::TuiEvent::Tick) {
app.app_time = get_app_time();
app.countdown.set_app_time(app.app_time);
}
// Pipe events into subviews and handle only 'unhandled' events afterwards // Pipe events into subviews and handle only 'unhandled' events afterwards
if let Some(unhandled) = match self.content { if let Some(unhandled) = match app.content {
Content::Countdown => self.countdown.update(event.clone()), Content::Countdown => app.countdown.update(event.clone()),
Content::Timer => self.timer.update(event.clone()), Content::Timer => app.timer.update(event.clone()),
Content::Pomodoro => self.pomodoro.update(event.clone()), Content::Pomodoro => app.pomodoro.update(event.clone()),
} { } {
match unhandled { match unhandled {
Event::Render | Event::Resize => { events::TuiEvent::Render | events::TuiEvent::Resize => {
self.draw(&mut terminal)?; app.draw(terminal)?;
} }
Event::Key(key) => self.handle_key_event(key), events::TuiEvent::Key(key) => handle_key_event(app, key),
_ => {} _ => {}
} }
} }
Ok(())
};
#[allow(unused_variables)] // `app` is used by `--features sound` only
// Closure to handle `AppEvent`'s
let handle_app_events = |app: &mut Self, event: events::AppEvent| -> Result<()> {
match event {
events::AppEvent::ClockDone(type_id, name) => {
debug!("AppEvent::ClockDone");
if app.notification == Toggle::On {
let msg = match type_id {
ClockTypeId::Timer => {
format!("{name} stopped by reaching its maximum value.")
}
_ => format!("{type_id:?} {name} done!"),
};
// notification
let result = notify_rust::Notification::new()
.summary(&msg.to_uppercase())
.show();
if let Err(err) = result {
error!("on_done {name} error: {err}");
}
};
#[cfg(feature = "sound")]
if let Some(path) = app.sound_path.clone() {
_ = Sound::new(path).and_then(|sound| sound.play()).or_else(
|err| -> Result<()> {
error!("Sound error: {:?}", err);
Ok(())
},
);
}
}
}
Ok(())
};
while self.is_running() {
if let Some(event) = events.next().await {
let _ = match event {
events::Event::Terminal(e) => handle_tui_events(&mut self, e),
events::Event::App(e) => handle_app_events(&mut self, e),
};
} }
} }
Ok(self) Ok(self)
@@ -155,17 +316,38 @@ impl App {
self.mode != Mode::Quit self.mode != Mode::Quit
} }
fn is_edit_mode(&self) -> bool { fn get_edit_mode(&self) -> AppEditMode {
match self.content { match self.content {
Content::Countdown => self.countdown.get_clock().is_edit_mode(), Content::Countdown => {
Content::Timer => self.timer.get_clock().is_edit_mode(), if self.countdown.is_clock_edit_mode() {
Content::Pomodoro => self.pomodoro.get_clock().is_edit_mode(), AppEditMode::Clock
} else if self.countdown.is_time_edit_mode() {
AppEditMode::Time
} else {
AppEditMode::None
}
}
Content::Timer => {
if self.timer.get_clock().is_edit_mode() {
AppEditMode::Clock
} else {
AppEditMode::None
}
}
Content::Pomodoro => {
if self.pomodoro.get_clock().is_edit_mode() {
AppEditMode::Clock
} else {
AppEditMode::None
}
}
} }
} }
fn clock_is_running(&self) -> bool { fn clock_is_running(&self) -> bool {
match self.content { match self.content {
Content::Countdown => self.countdown.get_clock().is_running(), Content::Countdown => self.countdown.is_running(),
Content::Timer => self.timer.get_clock().is_running(), Content::Timer => self.timer.get_clock().is_running(),
Content::Pomodoro => self.pomodoro.get_clock().is_running(), Content::Pomodoro => self.pomodoro.get_clock().is_running(),
} }
@@ -179,34 +361,6 @@ impl App {
} }
} }
fn handle_key_event(&mut self, key: KeyEvent) {
debug!("Received key {:?}", key.code);
match key.code {
KeyCode::Char('q') | KeyCode::Esc => self.mode = Mode::Quit,
KeyCode::Char('c') => self.content = Content::Countdown,
KeyCode::Char('t') => self.content = Content::Timer,
KeyCode::Char('p') => self.content = Content::Pomodoro,
KeyCode::Char('m') => self.show_menu = !self.show_menu,
KeyCode::Char(',') => {
self.style = self.style.next();
// update clocks
self.timer.set_style(self.style);
self.countdown.set_style(self.style);
self.pomodoro.set_style(self.style);
}
KeyCode::Char('.') => {
self.with_decis = !self.with_decis;
// update clocks
self.timer.set_with_decis(self.with_decis);
self.countdown.set_with_decis(self.with_decis);
self.pomodoro.set_with_decis(self.with_decis);
}
KeyCode::Up => self.show_menu = true,
KeyCode::Down => self.show_menu = false,
_ => {}
};
}
fn draw(&mut self, terminal: &mut Terminal) -> Result<()> { fn draw(&mut self, terminal: &mut Terminal) -> Result<()> {
terminal.draw(|frame| { terminal.draw(|frame| {
frame.render_stateful_widget(AppWidget, frame.area(), self); frame.render_stateful_widget(AppWidget, frame.area(), self);
@@ -217,10 +371,14 @@ impl App {
pub fn to_storage(&self) -> AppStorage { pub fn to_storage(&self) -> AppStorage {
AppStorage { AppStorage {
content: self.content, content: self.content,
show_menu: self.show_menu, show_menu: self.footer.get_show_menu(),
notification: self.notification,
blink: self.blink,
app_time_format: *self.footer.app_time_format(),
style: self.style, style: self.style,
with_decis: self.with_decis, with_decis: self.with_decis,
pomodoro_mode: self.pomodoro.get_mode().clone(), pomodoro_mode: self.pomodoro.get_mode().clone(),
pomodoro_count: self.pomodoro.get_round(),
inital_value_work: Duration::from(*self.pomodoro.get_clock_work().get_initial_value()), inital_value_work: Duration::from(*self.pomodoro.get_clock_work().get_initial_value()),
current_value_work: Duration::from(*self.pomodoro.get_clock_work().get_current_value()), current_value_work: Duration::from(*self.pomodoro.get_clock_work().get_current_value()),
inital_value_pause: Duration::from( inital_value_pause: Duration::from(
@@ -233,6 +391,7 @@ impl App {
current_value_countdown: Duration::from( current_value_countdown: Duration::from(
*self.countdown.get_clock().get_current_value(), *self.countdown.get_clock().get_current_value(),
), ),
elapsed_value_countdown: Duration::from(*self.countdown.get_elapsed_value()),
current_value_timer: Duration::from(*self.timer.get_clock().get_current_value()), current_value_timer: Duration::from(*self.timer.get_clock().get_current_value()),
} }
} }
@@ -243,9 +402,23 @@ struct AppWidget;
impl AppWidget { impl AppWidget {
fn render_content(&self, area: Rect, buf: &mut Buffer, state: &mut App) { fn render_content(&self, area: Rect, buf: &mut Buffer, state: &mut App) {
match state.content { match state.content {
Content::Timer => TimerWidget.render(area, buf, &mut state.timer.clone()), Content::Timer => {
Content::Countdown => CountdownWidget.render(area, buf, &mut state.countdown.clone()), Timer {
Content::Pomodoro => PomodoroWidget.render(area, buf, &mut state.pomodoro.clone()), style: state.style,
blink: state.blink == Toggle::On,
}
.render(area, buf, &mut state.timer);
}
Content::Countdown => Countdown {
style: state.style,
blink: state.blink == Toggle::On,
}
.render(area, buf, &mut state.countdown),
Content::Pomodoro => PomodoroWidget {
style: state.style,
blink: state.blink == Toggle::On,
}
.render(area, buf, &mut state.pomodoro),
}; };
} }
} }
@@ -256,7 +429,7 @@ impl StatefulWidget for AppWidget {
let [v0, v1, v2] = Layout::vertical([ let [v0, v1, v2] = Layout::vertical([
Constraint::Length(1), Constraint::Length(1),
Constraint::Percentage(100), Constraint::Percentage(100),
Constraint::Length(if state.show_menu { 4 } else { 1 }), Constraint::Length(if state.footer.get_show_menu() { 5 } else { 1 }),
]) ])
.areas(area); .areas(area);
@@ -269,11 +442,11 @@ impl StatefulWidget for AppWidget {
self.render_content(v1, buf, state); self.render_content(v1, buf, state);
// footer // footer
Footer { Footer {
show_menu: state.show_menu,
running_clock: state.clock_is_running(), running_clock: state.clock_is_running(),
selected_content: state.content, selected_content: state.content,
edit_mode: state.is_edit_mode(), app_edit_mode: state.get_edit_mode(),
app_time: state.app_time,
} }
.render(v2, buf); .render(v2, buf, &mut state.footer);
} }
} }

View File

@@ -1,10 +1,15 @@
use crate::{ use crate::{
common::{Content, Style}, common::{Content, Style, Toggle},
duration, duration,
}; };
#[cfg(feature = "sound")]
use crate::{sound, sound::SoundError};
use clap::Parser; use clap::Parser;
use std::path::PathBuf;
use std::time::Duration; use std::time::Duration;
pub const LOG_DIRECTORY_DEFAULT_MISSING_VALUE: &str = " "; // empty string
#[derive(Parser)] #[derive(Parser)]
#[command(version)] #[command(version)]
pub struct Args { pub struct Args {
@@ -23,7 +28,7 @@ pub struct Args {
)] )]
pub pause: Option<Duration>, pub pause: Option<Duration>,
#[arg(long, short = 'd', help = "Whether to show deciseconds or not.")] #[arg(long, short = 'd', help = "Show deciseconds.")]
pub decis: bool, pub decis: bool,
#[arg(long, short = 'm', value_enum, help = "Mode to start with.")] #[arg(long, short = 'm', value_enum, help = "Mode to start with.")]
@@ -32,9 +37,55 @@ pub struct Args {
#[arg(long, short = 's', value_enum, help = "Style to display time with.")] #[arg(long, short = 's', value_enum, help = "Style to display time with.")]
pub style: Option<Style>, pub style: Option<Style>,
#[arg(long, value_enum, help = "Whether to open the menu or not.")] #[arg(long, value_enum, help = "Open the menu.")]
pub menu: bool, pub menu: bool,
#[arg(long, short = 'r', help = "Reset stored values to default.")] #[arg(long, short = 'r', help = "Reset stored values to default values.")]
pub reset: bool, pub reset: bool,
#[arg(
long,
short,
value_enum,
help = "Toggle desktop notifications. Experimental."
)]
pub notification: Option<Toggle>,
#[arg(
long,
value_enum,
help = "Toggle blink mode to animate a clock when it reaches its finished mode."
)]
pub blink: Option<Toggle>,
#[cfg(feature = "sound")]
#[arg(
long,
value_enum,
help = "Path to sound file (.mp3 or .wav) to play as notification. Experimental.",
value_hint = clap::ValueHint::FilePath,
value_parser = sound_file_parser,
)]
pub sound: Option<PathBuf>,
#[arg(
long,
// allows both --log=path and --log path syntax
num_args = 0..=1,
// Note: If no value is passed, use a " " by default,
// this value will be checked later in `main`
// to use another (default) log directory instead
default_missing_value=LOG_DIRECTORY_DEFAULT_MISSING_VALUE,
help = "Directory to store log file. If not set, standard application log directory is used (check README for details).",
value_hint = clap::ValueHint::DirPath,
)]
pub log: Option<PathBuf>,
}
#[cfg(feature = "sound")]
/// Custom parser for sound file
fn sound_file_parser(s: &str) -> Result<PathBuf, SoundError> {
let path = PathBuf::from(s);
sound::validate_sound_file(&path)?;
Ok(path)
} }

View File

@@ -1,6 +1,8 @@
use clap::ValueEnum; use clap::ValueEnum;
use ratatui::symbols::shade; use ratatui::symbols::shade;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use time::format_description;
#[derive( #[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Default, Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Default, Serialize, Deserialize,
@@ -15,6 +17,12 @@ pub enum Content {
Pomodoro, Pomodoro,
} }
#[derive(Clone, Debug)]
pub enum ClockTypeId {
Countdown,
Timer,
}
#[derive(Debug, Copy, Clone, ValueEnum, Default, Serialize, Deserialize)] #[derive(Debug, Copy, Clone, ValueEnum, Default, Serialize, Deserialize)]
pub enum Style { pub enum Style {
#[default] #[default]
@@ -62,3 +70,138 @@ impl Style {
} }
} }
} }
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub enum AppTimeFormat {
/// `hh:mm:ss`
#[default]
HhMmSs,
/// `hh:mm`
HhMm,
/// `hh:mm AM` (or PM)
Hh12Mm,
/// `` (empty)
Hidden,
}
impl AppTimeFormat {
pub fn next(&self) -> Self {
match self {
AppTimeFormat::HhMmSs => AppTimeFormat::HhMm,
AppTimeFormat::HhMm => AppTimeFormat::Hh12Mm,
AppTimeFormat::Hh12Mm => AppTimeFormat::Hidden,
AppTimeFormat::Hidden => AppTimeFormat::HhMmSs,
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum AppTime {
Local(OffsetDateTime),
Utc(OffsetDateTime),
}
impl From<AppTime> for OffsetDateTime {
fn from(app_time: AppTime) -> Self {
match app_time {
AppTime::Local(t) => t,
AppTime::Utc(t) => t,
}
}
}
impl AppTime {
pub fn format(&self, app_format: &AppTimeFormat) -> String {
let parse_str = match app_format {
AppTimeFormat::HhMmSs => Some("[hour]:[minute]:[second]"),
AppTimeFormat::HhMm => Some("[hour]:[minute]"),
AppTimeFormat::Hh12Mm => Some("[hour repr:12 padding:none]:[minute] [period]"),
AppTimeFormat::Hidden => None,
};
if let Some(str) = parse_str {
format_description::parse(str)
.map_err(|_| "parse error")
.and_then(|fd| {
OffsetDateTime::from(*self)
.format(&fd)
.map_err(|_| "format error")
})
.unwrap_or_else(|e| e.to_string())
} else {
"".to_owned()
}
}
}
#[derive(Debug)]
pub enum AppEditMode {
None,
Clock,
Time,
}
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum Toggle {
#[value(name = "on")]
On,
#[default]
#[value(name = "off")]
Off,
}
#[cfg(test)]
mod tests {
use super::*;
use time::{Date, Month, PrimitiveDateTime, Time};
#[test]
fn test_format_app_time() {
let dt = PrimitiveDateTime::new(
Date::from_calendar_date(2025, Month::January, 6).unwrap(),
Time::from_hms(18, 6, 10).unwrap(),
)
.assume_utc();
// hh:mm:ss
assert_eq!(
AppTime::Utc(dt).format(&AppTimeFormat::HhMmSs),
"18:06:10",
"utc"
);
assert_eq!(
AppTime::Local(dt).format(&AppTimeFormat::HhMmSs),
"18:06:10",
"local"
);
// hh:mm
assert_eq!(
AppTime::Utc(dt).format(&AppTimeFormat::HhMm),
"18:06",
"utc"
);
assert_eq!(
AppTime::Local(dt).format(&AppTimeFormat::HhMm),
"18:06",
"local"
);
// hh:mm period
assert_eq!(
AppTime::Utc(dt).format(&AppTimeFormat::Hh12Mm),
"6:06 PM",
"utc"
);
assert_eq!(
AppTime::Local(dt).format(&AppTimeFormat::Hh12Mm),
"6:06 PM",
"local"
);
// hidden
assert_eq!(AppTime::Utc(dt).format(&AppTimeFormat::Hidden), "", "utc");
assert_eq!(
AppTime::Local(dt).format(&AppTimeFormat::Hidden),
"",
"local"
);
}
}

View File

@@ -1,8 +1,9 @@
use crate::constants::APP_NAME; use crate::constants::APP_NAME;
use color_eyre::eyre::{eyre, Result}; use color_eyre::eyre::{Result, eyre};
use directories::ProjectDirs; use directories::ProjectDirs;
use std::fs; use std::fs;
use std::path::PathBuf; use std::path::PathBuf;
pub struct Config { pub struct Config {
pub log_dir: PathBuf, pub log_dir: PathBuf,
pub data_dir: PathBuf, pub data_dir: PathBuf,
@@ -10,8 +11,11 @@ pub struct Config {
impl Config { impl Config {
pub fn init() -> Result<Self> { pub fn init() -> Result<Self> {
// default logs dir
let log_dir = get_default_state_dir()?.join("logs"); let log_dir = get_default_state_dir()?.join("logs");
fs::create_dir_all(&log_dir)?; fs::create_dir_all(&log_dir)?;
// default data dir
let data_dir = get_default_state_dir()?.join("data"); let data_dir = get_default_state_dir()?.join("data");
fs::create_dir_all(&data_dir)?; fs::create_dir_all(&data_dir)?;

View File

@@ -1,6 +1,6 @@
use color_eyre::{ use color_eyre::{
eyre::{ensure, eyre},
Report, Report,
eyre::{ensure, eyre},
}; };
use std::fmt; use std::fmt;
use std::time::Duration; use std::time::Duration;
@@ -20,6 +20,10 @@ pub const MINS_PER_HOUR: u64 = 60;
// https://doc.rust-lang.org/src/core/time.rs.html#36 // https://doc.rust-lang.org/src/core/time.rs.html#36
const HOURS_PER_DAY: u64 = 24; const HOURS_PER_DAY: u64 = 24;
// max. 99:59:59
pub const MAX_DURATION: Duration =
Duration::from_secs(100 * MINS_PER_HOUR * SECS_PER_MINUTE).saturating_sub(ONE_SECOND);
#[derive(Debug, Clone, Copy, PartialOrd)] #[derive(Debug, Clone, Copy, PartialOrd)]
pub struct DurationEx { pub struct DurationEx {
inner: Duration, inner: Duration,
@@ -86,6 +90,10 @@ impl DurationEx {
let inner = self.inner.saturating_sub(ex.inner); let inner = self.inner.saturating_sub(ex.inner);
Self { inner } Self { inner }
} }
pub fn to_string_with_decis(self) -> String {
format!("{}.{}", self, self.decis())
}
} }
impl fmt::Display for DurationEx { impl fmt::Display for DurationEx {
@@ -169,22 +177,22 @@ mod tests {
fn test_fmt() { fn test_fmt() {
// hh:mm:ss // hh:mm:ss
let ex: DurationEx = Duration::from_secs(36001).into(); let ex: DurationEx = Duration::from_secs(36001).into();
assert_eq!(format!("{}", ex), "10:00:01"); assert_eq!(format!("{ex}"), "10:00:01");
// h:mm:ss // h:mm:ss
let ex: DurationEx = Duration::from_secs(3601).into(); let ex: DurationEx = Duration::from_secs(3601).into();
assert_eq!(format!("{}", ex), "1:00:01"); assert_eq!(format!("{ex}"), "1:00:01");
// mm:ss // mm:ss
let ex: DurationEx = Duration::from_secs(71).into(); let ex: DurationEx = Duration::from_secs(71).into();
assert_eq!(format!("{}", ex), "1:11"); assert_eq!(format!("{ex}"), "1:11");
// m:ss // m:ss
let ex: DurationEx = Duration::from_secs(61).into(); let ex: DurationEx = Duration::from_secs(61).into();
assert_eq!(format!("{}", ex), "1:01"); assert_eq!(format!("{ex}"), "1:01");
// ss // ss
let ex: DurationEx = Duration::from_secs(11).into(); let ex: DurationEx = Duration::from_secs(11).into();
assert_eq!(format!("{}", ex), "11"); assert_eq!(format!("{ex}"), "11");
// s // s
let ex: DurationEx = Duration::from_secs(1).into(); let ex: DurationEx = Duration::from_secs(1).into();
assert_eq!(format!("{}", ex), "1"); assert_eq!(format!("{ex}"), "1");
} }
#[test] #[test]
@@ -192,7 +200,7 @@ mod tests {
let ex: DurationEx = Duration::from_secs(10).into(); let ex: DurationEx = Duration::from_secs(10).into();
let ex2: DurationEx = Duration::from_secs(1).into(); let ex2: DurationEx = Duration::from_secs(1).into();
let ex3 = ex.saturating_sub(ex2); let ex3 = ex.saturating_sub(ex2);
assert_eq!(format!("{}", ex3), "9"); assert_eq!(format!("{ex3}"), "9");
} }
#[test] #[test]
@@ -200,7 +208,7 @@ mod tests {
let ex: DurationEx = Duration::from_secs(10).into(); let ex: DurationEx = Duration::from_secs(10).into();
let ex2: DurationEx = Duration::from_secs(1).into(); let ex2: DurationEx = Duration::from_secs(1).into();
let ex3 = ex.saturating_add(ex2); let ex3 = ex.saturating_add(ex2);
assert_eq!(format!("{}", ex3), "11"); assert_eq!(format!("{ex3}"), "11");
} }
#[test] #[test]

View File

@@ -1,9 +1,11 @@
use crossterm::event::{Event as CrosstermEvent, EventStream, KeyEvent, KeyEventKind}; use crossterm::event::{Event as CrosstermEvent, EventStream, KeyEvent, KeyEventKind};
use futures::{Stream, StreamExt}; use futures::{Stream, StreamExt};
use std::{pin::Pin, time::Duration}; use std::{pin::Pin, time::Duration};
use tokio::sync::mpsc;
use tokio::time::interval; use tokio::time::interval;
use tokio_stream::{wrappers::IntervalStream, StreamMap}; use tokio_stream::{StreamMap, wrappers::IntervalStream};
use crate::common::ClockTypeId;
use crate::constants::{FPS_VALUE_MS, TICK_VALUE_MS}; use crate::constants::{FPS_VALUE_MS, TICK_VALUE_MS};
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
@@ -12,8 +14,9 @@ enum StreamKey {
Render, Render,
Crossterm, Crossterm,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Event { pub enum TuiEvent {
Error, Error,
Tick, Tick,
Render, Render,
@@ -21,8 +24,17 @@ pub enum Event {
Resize, Resize,
} }
#[derive(Clone, Debug)]
pub enum AppEvent {
ClockDone(ClockTypeId, String),
}
pub type AppEventTx = mpsc::UnboundedSender<AppEvent>;
pub type AppEventRx = mpsc::UnboundedReceiver<AppEvent>;
pub struct Events { pub struct Events {
streams: StreamMap<StreamKey, Pin<Box<dyn Stream<Item = Event>>>>, streams: StreamMap<StreamKey, Pin<Box<dyn Stream<Item = TuiEvent>>>>,
app_channel: (AppEventTx, AppEventRx),
} }
impl Default for Events { impl Default for Events {
@@ -33,31 +45,46 @@ impl Default for Events {
(StreamKey::Render, render_stream()), (StreamKey::Render, render_stream()),
(StreamKey::Crossterm, crossterm_stream()), (StreamKey::Crossterm, crossterm_stream()),
]), ]),
app_channel: mpsc::unbounded_channel(),
} }
} }
} }
pub enum Event {
Terminal(TuiEvent),
App(AppEvent),
}
impl Events { impl Events {
pub fn new() -> Self { pub fn new() -> Self {
Self::default() Self::default()
} }
pub async fn next(&mut self) -> Option<Event> { pub async fn next(&mut self) -> Option<Event> {
self.streams.next().await.map(|(_, event)| event) let streams = &mut self.streams;
let app_rx = &mut self.app_channel.1;
tokio::select! {
Some((_, event)) = streams.next() => Some(Event::Terminal(event)),
Some(app_event) = app_rx.recv() => Some(Event::App(app_event)),
} }
} }
fn tick_stream() -> Pin<Box<dyn Stream<Item = Event>>> { pub fn get_app_event_tx(&self) -> AppEventTx {
self.app_channel.0.clone()
}
}
fn tick_stream() -> Pin<Box<dyn Stream<Item = TuiEvent>>> {
let tick_interval = interval(Duration::from_millis(TICK_VALUE_MS)); let tick_interval = interval(Duration::from_millis(TICK_VALUE_MS));
Box::pin(IntervalStream::new(tick_interval).map(|_| Event::Tick)) Box::pin(IntervalStream::new(tick_interval).map(|_| TuiEvent::Tick))
} }
fn render_stream() -> Pin<Box<dyn Stream<Item = Event>>> { fn render_stream() -> Pin<Box<dyn Stream<Item = TuiEvent>>> {
let render_interval = interval(Duration::from_millis(FPS_VALUE_MS)); let render_interval = interval(Duration::from_millis(FPS_VALUE_MS));
Box::pin(IntervalStream::new(render_interval).map(|_| Event::Render)) Box::pin(IntervalStream::new(render_interval).map(|_| TuiEvent::Render))
} }
fn crossterm_stream() -> Pin<Box<dyn Stream<Item = Event>>> { fn crossterm_stream() -> Pin<Box<dyn Stream<Item = TuiEvent>>> {
Box::pin( Box::pin(
EventStream::new() EventStream::new()
.fuse() .fuse()
@@ -65,16 +92,16 @@ fn crossterm_stream() -> Pin<Box<dyn Stream<Item = Event>>> {
.filter_map(|event| async move { .filter_map(|event| async move {
match event { match event {
Ok(CrosstermEvent::Key(key)) if key.kind == KeyEventKind::Press => { Ok(CrosstermEvent::Key(key)) if key.kind == KeyEventKind::Press => {
Some(Event::Key(key)) Some(TuiEvent::Key(key))
} }
Ok(CrosstermEvent::Resize(_, _)) => Some(Event::Resize), Ok(CrosstermEvent::Resize(_, _)) => Some(TuiEvent::Resize),
Err(_) => Some(Event::Error), Err(_) => Some(TuiEvent::Error),
_ => None, _ => None,
} }
}), }),
) )
} }
pub trait EventHandler { pub trait TuiEventHandler {
fn update(&mut self, _: Event) -> Option<Event>; fn update(&mut self, _: TuiEvent) -> Option<TuiEvent>;
} }

View File

@@ -1,4 +1,4 @@
use color_eyre::eyre::Result; use color_eyre::eyre::{Result, eyre};
use std::fs; use std::fs;
use std::path::PathBuf; use std::path::PathBuf;
use tracing::level_filters::LevelFilter; use tracing::level_filters::LevelFilter;
@@ -17,7 +17,13 @@ impl Logger {
pub fn init(&self) -> Result<()> { pub fn init(&self) -> Result<()> {
let log_path = self.log_dir.join("app.log"); let log_path = self.log_dir.join("app.log");
let log_file = fs::File::create(log_path)?; let log_file = fs::File::create(log_path).map_err(|err| {
eyre!(
"Could not create a log file in {:?} : {}",
self.log_dir,
err
)
})?;
let fmt_layer = tracing_subscriber::fmt::layer() let fmt_layer = tracing_subscriber::fmt::layer()
.with_file(true) .with_file(true)
.with_line_number(true) .with_line_number(true)

View File

@@ -3,7 +3,6 @@ mod common;
mod config; mod config;
mod constants; mod constants;
mod events; mod events;
#[cfg(debug_assertions)]
mod logging; mod logging;
mod args; mod args;
@@ -13,24 +12,50 @@ mod terminal;
mod utils; mod utils;
mod widgets; mod widgets;
use app::{App, AppArgs}; #[cfg(feature = "sound")]
use args::Args; mod sound;
use app::{App, FromAppArgs};
use args::{Args, LOG_DIRECTORY_DEFAULT_MISSING_VALUE};
use clap::Parser; use clap::Parser;
use color_eyre::Result; use color_eyre::Result;
use config::Config; use config::Config;
use std::path::PathBuf;
use storage::{AppStorage, Storage}; use storage::{AppStorage, Storage};
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
// init `Config`
let cfg = Config::init()?; let cfg = Config::init()?;
#[cfg(debug_assertions)]
logging::Logger::new(cfg.log_dir).init()?;
color_eyre::install()?; color_eyre::install()?;
// get args given by CLI // get args given by CLI
let args = Args::parse(); let args = Args::parse();
// Note:
// `log` arg can have three different values:
// (1) not set => None
// (2) set with path => Some(Some(path))
// (3) set without path => Some(None)
let custom_log_dir: Option<Option<&PathBuf>> = if let Some(path) = &args.log {
if path.ne(PathBuf::from(LOG_DIRECTORY_DEFAULT_MISSING_VALUE).as_os_str()) {
// (2)
Some(Some(path))
} else {
// (3)
Some(None)
}
} else {
// (1)
None
};
let terminal = terminal::setup()?; if let Some(log_dir) = custom_log_dir {
let dir: PathBuf = log_dir.unwrap_or(&cfg.log_dir).to_path_buf();
logging::Logger::new(dir).init()?;
}
let mut terminal = terminal::setup()?;
let events = events::Events::new(); let events = events::Events::new();
// check persistant storage // check persistant storage
@@ -42,9 +67,14 @@ async fn main() -> Result<()> {
storage.load().unwrap_or_default() storage.load().unwrap_or_default()
}; };
// merge `Args` and `AppStorage`. let app_storage = App::from(FromAppArgs {
let app_args = AppArgs::from((args, stg)); args,
let app_storage = App::new(app_args).run(terminal, events).await?.to_storage(); stg,
app_tx: events.get_app_event_tx(),
})
.run(&mut terminal, events)
.await?
.to_storage();
// store app state persistantly // store app state persistantly
storage.save(app_storage)?; storage.save(app_storage)?;

73
src/sound.rs Normal file
View File

@@ -0,0 +1,73 @@
use rodio::{Decoder, OutputStream, Sink};
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum SoundError {
#[error("Sound output stream error: {0}")]
OutputStream(String),
#[error("Sound file error: {0}")]
File(String),
#[error("Sound sink error: {0}")]
Sink(String),
#[error("Sound decoder error: {0}")]
Decoder(String),
}
pub fn validate_sound_file(path: &PathBuf) -> Result<&PathBuf, SoundError> {
// validate path
if !path.exists() {
let err = SoundError::File(format!("File not found: {:?}", path));
return Err(err);
};
// Validate file extension
path.extension()
.and_then(|ext| ext.to_str())
.filter(|ext| ["mp3", "wav"].contains(&ext.to_lowercase().as_str()))
.ok_or_else(|| {
SoundError::File(
"Unsupported file extension. Only .mp3 and .wav are supported".to_owned(),
)
})?;
Ok(path)
}
// #[derive(Clone)]
pub struct Sound {
path: PathBuf,
}
impl Sound {
pub fn new(path: PathBuf) -> Result<Self, SoundError> {
Ok(Self { path })
}
pub fn play(&self) -> Result<(), SoundError> {
// validate file again
validate_sound_file(&self.path)?;
// before playing the sound
let path = self.path.clone();
std::thread::spawn(move || -> Result<(), SoundError> {
// Important note: Never (ever) use a single `_` as a placeholder here. `_stream` or something is fine!
// The value will dropped and the sound will fail without any errors
// see https://github.com/RustAudio/rodio/issues/330
let (_stream, handle) =
OutputStream::try_default().map_err(|e| SoundError::OutputStream(e.to_string()))?;
let file = File::open(&path).map_err(|e| SoundError::File(e.to_string()))?;
let sink = Sink::try_new(&handle).map_err(|e| SoundError::Sink(e.to_string()))?;
let decoder = Decoder::new(BufReader::new(file))
.map_err(|e| SoundError::Decoder(e.to_string()))?;
sink.append(decoder);
sink.sleep_until_end();
Ok(())
});
Ok(())
}
}

View File

@@ -1,5 +1,5 @@
use crate::{ use crate::{
common::{Content, Style}, common::{AppTimeFormat, Content, Style, Toggle},
widgets::pomodoro::Mode as PomodoroMode, widgets::pomodoro::Mode as PomodoroMode,
}; };
use color_eyre::eyre::Result; use color_eyre::eyre::Result;
@@ -12,9 +12,13 @@ use std::time::Duration;
pub struct AppStorage { pub struct AppStorage {
pub content: Content, pub content: Content,
pub show_menu: bool, pub show_menu: bool,
pub notification: Toggle,
pub blink: Toggle,
pub app_time_format: AppTimeFormat,
pub style: Style, pub style: Style,
pub with_decis: bool, pub with_decis: bool,
pub pomodoro_mode: PomodoroMode, pub pomodoro_mode: PomodoroMode,
pub pomodoro_count: u64,
// pomodoro -> work // pomodoro -> work
pub inital_value_work: Duration, pub inital_value_work: Duration,
pub current_value_work: Duration, pub current_value_work: Duration,
@@ -24,6 +28,7 @@ pub struct AppStorage {
// countdown // countdown
pub inital_value_countdown: Duration, pub inital_value_countdown: Duration,
pub current_value_countdown: Duration, pub current_value_countdown: Duration,
pub elapsed_value_countdown: Duration,
// timer // timer
pub current_value_timer: Duration, pub current_value_timer: Duration,
} }
@@ -36,9 +41,13 @@ impl Default for AppStorage {
AppStorage { AppStorage {
content: Content::default(), content: Content::default(),
show_menu: true, show_menu: true,
notification: Toggle::Off,
blink: Toggle::Off,
app_time_format: AppTimeFormat::default(),
style: Style::default(), style: Style::default(),
with_decis: false, with_decis: false,
pomodoro_mode: PomodoroMode::Work, pomodoro_mode: PomodoroMode::Work,
pomodoro_count: 1,
// pomodoro -> work // pomodoro -> work
inital_value_work: DEFAULT_WORK, inital_value_work: DEFAULT_WORK,
current_value_work: DEFAULT_WORK, current_value_work: DEFAULT_WORK,
@@ -48,6 +57,7 @@ impl Default for AppStorage {
// countdown // countdown
inital_value_countdown: DEFAULT_COUNTDOWN, inital_value_countdown: DEFAULT_COUNTDOWN,
current_value_countdown: DEFAULT_COUNTDOWN, current_value_countdown: DEFAULT_COUNTDOWN,
elapsed_value_countdown: Duration::ZERO,
// timer // timer
current_value_timer: Duration::ZERO, current_value_timer: Duration::ZERO,
} }

View File

@@ -5,13 +5,14 @@ use crossterm::{
cursor, execute, cursor, execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen}, terminal::{EnterAlternateScreen, LeaveAlternateScreen},
}; };
use ratatui::{backend::CrosstermBackend, Terminal as RatatuiTerminal}; use ratatui::{Terminal as RatatuiTerminal, backend::CrosstermBackend};
pub type Terminal = RatatuiTerminal<CrosstermBackend<io::Stdout>>; pub type Terminal = RatatuiTerminal<CrosstermBackend<io::Stdout>>;
pub fn setup() -> Result<Terminal> { pub fn setup() -> Result<Terminal> {
let mut stdout = std::io::stdout(); let mut stdout = std::io::stdout();
crossterm::terminal::enable_raw_mode()?; crossterm::terminal::enable_raw_mode()?;
set_panic_hook();
execute!(stdout, EnterAlternateScreen, cursor::Hide)?; execute!(stdout, EnterAlternateScreen, cursor::Hide)?;
let mut terminal = RatatuiTerminal::new(CrosstermBackend::new(stdout))?; let mut terminal = RatatuiTerminal::new(CrosstermBackend::new(stdout))?;
terminal.clear()?; terminal.clear()?;
@@ -24,3 +25,13 @@ pub fn teardown() -> Result<()> {
crossterm::terminal::disable_raw_mode()?; crossterm::terminal::disable_raw_mode()?;
Ok(()) Ok(())
} }
// Panic hook
// see https://ratatui.rs/tutorials/counter-app/error-handling/#setup-hooks
fn set_panic_hook() {
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
let _ = teardown(); // ignore any errors as we are already failing
hook(panic_info);
}));
}

View File

@@ -5,6 +5,7 @@ pub mod clock_elements_test;
#[cfg(test)] #[cfg(test)]
pub mod clock_test; pub mod clock_test;
pub mod countdown; pub mod countdown;
pub mod edit_time;
pub mod footer; pub mod footer;
pub mod header; pub mod header;
pub mod pomodoro; pub mod pomodoro;

View File

@@ -10,21 +10,15 @@ use ratatui::{
}; };
use crate::{ use crate::{
common::Style, common::{ClockTypeId, Style},
duration::{ duration::{DurationEx, MAX_DURATION, ONE_DECI_SECOND, ONE_HOUR, ONE_MINUTE, ONE_SECOND},
DurationEx, MINS_PER_HOUR, ONE_DECI_SECOND, ONE_HOUR, ONE_MINUTE, ONE_SECOND, events::{AppEvent, AppEventTx},
SECS_PER_MINUTE,
},
utils::center_horizontal, utils::center_horizontal,
widgets::clock_elements::{ widgets::clock_elements::{
Colon, Digit, Dot, COLON_WIDTH, DIGIT_HEIGHT, DIGIT_WIDTH, DOT_WIDTH, COLON_WIDTH, Colon, DIGIT_HEIGHT, DIGIT_SPACE_WIDTH, DIGIT_WIDTH, DOT_WIDTH, Digit, Dot,
}, },
}; };
// max. 99:59:59
const MAX_DURATION: Duration =
Duration::from_secs(100 * MINS_PER_HOUR * SECS_PER_MINUTE).saturating_sub(ONE_SECOND);
#[derive(Debug, Copy, Clone, Display, PartialEq, Eq)] #[derive(Debug, Copy, Clone, Display, PartialEq, Eq)]
pub enum Time { pub enum Time {
Decis, Decis,
@@ -72,27 +66,71 @@ pub enum Format {
HhMmSs, HhMmSs,
} }
#[derive(Debug, Clone)] const RANGE_OF_DONE_COUNT: u64 = 4;
pub struct Clock<T> { const MAX_DONE_COUNT: u64 = RANGE_OF_DONE_COUNT * 5;
pub struct ClockState<T> {
type_id: ClockTypeId,
name: Option<String>,
initial_value: DurationEx, initial_value: DurationEx,
current_value: DurationEx, current_value: DurationEx,
prev_value: DurationEx,
tick_value: DurationEx, tick_value: DurationEx,
mode: Mode, mode: Mode,
format: Format, format: Format,
pub style: Style,
pub with_decis: bool, pub with_decis: bool,
app_tx: Option<AppEventTx>,
/// Tick counter starting whenever `Mode::DONE` has been reached.
/// Initial value is set in `done()`.
/// Updates happened in `update_done_count`
/// Default value: `None`
done_count: Option<u64>,
phantom: PhantomData<T>, phantom: PhantomData<T>,
} }
pub struct ClockArgs { pub struct ClockStateArgs {
pub initial_value: Duration, pub initial_value: Duration,
pub current_value: Duration, pub current_value: Duration,
pub tick_value: Duration, pub tick_value: Duration,
pub style: Style,
pub with_decis: bool, pub with_decis: bool,
pub app_tx: Option<AppEventTx>,
}
impl<T> ClockState<T> {
pub fn with_name(mut self, name: String) -> Self {
self.name = Some(name);
self
}
pub fn get_name(&self) -> String {
self.name.clone().unwrap_or_default()
}
pub fn get_type_id(&self) -> &ClockTypeId {
&self.type_id
}
pub fn with_mode(mut self, mode: Mode) -> Self {
self.mode = mode;
self
}
pub fn get_mode(&self) -> &Mode {
&self.mode
}
pub fn is_initial(&self) -> bool {
self.mode == Mode::Initial
}
pub fn run(&mut self) {
self.mode = Mode::Tick
}
pub fn is_running(&self) -> bool {
self.mode == Mode::Tick
} }
impl<T> Clock<T> {
pub fn toggle_pause(&mut self) { pub fn toggle_pause(&mut self) {
self.mode = if self.mode == Mode::Tick { self.mode = if self.mode == Mode::Tick {
Mode::Pause Mode::Pause
@@ -105,18 +143,31 @@ impl<T> Clock<T> {
&self.initial_value &self.initial_value
} }
pub fn set_initial_value(&mut self, duration: DurationEx) {
self.initial_value = duration;
}
pub fn get_current_value(&self) -> &DurationEx { pub fn get_current_value(&self) -> &DurationEx {
&self.current_value &self.current_value
} }
pub fn set_current_value(&mut self, duration: DurationEx) {
self.current_value = duration;
self.update_format();
}
pub fn get_prev_value(&self) -> &DurationEx {
&self.prev_value
}
pub fn toggle_edit(&mut self) { pub fn toggle_edit(&mut self) {
self.mode = match self.mode.clone() { self.mode = match self.mode.clone() {
Mode::Editable(_, prev) => { Mode::Editable(_, prev) => {
let p = *prev; let p = *prev;
// special cases: Should `Mode` be updated? // Update `Mode`
// 1. `Done` -> `Initial` ? // 1. `Done` -> `Pause`
if p == Mode::Done && self.current_value.gt(&Duration::ZERO.into()) { if p == Mode::Done && self.current_value.gt(&Duration::ZERO.into()) {
Mode::Initial Mode::Pause
} }
// 2. `_` -> `Done` ? // 2. `_` -> `Done` ?
else if p != Mode::Done && self.current_value.eq(&Duration::ZERO.into()) { else if p != Mode::Done && self.current_value.eq(&Duration::ZERO.into()) {
@@ -128,6 +179,8 @@ impl<T> Clock<T> {
} }
} }
mode => { mode => {
// store prev. value
self.prev_value = self.current_value;
if self.format <= Format::Ss { if self.format <= Format::Ss {
Mode::Editable(Time::Seconds, Box::new(mode)) Mode::Editable(Time::Seconds, Box::new(mode))
} else { } else {
@@ -187,6 +240,7 @@ impl<T> Clock<T> {
}; };
self.update_format(); self.update_format();
} }
pub fn edit_current_down(&mut self) { pub fn edit_current_down(&mut self) {
self.current_value = match self.mode { self.current_value = match self.mode {
Mode::Editable(Time::Decis, _) => { Mode::Editable(Time::Decis, _) => {
@@ -205,14 +259,6 @@ impl<T> Clock<T> {
self.update_mode(); self.update_mode();
} }
pub fn get_mode(&self) -> &Mode {
&self.mode
}
pub fn is_running(&self) -> bool {
self.mode == Mode::Tick
}
pub fn is_edit_mode(&self) -> bool { pub fn is_edit_mode(&self) -> bool {
matches!(self.mode, Mode::Editable(_, _)) matches!(self.mode, Mode::Editable(_, _))
} }
@@ -300,6 +346,18 @@ impl<T> Clock<T> {
self.mode == Mode::Done self.mode == Mode::Done
} }
fn done(&mut self) {
if !self.is_done() {
self.mode = Mode::Done;
let type_id = self.get_type_id().clone();
let name = self.get_name();
if let Some(tx) = &self.app_tx {
_ = tx.send(AppEvent::ClockDone(type_id, name));
};
self.done_count = Some(MAX_DONE_COUNT);
}
}
fn update_format(&mut self) { fn update_format(&mut self) {
self.format = self.get_format(); self.format = self.get_format();
} }
@@ -319,23 +377,43 @@ impl<T> Clock<T> {
Format::S Format::S
} }
} }
/// Updates inner value of `done_count`.
/// It should be called whenever `TuiEvent::Tick` is handled.
/// At first glance it might happen in `Clock::tick`, but sometimes
/// `tick` won't be called again after `Mode::Done` event (e.g. in `widget::Countdown`).
/// That's why `update_done_count` is called from "outside".
pub fn update_done_count(&mut self) {
if let Some(count) = self.done_count {
if count > 0 {
let value = count - 1;
self.done_count = Some(value)
} else {
// None means we are done and no counting anymore.
self.done_count = None
}
}
}
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Countdown {} pub struct Countdown {}
impl Clock<Countdown> { impl ClockState<Countdown> {
pub fn new(args: ClockArgs) -> Self { pub fn new(args: ClockStateArgs) -> Self {
let ClockArgs { let ClockStateArgs {
initial_value, initial_value,
current_value, current_value,
tick_value, tick_value,
style,
with_decis, with_decis,
app_tx,
} = args; } = args;
let mut instance = Self { let mut instance = Self {
type_id: ClockTypeId::Countdown,
name: None,
initial_value: initial_value.into(), initial_value: initial_value.into(),
current_value: current_value.into(), current_value: current_value.into(),
prev_value: current_value.into(),
tick_value: tick_value.into(), tick_value: tick_value.into(),
mode: if current_value == Duration::ZERO { mode: if current_value == Duration::ZERO {
Mode::Done Mode::Done
@@ -345,8 +423,9 @@ impl Clock<Countdown> {
Mode::Pause Mode::Pause
}, },
format: Format::S, format: Format::S,
style,
with_decis, with_decis,
app_tx,
done_count: None,
phantom: PhantomData, phantom: PhantomData,
}; };
// update format once // update format once
@@ -357,14 +436,14 @@ impl Clock<Countdown> {
pub fn tick(&mut self) { pub fn tick(&mut self) {
if self.mode == Mode::Tick { if self.mode == Mode::Tick {
self.current_value = self.current_value.saturating_sub(self.tick_value); self.current_value = self.current_value.saturating_sub(self.tick_value);
self.set_done(); self.check_done();
self.update_format(); self.update_format();
} }
} }
fn set_done(&mut self) { fn check_done(&mut self) {
if self.current_value.eq(&Duration::ZERO.into()) { if self.current_value.eq(&Duration::ZERO.into()) {
self.mode = Mode::Done; self.done();
} }
} }
@@ -394,18 +473,21 @@ impl Clock<Countdown> {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Timer {} pub struct Timer {}
impl Clock<Timer> { impl ClockState<Timer> {
pub fn new(args: ClockArgs) -> Self { pub fn new(args: ClockStateArgs) -> Self {
let ClockArgs { let ClockStateArgs {
initial_value, initial_value,
current_value, current_value,
tick_value, tick_value,
style,
with_decis, with_decis,
app_tx,
} = args; } = args;
let mut instance = Self { let mut instance = Self {
type_id: ClockTypeId::Timer,
name: None,
initial_value: initial_value.into(), initial_value: initial_value.into(),
current_value: current_value.into(), current_value: current_value.into(),
prev_value: current_value.into(),
tick_value: tick_value.into(), tick_value: tick_value.into(),
mode: if current_value == initial_value { mode: if current_value == initial_value {
Mode::Initial Mode::Initial
@@ -415,9 +497,10 @@ impl Clock<Timer> {
Mode::Pause Mode::Pause
}, },
format: Format::S, format: Format::S,
phantom: PhantomData,
style,
with_decis, with_decis,
app_tx,
done_count: None,
phantom: PhantomData,
}; };
// update format once // update format once
instance.update_format(); instance.update_format();
@@ -427,14 +510,14 @@ impl Clock<Timer> {
pub fn tick(&mut self) { pub fn tick(&mut self) {
if self.mode == Mode::Tick { if self.mode == Mode::Tick {
self.current_value = self.current_value.saturating_add(self.tick_value); self.current_value = self.current_value.saturating_add(self.tick_value);
self.set_done(); self.check_done();
self.update_format(); self.update_format();
} }
} }
fn set_done(&mut self) { fn check_done(&mut self) {
if self.current_value.ge(&MAX_DURATION.into()) { if self.current_value.ge(&MAX_DURATION.into()) {
self.mode = Mode::Done; self.done();
} }
} }
@@ -455,12 +538,12 @@ impl Clock<Timer> {
} }
} }
const SPACE_WIDTH: u16 = 1;
pub struct ClockWidget<T> pub struct ClockWidget<T>
where where
T: std::fmt::Debug, T: std::fmt::Debug,
{ {
style: Style,
blink: bool,
phantom: PhantomData<T>, phantom: PhantomData<T>,
} }
@@ -468,8 +551,10 @@ impl<T> ClockWidget<T>
where where
T: std::fmt::Debug, T: std::fmt::Debug,
{ {
pub fn new() -> Self { pub fn new(style: Style, blink: bool) -> Self {
Self { Self {
style,
blink,
phantom: PhantomData, phantom: PhantomData,
} }
} }
@@ -489,15 +574,15 @@ where
Format::HhMmSs => add_decis( Format::HhMmSs => add_decis(
vec![ vec![
DIGIT_WIDTH, // h DIGIT_WIDTH, // h
SPACE_WIDTH, // (space) DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // h DIGIT_WIDTH, // h
COLON_WIDTH, // : COLON_WIDTH, // :
DIGIT_WIDTH, // m DIGIT_WIDTH, // m
SPACE_WIDTH, // (space) DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // m DIGIT_WIDTH, // m
COLON_WIDTH, // : COLON_WIDTH, // :
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
SPACE_WIDTH, // (space) DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
], ],
with_decis, with_decis,
@@ -507,11 +592,11 @@ where
DIGIT_WIDTH, // h DIGIT_WIDTH, // h
COLON_WIDTH, // : COLON_WIDTH, // :
DIGIT_WIDTH, // m DIGIT_WIDTH, // m
SPACE_WIDTH, // (space) DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // m DIGIT_WIDTH, // m
COLON_WIDTH, // : COLON_WIDTH, // :
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
SPACE_WIDTH, // (space) DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
], ],
with_decis, with_decis,
@@ -519,11 +604,11 @@ where
Format::MmSs => add_decis( Format::MmSs => add_decis(
vec![ vec![
DIGIT_WIDTH, // m DIGIT_WIDTH, // m
SPACE_WIDTH, // (space) DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // m DIGIT_WIDTH, // m
COLON_WIDTH, // : COLON_WIDTH, // :
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
SPACE_WIDTH, // (space) DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
], ],
with_decis, with_decis,
@@ -533,7 +618,7 @@ where
DIGIT_WIDTH, // m DIGIT_WIDTH, // m
COLON_WIDTH, // : COLON_WIDTH, // :
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
SPACE_WIDTH, // (space) DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
], ],
with_decis, with_decis,
@@ -541,7 +626,7 @@ where
Format::Ss => add_decis( Format::Ss => add_decis(
vec![ vec![
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
SPACE_WIDTH, // (space) DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // s DIGIT_WIDTH, // s
], ],
with_decis, with_decis,
@@ -562,18 +647,35 @@ where
pub fn get_height(&self) -> u16 { pub fn get_height(&self) -> u16 {
DIGIT_HEIGHT DIGIT_HEIGHT
} }
/// Checks whether to blink the clock while rendering.
/// Its logic is based on a given `count` value.
fn should_blink(&self, count_value: &Option<u64>) -> bool {
// Example:
// if `RANGE_OF_DONE_COUNT` is 4
// then for ranges `0..4`, `8..12` etc. it will return `true`
count_value
.map(|b| (b % (RANGE_OF_DONE_COUNT * 2)) < RANGE_OF_DONE_COUNT)
.unwrap_or(false)
}
} }
impl<T> StatefulWidget for ClockWidget<T> impl<T> StatefulWidget for ClockWidget<T>
where where
T: std::fmt::Debug, T: std::fmt::Debug,
{ {
type State = Clock<T>; type State = ClockState<T>;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let with_decis = state.with_decis; let with_decis = state.with_decis;
let format = state.format; let format = state.format;
let symbol = state.style.get_digit_symbol(); // to simulate a blink effect, just use an "empty" symbol (string)
// to "empty" all digits and to have an "empty" render area
let symbol = if self.blink && self.should_blink(&state.done_count) {
" "
} else {
self.style.get_digit_symbol()
};
let widths = self.get_horizontal_lengths(&format, with_decis); let widths = self.get_horizontal_lengths(&format, with_decis);
let area = center_horizontal( let area = center_horizontal(
area, area,

View File

@@ -9,6 +9,7 @@ pub const DIGIT_WIDTH: u16 = DIGIT_SIZE as u16;
pub const DIGIT_HEIGHT: u16 = DIGIT_SIZE as u16 + 1 /* border height */; pub const DIGIT_HEIGHT: u16 = DIGIT_SIZE as u16 + 1 /* border height */;
pub const COLON_WIDTH: u16 = 4; // incl. padding left + padding right pub const COLON_WIDTH: u16 = 4; // incl. padding left + padding right
pub const DOT_WIDTH: u16 = 4; // incl. padding left + padding right pub const DOT_WIDTH: u16 = 4; // incl. padding left + padding right
pub const DIGIT_SPACE_WIDTH: u16 = 1; // space between digits
#[rustfmt::skip] #[rustfmt::skip]
const DIGIT_0: [u8; DIGIT_SIZE * DIGIT_SIZE] = [ const DIGIT_0: [u8; DIGIT_SIZE * DIGIT_SIZE] = [

View File

@@ -1,37 +1,33 @@
use crate::{ use crate::{
common::Style, common::ClockTypeId,
duration::{ONE_DECI_SECOND, ONE_HOUR, ONE_MINUTE, ONE_SECOND}, duration::{ONE_DECI_SECOND, ONE_HOUR, ONE_MINUTE, ONE_SECOND},
widgets::clock::*, widgets::clock::*,
}; };
use std::time::Duration; use std::time::Duration;
#[test] fn default_args() -> ClockStateArgs {
fn test_toggle_edit() { ClockStateArgs {
let mut c = Clock::<Timer>::new(ClockArgs {
initial_value: ONE_HOUR, initial_value: ONE_HOUR,
current_value: ONE_HOUR, current_value: ONE_HOUR,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(), with_decis: false,
with_decis: true, app_tx: None,
}); }
// off by default }
assert!(!c.is_edit_mode());
// toggle on #[test]
c.toggle_edit(); fn test_type_id() {
assert!(c.is_edit_mode()); let c = ClockState::<Timer>::new(default_args());
// toggle off assert!(matches!(c.get_type_id(), ClockTypeId::Timer));
c.toggle_edit(); let c = ClockState::<Countdown>::new(default_args());
assert!(!c.is_edit_mode()); assert!(matches!(c.get_type_id(), ClockTypeId::Countdown));
} }
#[test] #[test]
fn test_default_edit_mode_hhmmss() { fn test_default_edit_mode_hhmmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_HOUR,
current_value: ONE_HOUR,
tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: true, with_decis: true,
..default_args()
}); });
// toggle on // toggle on
@@ -41,12 +37,12 @@ fn test_default_edit_mode_hhmmss() {
#[test] #[test]
fn test_default_edit_mode_mmss() { fn test_default_edit_mode_mmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_MINUTE, initial_value: ONE_MINUTE,
current_value: ONE_MINUTE, current_value: ONE_MINUTE,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: true, with_decis: true,
app_tx: None,
}); });
// toggle on // toggle on
c.toggle_edit(); c.toggle_edit();
@@ -55,12 +51,12 @@ fn test_default_edit_mode_mmss() {
#[test] #[test]
fn test_default_edit_mode_ss() { fn test_default_edit_mode_ss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_SECOND, initial_value: ONE_SECOND,
current_value: ONE_SECOND, current_value: ONE_SECOND,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: true, with_decis: true,
app_tx: None,
}); });
// toggle on // toggle on
c.toggle_edit(); c.toggle_edit();
@@ -69,12 +65,12 @@ fn test_default_edit_mode_ss() {
#[test] #[test]
fn test_edit_next_hhmmssd() { fn test_edit_next_hhmmssd() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_HOUR, initial_value: ONE_HOUR,
current_value: ONE_HOUR, current_value: ONE_HOUR,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: true, with_decis: true,
app_tx: None,
}); });
// toggle on // toggle on
@@ -91,12 +87,12 @@ fn test_edit_next_hhmmssd() {
#[test] #[test]
fn test_edit_next_hhmmss() { fn test_edit_next_hhmmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_HOUR, initial_value: ONE_HOUR,
current_value: ONE_HOUR, current_value: ONE_HOUR,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: false, with_decis: false,
app_tx: None,
}); });
// toggle on // toggle on
@@ -111,12 +107,12 @@ fn test_edit_next_hhmmss() {
#[test] #[test]
fn test_edit_next_mmssd() { fn test_edit_next_mmssd() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_MINUTE, initial_value: ONE_MINUTE,
current_value: ONE_MINUTE, current_value: ONE_MINUTE,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: true, with_decis: true,
app_tx: None,
}); });
// toggle on // toggle on
@@ -131,12 +127,12 @@ fn test_edit_next_mmssd() {
#[test] #[test]
fn test_edit_next_mmss() { fn test_edit_next_mmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_MINUTE, initial_value: ONE_MINUTE,
current_value: ONE_MINUTE, current_value: ONE_MINUTE,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: false, with_decis: false,
app_tx: None,
}); });
// toggle on // toggle on
@@ -149,12 +145,12 @@ fn test_edit_next_mmss() {
#[test] #[test]
fn test_edit_next_ssd() { fn test_edit_next_ssd() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_SECOND * 3, initial_value: ONE_SECOND * 3,
current_value: ONE_SECOND * 3, current_value: ONE_SECOND * 3,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: true, with_decis: true,
app_tx: None,
}); });
// toggle on // toggle on
@@ -165,12 +161,12 @@ fn test_edit_next_ssd() {
#[test] #[test]
fn test_edit_next_ss() { fn test_edit_next_ss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_SECOND * 3, initial_value: ONE_SECOND * 3,
current_value: ONE_SECOND * 3, current_value: ONE_SECOND * 3,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: false, with_decis: false,
app_tx: None,
}); });
// toggle on // toggle on
@@ -182,12 +178,12 @@ fn test_edit_next_ss() {
#[test] #[test]
fn test_edit_prev_hhmmssd() { fn test_edit_prev_hhmmssd() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_HOUR, initial_value: ONE_HOUR,
current_value: ONE_HOUR, current_value: ONE_HOUR,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: true, with_decis: true,
app_tx: None,
}); });
// toggle on // toggle on
@@ -203,12 +199,12 @@ fn test_edit_prev_hhmmssd() {
#[test] #[test]
fn test_edit_prev_hhmmss() { fn test_edit_prev_hhmmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_HOUR, initial_value: ONE_HOUR,
current_value: ONE_HOUR, current_value: ONE_HOUR,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: false, with_decis: false,
app_tx: None,
}); });
// toggle on // toggle on
@@ -222,12 +218,12 @@ fn test_edit_prev_hhmmss() {
#[test] #[test]
fn test_edit_prev_mmssd() { fn test_edit_prev_mmssd() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_MINUTE, initial_value: ONE_MINUTE,
current_value: ONE_MINUTE, current_value: ONE_MINUTE,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: true, with_decis: true,
app_tx: None,
}); });
// toggle on // toggle on
@@ -243,12 +239,12 @@ fn test_edit_prev_mmssd() {
#[test] #[test]
fn test_edit_prev_mmss() { fn test_edit_prev_mmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_MINUTE, initial_value: ONE_MINUTE,
current_value: ONE_MINUTE, current_value: ONE_MINUTE,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: false, with_decis: false,
app_tx: None,
}); });
// toggle on // toggle on
@@ -262,12 +258,12 @@ fn test_edit_prev_mmss() {
#[test] #[test]
fn test_edit_prev_ssd() { fn test_edit_prev_ssd() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_SECOND, initial_value: ONE_SECOND,
current_value: ONE_SECOND, current_value: ONE_SECOND,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: true, with_decis: true,
app_tx: None,
}); });
// toggle on // toggle on
@@ -281,12 +277,12 @@ fn test_edit_prev_ssd() {
#[test] #[test]
fn test_edit_prev_ss() { fn test_edit_prev_ss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: ONE_SECOND, initial_value: ONE_SECOND,
current_value: ONE_SECOND, current_value: ONE_SECOND,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(),
with_decis: false, with_decis: false,
app_tx: None,
}); });
// toggle on // toggle on
@@ -298,12 +294,12 @@ fn test_edit_prev_ss() {
#[test] #[test]
fn test_edit_up_ss() { fn test_edit_up_ss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: Duration::ZERO, initial_value: Duration::ZERO,
current_value: Duration::ZERO, current_value: Duration::ZERO,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(), with_decis: true,
with_decis: false, app_tx: None,
}); });
// toggle on // toggle on
@@ -315,12 +311,12 @@ fn test_edit_up_ss() {
#[test] #[test]
fn test_edit_up_mmss() { fn test_edit_up_mmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: Duration::ZERO, initial_value: Duration::ZERO,
current_value: Duration::from_secs(60), current_value: Duration::from_secs(60),
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(), with_decis: true,
with_decis: false, app_tx: None,
}); });
// toggle on // toggle on
@@ -335,12 +331,12 @@ fn test_edit_up_mmss() {
#[test] #[test]
fn test_edit_up_hhmmss() { fn test_edit_up_hhmmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: Duration::ZERO, initial_value: Duration::ZERO,
current_value: Duration::from_secs(3600), current_value: Duration::from_secs(3600),
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(), with_decis: true,
with_decis: false, app_tx: None,
}); });
// toggle on // toggle on
@@ -357,12 +353,12 @@ fn test_edit_up_hhmmss() {
#[test] #[test]
fn test_edit_down_ss() { fn test_edit_down_ss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: Duration::ZERO, initial_value: Duration::ZERO,
current_value: ONE_SECOND, current_value: ONE_SECOND,
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(), with_decis: true,
with_decis: false, app_tx: None,
}); });
// toggle on // toggle on
@@ -378,12 +374,12 @@ fn test_edit_down_ss() {
#[test] #[test]
fn test_edit_down_mmss() { fn test_edit_down_mmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: Duration::ZERO, initial_value: Duration::ZERO,
current_value: Duration::from_secs(120), current_value: Duration::from_secs(120),
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(), with_decis: true,
with_decis: false, app_tx: None,
}); });
// toggle on // toggle on
@@ -401,12 +397,12 @@ fn test_edit_down_mmss() {
#[test] #[test]
fn test_edit_down_hhmmss() { fn test_edit_down_hhmmss() {
let mut c = Clock::<Timer>::new(ClockArgs { let mut c = ClockState::<Timer>::new(ClockStateArgs {
initial_value: Duration::ZERO, initial_value: Duration::ZERO,
current_value: Duration::from_secs(3600), current_value: Duration::from_secs(3600),
tick_value: ONE_DECI_SECOND, tick_value: ONE_DECI_SECOND,
style: Style::default(), with_decis: true,
with_decis: false, app_tx: None,
}); });
// toggle on // toggle on

View File

@@ -1,3 +1,15 @@
use crate::{
common::{AppTime, Style},
constants::TICK_VALUE_MS,
duration::{DurationEx, MAX_DURATION},
events::{AppEventTx, TuiEvent, TuiEventHandler},
utils::center,
widgets::{
clock::{self, ClockState, ClockStateArgs, ClockWidget, Mode as ClockMode},
edit_time::{EditTimeState, EditTimeStateArgs, EditTimeWidget},
},
};
use crossterm::event::KeyModifiers;
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
crossterm::event::KeyCode, crossterm::event::KeyCode,
@@ -5,98 +17,374 @@ use ratatui::{
text::Line, text::Line,
widgets::{StatefulWidget, Widget}, widgets::{StatefulWidget, Widget},
}; };
use std::cmp::max; use std::ops::Sub;
use std::{cmp::max, time::Duration};
use time::OffsetDateTime;
use crate::{ pub struct CountdownStateArgs {
common::Style, pub initial_value: Duration,
events::{Event, EventHandler}, pub current_value: Duration,
utils::center, pub elapsed_value: Duration,
widgets::clock::{self, Clock, ClockWidget}, pub app_time: AppTime,
}; pub with_decis: bool,
pub app_tx: AppEventTx,
#[derive(Debug, Clone)]
pub struct Countdown {
clock: Clock<clock::Countdown>,
} }
impl Countdown { /// State for Countdown Widget
pub const fn new(clock: Clock<clock::Countdown>) -> Self { pub struct CountdownState {
Self { clock } /// clock to count down
clock: ClockState<clock::Countdown>,
/// clock to count time after `DONE` - similar to Mission Elapsed Time (MET)
elapsed_clock: ClockState<clock::Timer>,
app_time: AppTime,
/// Edit by local time
edit_time: Option<EditTimeState>,
} }
pub fn set_style(&mut self, style: Style) { impl CountdownState {
self.clock.style = style; pub fn new(args: CountdownStateArgs) -> Self {
let CountdownStateArgs {
initial_value,
current_value,
elapsed_value,
with_decis,
app_time,
app_tx,
} = args;
Self {
clock: ClockState::<clock::Countdown>::new(ClockStateArgs {
initial_value,
current_value,
tick_value: Duration::from_millis(TICK_VALUE_MS),
with_decis,
app_tx: Some(app_tx.clone()),
}),
elapsed_clock: ClockState::<clock::Timer>::new(ClockStateArgs {
initial_value: Duration::ZERO,
current_value: elapsed_value,
tick_value: Duration::from_millis(TICK_VALUE_MS),
with_decis: false,
app_tx: None,
})
.with_name("MET".to_owned())
// A previous `elapsed_value > 0` means the `Clock` was running before,
// but not in `Initial` state anymore. Updating `Mode` here
// is needed to handle `Event::Tick` in `EventHandler::update` properly
.with_mode(if elapsed_value.gt(&Duration::ZERO) {
ClockMode::Pause
} else {
ClockMode::Initial
}),
app_time,
edit_time: None,
}
} }
pub fn set_with_decis(&mut self, with_decis: bool) { pub fn set_with_decis(&mut self, with_decis: bool) {
self.clock.with_decis = with_decis; self.clock.with_decis = with_decis;
self.elapsed_clock.with_decis = with_decis;
} }
pub fn get_clock(&self) -> &Clock<clock::Countdown> { pub fn get_clock(&self) -> &ClockState<clock::Countdown> {
&self.clock &self.clock
} }
pub fn is_running(&self) -> bool {
self.clock.is_running() || self.elapsed_clock.is_running()
} }
impl EventHandler for Countdown { pub fn get_elapsed_value(&self) -> &DurationEx {
fn update(&mut self, event: Event) -> Option<Event> { self.elapsed_clock.get_current_value()
let edit_mode = self.clock.is_edit_mode(); }
pub fn set_app_time(&mut self, app_time: AppTime) {
self.app_time = app_time;
}
fn time_to_edit(&self) -> OffsetDateTime {
// get current value
let d: Duration = (*self.clock.get_current_value()).into();
// transform
let dd = time::Duration::try_from(d).unwrap_or(time::Duration::ZERO);
// substract from `app_time`
OffsetDateTime::from(self.app_time).saturating_add(dd)
}
pub fn min_time_to_edit(&self) -> OffsetDateTime {
OffsetDateTime::from(self.app_time)
}
fn max_time_to_edit(&self) -> OffsetDateTime {
OffsetDateTime::from(self.app_time)
.saturating_add(time::Duration::try_from(MAX_DURATION).unwrap_or(time::Duration::ZERO))
}
fn edit_time_done(&mut self, edit_time: &mut EditTimeState) {
// get diff
let d: time::Duration = edit_time
.get_time()
.sub(OffsetDateTime::from(self.app_time));
// transfrom
let dx: DurationEx = Duration::try_from(d).unwrap_or(Duration::ZERO).into();
// update clock
self.clock.set_current_value(dx);
// remove `edit_time`
self.edit_time = None;
}
pub fn is_clock_edit_mode(&self) -> bool {
self.clock.is_edit_mode()
}
pub fn is_time_edit_mode(&self) -> bool {
self.edit_time.is_some()
}
}
impl TuiEventHandler for CountdownState {
fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
match event { match event {
Event::Tick => { TuiEvent::Tick => {
if !self.clock.is_done() {
self.clock.tick(); self.clock.tick();
} else {
self.clock.update_done_count();
self.elapsed_clock.tick();
if self.elapsed_clock.is_initial() {
self.elapsed_clock.run();
} }
Event::Key(key) if key.code == KeyCode::Char('r') => {
self.clock.reset();
} }
Event::Key(key) => match key.code { let min_time = self.min_time_to_edit();
KeyCode::Char('r') => { let max_time = self.max_time_to_edit();
self.clock.reset(); if let Some(edit_time) = &mut self.edit_time {
edit_time.set_min_time(min_time);
edit_time.set_max_time(max_time);
} }
KeyCode::Char('s') => {
self.clock.toggle_pause();
} }
KeyCode::Char('e') => { // EDIT CLOCK mode
TuiEvent::Key(key) if self.is_clock_edit_mode() => match key.code {
// skip editing
KeyCode::Esc => {
// Important: set current value first
self.clock.set_current_value(*self.clock.get_prev_value());
// before toggling back to non-edit mode
self.clock.toggle_edit(); self.clock.toggle_edit();
} }
KeyCode::Left if edit_mode => { // Apply changes and set new initial value
self.clock.edit_next(); KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
// toggle edit mode
self.clock.toggle_edit();
// set initial value
self.clock
.set_initial_value(*self.clock.get_current_value());
// always reset `elapsed_clock`
self.elapsed_clock.reset();
} }
KeyCode::Right if edit_mode => { // Apply changes
KeyCode::Char('s') => {
// toggle edit mode
self.clock.toggle_edit();
// always reset `elapsed_clock`
self.elapsed_clock.reset();
}
KeyCode::Right => {
self.clock.edit_prev(); self.clock.edit_prev();
} }
KeyCode::Up if edit_mode => { KeyCode::Left => {
self.clock.edit_next();
}
KeyCode::Up => {
self.clock.edit_up(); self.clock.edit_up();
} }
KeyCode::Down if edit_mode => { KeyCode::Down => {
self.clock.edit_down(); self.clock.edit_down();
} }
_ => return Some(event), _ => return Some(event),
}, },
// EDIT LOCAL TIME mode
TuiEvent::Key(key) if self.is_time_edit_mode() => match key.code {
// skip editing
KeyCode::Esc => {
self.edit_time = None;
}
// Apply changes and set new initial value
KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
if let Some(edit_time) = &mut self.edit_time.clone() {
// Order matters:
// 1. update current value
self.edit_time_done(edit_time);
// 2. set initial value
self.clock
.set_initial_value(*self.clock.get_current_value());
}
// always reset `elapsed_clock`
self.elapsed_clock.reset();
}
// Apply changes of editing by local time
KeyCode::Char('s') => {
if let Some(edit_time) = &mut self.edit_time.clone() {
self.edit_time_done(edit_time)
}
// always reset `elapsed_clock`
self.elapsed_clock.reset();
}
// move edit position to the left
KeyCode::Left => {
// safe unwrap because we are in `is_time_edit_mode`
self.edit_time.as_mut().unwrap().next();
}
// move edit position to the right
KeyCode::Right => {
// safe unwrap because we are in `is_time_edit_mode`
self.edit_time.as_mut().unwrap().prev();
}
// Value up
KeyCode::Up => {
// safe unwrap because of previous check in `is_time_edit_mode`
self.edit_time.as_mut().unwrap().up();
}
// Value down
KeyCode::Down => {
// safe unwrap because of previous check in `is_time_edit_mode`
self.edit_time.as_mut().unwrap().down();
}
_ => return Some(event),
},
// default mode
TuiEvent::Key(key) => match key.code {
KeyCode::Char('r') => {
// reset both clocks to use intial values
self.clock.reset();
self.elapsed_clock.reset();
// reset `edit_time` back initial value
let time = self.time_to_edit();
if let Some(edit_time) = &mut self.edit_time {
edit_time.set_time(time);
}
}
KeyCode::Char('s') => {
// toggle pause status depending on which clock is running
if !self.clock.is_done() {
self.clock.toggle_pause();
} else {
self.elapsed_clock.toggle_pause();
}
// finish `edit_time` and continue for using `clock`
if let Some(edit_time) = &mut self.edit_time.clone() {
self.edit_time_done(edit_time);
}
}
// Enter edit by local time mode
KeyCode::Char('e') if key.modifiers.contains(KeyModifiers::CONTROL) => {
// set `edit_time`
self.edit_time = Some(EditTimeState::new(EditTimeStateArgs {
time: self.time_to_edit(),
min: self.min_time_to_edit(),
max: self.max_time_to_edit(),
}));
// pause `elapsed_clock`
if self.elapsed_clock.is_running() {
self.elapsed_clock.toggle_pause();
}
}
// Enter edit clock mode
KeyCode::Char('e') => {
// toggle edit mode
self.clock.toggle_edit();
// pause `elapsed_clock`
if self.elapsed_clock.is_running() {
self.elapsed_clock.toggle_pause();
}
}
_ => return Some(event),
},
_ => return Some(event), _ => return Some(event),
} }
None None
} }
} }
pub struct CountdownWidget; pub struct Countdown {
pub style: Style,
pub blink: bool,
}
impl StatefulWidget for CountdownWidget { fn human_days_diff(a: &OffsetDateTime, b: &OffsetDateTime) -> String {
type State = Countdown; let days_diff = (a.date() - b.date()).whole_days();
match days_diff {
0 => "today".to_owned(),
1 => "tomorrow".to_owned(),
n => format!("+{n}days"),
}
}
impl StatefulWidget for Countdown {
type State = CountdownState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let clock = ClockWidget::new(); // render `edit_time` OR `clock`
let label = Line::raw((format!("Countdown {}", state.clock.get_mode())).to_uppercase()); if let Some(edit_time) = &mut state.edit_time {
let label = Line::raw(
format!(
"Countdown {} {}",
edit_time.get_selected().clone(),
human_days_diff(edit_time.get_time(), &state.app_time.into())
)
.to_uppercase(),
);
let widget = EditTimeWidget::new(self.style);
let area = center(
area,
Constraint::Length(max(widget.get_width(), label.width() as u16)),
Constraint::Length(widget.get_height() + 1 /* height of label */),
);
let [v1, v2] =
Layout::vertical(Constraint::from_lengths([widget.get_height(), 1])).areas(area);
widget.render(v1, buf, edit_time);
label.centered().render(v2, buf);
} else {
let label = Line::raw(
if state.clock.is_done() {
if state.clock.with_decis {
format!(
"Countdown {} +{}",
state.clock.get_mode(),
state
.elapsed_clock
.get_current_value()
.to_string_with_decis()
)
} else {
format!(
"Countdown {} +{}",
state.clock.get_mode(),
state.elapsed_clock.get_current_value()
)
}
} else {
format!("Countdown {}", state.clock.get_mode())
}
.to_uppercase(),
);
let widget = ClockWidget::new(self.style, self.blink);
let area = center( let area = center(
area, area,
Constraint::Length(max( Constraint::Length(max(
clock.get_width(&state.clock.get_format(), state.clock.with_decis), widget.get_width(&state.clock.get_format(), state.clock.with_decis),
label.width() as u16, label.width() as u16,
)), )),
Constraint::Length(clock.get_height() + 1 /* height of label */), Constraint::Length(widget.get_height() + 1 /* height of label */),
); );
let [v1, v2] = let [v1, v2] =
Layout::vertical(Constraint::from_lengths([clock.get_height(), 1])).areas(area); Layout::vertical(Constraint::from_lengths([widget.get_height(), 1])).areas(area);
clock.render(v1, buf, &mut state.clock); widget.render(v1, buf, &mut state.clock);
label.centered().render(v2, buf); label.centered().render(v2, buf);
} }
} }
}

231
src/widgets/edit_time.rs Normal file
View File

@@ -0,0 +1,231 @@
use std::fmt;
use time::OffsetDateTime;
use ratatui::{
buffer::Buffer,
layout::{Constraint, Layout, Rect},
widgets::{StatefulWidget, Widget},
};
use crate::{
common::Style,
widgets::clock_elements::{COLON_WIDTH, Colon, DIGIT_SPACE_WIDTH, DIGIT_WIDTH, Digit},
};
use super::clock_elements::DIGIT_HEIGHT;
#[derive(Debug, Clone)]
pub enum Selected {
Seconds,
Minutes,
Hours,
}
impl Selected {
pub fn next(&self) -> Self {
match self {
Selected::Seconds => Selected::Minutes,
Selected::Minutes => Selected::Hours,
Selected::Hours => Selected::Seconds,
}
}
pub fn prev(&self) -> Self {
match self {
Selected::Seconds => Selected::Hours,
Selected::Minutes => Selected::Seconds,
Selected::Hours => Selected::Minutes,
}
}
}
impl fmt::Display for Selected {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Selected::Seconds => write!(f, "[edit seconds]"),
Selected::Minutes => write!(f, "[edit minutes]"),
Selected::Hours => write!(f, "[edit hours]"),
}
}
}
#[derive(Debug, Clone)]
pub struct EditTimeState {
selected: Selected,
time: OffsetDateTime,
min: OffsetDateTime,
max: OffsetDateTime,
}
#[derive(Debug, Clone)]
pub struct EditTimeStateArgs {
pub time: OffsetDateTime,
pub min: OffsetDateTime,
pub max: OffsetDateTime,
}
impl EditTimeState {
pub fn new(args: EditTimeStateArgs) -> Self {
EditTimeState {
time: args.time,
min: args.min,
max: args.max,
selected: Selected::Minutes,
}
}
pub fn set_time(&mut self, time: OffsetDateTime) {
self.time = time;
}
pub fn set_min_time(&mut self, min: OffsetDateTime) {
self.min = min;
}
pub fn set_max_time(&mut self, min: OffsetDateTime) {
self.max = min;
}
pub fn get_time(&mut self) -> &OffsetDateTime {
&self.time
}
pub fn get_selected(&mut self) -> &Selected {
&self.selected
}
pub fn next(&mut self) {
self.selected = self.selected.next();
}
pub fn prev(&mut self) {
self.selected = self.selected.prev();
}
pub fn up(&mut self) {
self.time = match self.selected {
Selected::Seconds => {
if self
.time
.lt(&self.max.saturating_sub(time::Duration::new(1, 0)))
{
self.time.saturating_add(time::Duration::new(1, 0))
} else {
self.time
}
}
Selected::Minutes => {
if self
.time
.lt(&self.max.saturating_sub(time::Duration::new(60, 0)))
{
self.time.saturating_add(time::Duration::new(60, 0))
} else {
self.time
}
}
Selected::Hours => {
if self
.time
.lt(&self.max.saturating_sub(time::Duration::new(60 * 60, 0)))
{
self.time.saturating_add(time::Duration::new(60 * 60, 0))
} else {
self.time
}
}
}
}
pub fn down(&mut self) {
self.time = match self.selected {
Selected::Seconds => {
if self
.time
.ge(&self.min.saturating_add(time::Duration::new(1, 0)))
{
self.time.saturating_sub(time::Duration::new(1, 0))
} else {
self.time
}
}
Selected::Minutes => {
if self
.time
.ge(&self.min.saturating_add(time::Duration::new(60, 0)))
{
self.time.saturating_sub(time::Duration::new(60, 0))
} else {
self.time
}
}
Selected::Hours => {
if self
.time
.ge(&self.min.saturating_add(time::Duration::new(60 * 60, 0)))
{
self.time.saturating_sub(time::Duration::new(60 * 60, 0))
} else {
self.time
}
}
}
}
}
#[derive(Debug, Clone)]
pub struct EditTimeWidget {
style: Style,
}
impl EditTimeWidget {
pub fn new(style: Style) -> Self {
Self { style }
}
fn get_horizontal_lengths(&self) -> Vec<u16> {
vec![
DIGIT_WIDTH, // h
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // h
COLON_WIDTH, // :
DIGIT_WIDTH, // m
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // m
COLON_WIDTH, // :
DIGIT_WIDTH, // s
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // s
]
}
pub fn get_width(&self) -> u16 {
self.get_horizontal_lengths().iter().sum()
}
pub fn get_height(&self) -> u16 {
DIGIT_HEIGHT
}
}
impl StatefulWidget for EditTimeWidget {
type State = EditTimeState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let symbol = self.style.get_digit_symbol();
let edit_hours = matches!(state.selected, Selected::Hours);
let edit_minutes = matches!(state.selected, Selected::Minutes);
let edit_secs = matches!(state.selected, Selected::Seconds);
let [hh, _, h, c_hm, mm, _, m, c_ms, ss, _, s] =
Layout::horizontal(Constraint::from_lengths(self.get_horizontal_lengths())).areas(area);
Digit::new((state.time.hour() as u64) / 10, edit_hours, symbol).render(hh, buf);
Digit::new((state.time.hour() as u64) % 10, edit_hours, symbol).render(h, buf);
Colon::new(symbol).render(c_hm, buf);
Digit::new((state.time.minute() as u64) / 10, edit_minutes, symbol).render(mm, buf);
Digit::new((state.time.minute() as u64) % 10, edit_minutes, symbol).render(m, buf);
Colon::new(symbol).render(c_ms, buf);
Digit::new((state.time.second() as u64) / 10, edit_secs, symbol).render(ss, buf);
Digit::new((state.time.second() as u64) % 10, edit_secs, symbol).render(s, buf);
}
}

View File

@@ -1,25 +1,57 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::common::Content; use crate::common::{AppEditMode, AppTime, AppTimeFormat, Content};
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
layout::{Constraint, Layout, Rect}, layout::{Constraint, Layout, Rect},
style::{Modifier, Style}, style::{Modifier, Style},
symbols::{border, scrollbar}, symbols::{border, scrollbar},
text::{Line, Span}, text::{Line, Span},
widgets::{Block, Borders, Cell, Row, Table, Widget}, widgets::{Block, Borders, Cell, Row, StatefulWidget, Table, Widget},
}; };
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Footer { pub struct FooterState {
pub show_menu: bool, show_menu: bool,
pub running_clock: bool, app_time_format: AppTimeFormat,
pub selected_content: Content,
pub edit_mode: bool,
} }
impl Widget for Footer { impl FooterState {
fn render(self, area: Rect, buf: &mut Buffer) { pub const fn new(show_menu: bool, app_time_format: AppTimeFormat) -> Self {
Self {
show_menu,
app_time_format,
}
}
pub fn set_show_menu(&mut self, value: bool) {
self.show_menu = value;
}
pub const fn get_show_menu(&self) -> bool {
self.show_menu
}
pub const fn app_time_format(&self) -> &AppTimeFormat {
&self.app_time_format
}
pub fn toggle_app_time_format(&mut self) {
self.app_time_format = self.app_time_format.next();
}
}
#[derive(Debug)]
pub struct Footer {
pub running_clock: bool,
pub selected_content: Content,
pub app_edit_mode: AppEditMode,
pub app_time: AppTime,
}
impl StatefulWidget for Footer {
type State = FooterState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let content_labels: BTreeMap<Content, &str> = BTreeMap::from([ let content_labels: BTreeMap<Content, &str> = BTreeMap::from([
(Content::Countdown, "[c]ountdown"), (Content::Countdown, "[c]ountdown"),
(Content::Timer, "[t]imer"), (Content::Timer, "[t]imer"),
@@ -31,15 +63,25 @@ impl Widget for Footer {
let [border_area, menu_area] = let [border_area, menu_area] =
Layout::vertical([Constraint::Length(1), Constraint::Percentage(100)]).areas(area); Layout::vertical([Constraint::Length(1), Constraint::Percentage(100)]).areas(area);
Block::new() Block::new()
.borders(Borders::TOP) .borders(Borders::TOP)
.title( .title(
format! {"[m]enu {:} ", if self.show_menu {scrollbar::VERTICAL.end} else {scrollbar::VERTICAL.begin}}, format! {"[m]enu {:} ", if state.show_menu {scrollbar::VERTICAL.end} else {scrollbar::VERTICAL.begin}},
) )
.title(
Line::from(
match state.app_time_format {
// `Hidden` -> no (empty) title
AppTimeFormat::Hidden => "".into(),
// others -> add some space around
_ => format!(" {} ", self.app_time.format(&state.app_time_format))
}
).right_aligned())
.border_set(border::PLAIN) .border_set(border::PLAIN)
.render(border_area, buf); .render(border_area, buf);
// show menu // show menu
if self.show_menu { if state.show_menu {
let content_labels: Vec<Span> = content_labels let content_labels: Vec<Span> = content_labels
.iter() .iter()
.enumerate() .enumerate()
@@ -47,7 +89,7 @@ impl Widget for Footer {
let mut style = Style::default(); let mut style = Style::default();
// Add space for all except last // Add space for all except last
let label = if index < content_labels.len() - 1 { let label = if index < content_labels.len() - 1 {
format!("{} ", label) format!("{label} ")
} else { } else {
label.to_string() label.to_string()
}; };
@@ -60,9 +102,9 @@ impl Widget for Footer {
const SPACE: &str = " "; // 2 empty spaces const SPACE: &str = " "; // 2 empty spaces
let widths = [Constraint::Length(12), Constraint::Percentage(100)]; let widths = [Constraint::Length(12), Constraint::Percentage(100)];
Table::new( let table = Table::new(
[ [
// content // screens
Row::new(vec![ Row::new(vec![
Cell::from(Span::styled( Cell::from(Span::styled(
"screens", "screens",
@@ -70,7 +112,7 @@ impl Widget for Footer {
)), )),
Cell::from(Line::from(content_labels)), Cell::from(Line::from(content_labels)),
]), ]),
// format // appearance
Row::new(vec![ Row::new(vec![
Cell::from(Span::styled( Cell::from(Span::styled(
"appearance", "appearance",
@@ -80,56 +122,114 @@ impl Widget for Footer {
Span::from("[,]change style"), Span::from("[,]change style"),
Span::from(SPACE), Span::from(SPACE),
Span::from("[.]toggle deciseconds"), Span::from("[.]toggle deciseconds"),
Span::from(SPACE),
Span::from(format!(
"[:]toggle {} time",
match self.app_time {
AppTime::Local(_) => "local",
AppTime::Utc(_) => "utc",
}
)),
])), ])),
]), ]),
// edit // controls - 1. row
Row::new(vec![ Row::new(vec![
Cell::from(Span::styled( Cell::from(Span::styled(
"controls", "controls",
Style::default().add_modifier(Modifier::BOLD), Style::default().add_modifier(Modifier::BOLD),
)), )),
Cell::from(Line::from({ Cell::from(Line::from({
if self.edit_mode { match self.app_edit_mode {
vec![ AppEditMode::None => {
Span::from("[e]dit done"), let mut spans = vec![Span::from(if self.running_clock {
Span::from(SPACE),
Span::from(format!(
"[{} {}]edit selection",
scrollbar::HORIZONTAL.begin,
scrollbar::HORIZONTAL.end
)), // ← →,
Span::from(SPACE),
Span::from(format!("[{}]edit up", scrollbar::VERTICAL.begin)), // ↑
Span::from(SPACE),
Span::from(format!("[{}]edit up", scrollbar::VERTICAL.end)), // ↓,
]
} else {
let mut spans = vec![
Span::from(if self.running_clock {
"[s]top" "[s]top"
} else { } else {
"[s]tart" "[s]tart"
}), })];
Span::from(SPACE), spans.extend_from_slice(&[
Span::from("[r]eset"),
Span::from(SPACE), Span::from(SPACE),
Span::from("[e]dit"), Span::from("[e]dit"),
]; ]);
if self.selected_content == Content::Countdown {
spans.extend_from_slice(&[
Span::from(SPACE),
Span::from("[^e]dit by local time"),
]);
}
spans.extend_from_slice(&[
Span::from(SPACE),
Span::from("[r]eset clock"),
]);
if self.selected_content == Content::Pomodoro { if self.selected_content == Content::Pomodoro {
spans.extend_from_slice(&[ spans.extend_from_slice(&[
Span::from(SPACE), Span::from(SPACE),
Span::from("[← →]switch work/pause"), Span::from("[^r]eset clocks+rounds"),
]); ]);
} }
spans spans
} }
_ => {
let mut spans = vec![Span::from("[s]ave changes")];
if self.selected_content == Content::Countdown
|| self.selected_content == Content::Pomodoro
{
spans.extend_from_slice(&[
Span::from(SPACE),
Span::from("[^s]ave initial value"),
]);
}
spans.extend_from_slice(&[
Span::from(SPACE),
Span::from("[esc]skip changes"),
]);
spans
}
}
})),
]),
// controls - 2. row
Row::new(vec![
Cell::from(Line::from("")),
Cell::from(Line::from({
match self.app_edit_mode {
AppEditMode::None => {
let mut spans = vec![];
if self.selected_content == Content::Pomodoro {
spans.extend_from_slice(&[Span::from(
"[← →]switch work/pause",
)]);
}
spans
}
_ => vec![
Span::from(format!(
// ← →,
"[{} {}]change selection",
scrollbar::HORIZONTAL.begin,
scrollbar::HORIZONTAL.end
)),
Span::from(SPACE),
Span::from(format!(
// ↑
"[{}]edit up",
scrollbar::VERTICAL.begin
)),
Span::from(SPACE),
Span::from(format!(
// ↓
"[{}]edit up",
scrollbar::VERTICAL.end
)),
],
}
})), })),
]), ]),
], ],
widths, widths,
) )
.column_spacing(1) .column_spacing(1);
.render(menu_area, buf);
Widget::render(table, menu_area, buf);
} }
} }
} }

View File

@@ -1,24 +1,20 @@
use crate::{ use crate::{
common::Style, common::Style,
constants::TICK_VALUE_MS, constants::TICK_VALUE_MS,
events::{Event, EventHandler}, events::{AppEventTx, TuiEvent, TuiEventHandler},
utils::center, utils::center,
widgets::clock::{Clock, ClockWidget, Countdown}, widgets::clock::{ClockState, ClockStateArgs, ClockWidget, Countdown},
}; };
use crossterm::event::{KeyCode, KeyModifiers};
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
crossterm::event::KeyCode,
layout::{Constraint, Layout, Rect}, layout::{Constraint, Layout, Rect},
text::Line, text::Line,
widgets::{StatefulWidget, Widget}, widgets::{StatefulWidget, Widget},
}; };
use std::{cmp::max, time::Duration};
use strum::Display;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{cmp::max, time::Duration};
use super::clock::ClockArgs; use strum::Display;
#[derive(Debug, Clone, Display, Hash, Eq, PartialEq, Deserialize, Serialize)] #[derive(Debug, Clone, Display, Hash, Eq, PartialEq, Deserialize, Serialize)]
pub enum Mode { pub enum Mode {
@@ -26,20 +22,19 @@ pub enum Mode {
Pause, Pause,
} }
#[derive(Debug, Clone)]
pub struct ClockMap { pub struct ClockMap {
work: Clock<Countdown>, work: ClockState<Countdown>,
pause: Clock<Countdown>, pause: ClockState<Countdown>,
} }
impl ClockMap { impl ClockMap {
fn get_mut(&mut self, mode: &Mode) -> &mut Clock<Countdown> { fn get_mut(&mut self, mode: &Mode) -> &mut ClockState<Countdown> {
match mode { match mode {
Mode::Work => &mut self.work, Mode::Work => &mut self.work,
Mode::Pause => &mut self.pause, Mode::Pause => &mut self.pause,
} }
} }
fn get(&self, mode: &Mode) -> &Clock<Countdown> { fn get(&self, mode: &Mode) -> &ClockState<Countdown> {
match mode { match mode {
Mode::Work => &self.work, Mode::Work => &self.work,
Mode::Pause => &self.pause, Mode::Pause => &self.pause,
@@ -47,77 +42,89 @@ impl ClockMap {
} }
} }
#[derive(Debug, Clone)] pub struct PomodoroState {
pub struct Pomodoro {
mode: Mode, mode: Mode,
clock_map: ClockMap, clock_map: ClockMap,
round: u64,
} }
pub struct PomodoroArgs { pub struct PomodoroStateArgs {
pub mode: Mode, pub mode: Mode,
pub initial_value_work: Duration, pub initial_value_work: Duration,
pub current_value_work: Duration, pub current_value_work: Duration,
pub initial_value_pause: Duration, pub initial_value_pause: Duration,
pub current_value_pause: Duration, pub current_value_pause: Duration,
pub style: Style,
pub with_decis: bool, pub with_decis: bool,
pub app_tx: AppEventTx,
pub round: u64,
} }
impl Pomodoro { impl PomodoroState {
pub fn new(args: PomodoroArgs) -> Self { pub fn new(args: PomodoroStateArgs) -> Self {
let PomodoroArgs { let PomodoroStateArgs {
mode, mode,
initial_value_work, initial_value_work,
current_value_work, current_value_work,
initial_value_pause, initial_value_pause,
current_value_pause, current_value_pause,
style,
with_decis, with_decis,
app_tx,
round,
} = args; } = args;
Self { Self {
mode, mode,
clock_map: ClockMap { clock_map: ClockMap {
work: Clock::<Countdown>::new(ClockArgs { work: ClockState::<Countdown>::new(ClockStateArgs {
initial_value: initial_value_work, initial_value: initial_value_work,
current_value: current_value_work, current_value: current_value_work,
tick_value: Duration::from_millis(TICK_VALUE_MS), tick_value: Duration::from_millis(TICK_VALUE_MS),
style,
with_decis, with_decis,
}), app_tx: Some(app_tx.clone()),
pause: Clock::<Countdown>::new(ClockArgs { })
.with_name("Work".to_owned()),
pause: ClockState::<Countdown>::new(ClockStateArgs {
initial_value: initial_value_pause, initial_value: initial_value_pause,
current_value: current_value_pause, current_value: current_value_pause,
tick_value: Duration::from_millis(TICK_VALUE_MS), tick_value: Duration::from_millis(TICK_VALUE_MS),
style,
with_decis, with_decis,
}), app_tx: Some(app_tx),
})
.with_name("Pause".to_owned()),
}, },
round,
} }
} }
fn get_clock_mut(&mut self) -> &mut Clock<Countdown> { fn get_clock_mut(&mut self) -> &mut ClockState<Countdown> {
self.clock_map.get_mut(&self.mode) self.clock_map.get_mut(&self.mode)
} }
pub fn get_clock(&self) -> &Clock<Countdown> { pub fn get_clock(&self) -> &ClockState<Countdown> {
self.clock_map.get(&self.mode) self.clock_map.get(&self.mode)
} }
pub fn get_clock_work(&self) -> &Clock<Countdown> { pub fn get_clock_work(&self) -> &ClockState<Countdown> {
&self.clock_map.work &self.clock_map.work
} }
pub fn get_clock_pause(&self) -> &Clock<Countdown> { pub fn get_clock_work_mut(&mut self) -> &mut ClockState<Countdown> {
self.clock_map.get_mut(&Mode::Work)
}
pub fn get_clock_pause(&self) -> &ClockState<Countdown> {
&self.clock_map.pause &self.clock_map.pause
} }
pub fn get_clock_pause_mut(&mut self) -> &mut ClockState<Countdown> {
self.clock_map.get_mut(&Mode::Pause)
}
pub fn get_mode(&self) -> &Mode { pub fn get_mode(&self) -> &Mode {
&self.mode &self.mode
} }
pub fn set_style(&mut self, style: Style) { pub fn get_round(&self) -> u64 {
self.clock_map.work.style = style; self.round
self.clock_map.pause.style = style;
} }
pub fn set_with_decis(&mut self, with_decis: bool) { pub fn set_with_decis(&mut self, with_decis: bool) {
@@ -133,40 +140,84 @@ impl Pomodoro {
} }
} }
impl EventHandler for Pomodoro { impl TuiEventHandler for PomodoroState {
fn update(&mut self, event: Event) -> Option<Event> { fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
let edit_mode = self.get_clock().is_edit_mode(); let edit_mode = self.get_clock().is_edit_mode();
match event { match event {
Event::Tick => { TuiEvent::Tick => {
self.get_clock_mut().tick(); self.get_clock_mut().tick();
self.get_clock_mut().update_done_count();
} }
Event::Key(key) => match key.code { // EDIT mode
TuiEvent::Key(key) if edit_mode => match key.code {
// Skip changes
KeyCode::Esc => {
let clock = self.get_clock_mut();
// Important: set current value first
clock.set_current_value(*clock.get_prev_value());
// before toggling back to non-edit mode
clock.toggle_edit();
}
// Apply changes and update initial value
KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.get_clock_mut().toggle_edit();
// update initial value
let c = *self.get_clock().get_current_value();
self.get_clock_mut().set_initial_value(c);
}
// Apply changes
KeyCode::Char('s') => {
self.get_clock_mut().toggle_edit();
}
// Value up
KeyCode::Up => {
self.get_clock_mut().edit_up();
}
// Value down
KeyCode::Down => {
self.get_clock_mut().edit_down();
}
// move edit position to the left
KeyCode::Left => {
self.get_clock_mut().edit_next();
}
// move edit position to the right
KeyCode::Right => {
self.get_clock_mut().edit_prev();
}
_ => return Some(event),
},
// default mode
TuiEvent::Key(key) => match key.code {
// Toggle run/pause
KeyCode::Char('s') => { KeyCode::Char('s') => {
self.get_clock_mut().toggle_pause(); self.get_clock_mut().toggle_pause();
} }
// Enter edit mode
KeyCode::Char('e') => { KeyCode::Char('e') => {
self.get_clock_mut().toggle_edit(); self.get_clock_mut().toggle_edit();
} }
KeyCode::Left if edit_mode => { // toggle WORK/PAUSE
self.get_clock_mut().edit_next();
}
KeyCode::Left => { KeyCode::Left => {
// `next` is acting as same as a `prev` function, we don't have // `next` is acting as same as a "prev" function we don't have
self.next(); self.next();
} }
KeyCode::Right if edit_mode => { // toggle WORK/PAUSE
self.get_clock_mut().edit_prev();
}
KeyCode::Right => { KeyCode::Right => {
self.next(); self.next();
} }
KeyCode::Up if edit_mode => { // reset rounds AND clocks
self.get_clock_mut().edit_up(); KeyCode::Char('r') if key.modifiers.contains(KeyModifiers::CONTROL) => {
} self.round = 1;
KeyCode::Down if edit_mode => { self.get_clock_work_mut().reset();
self.get_clock_mut().edit_down(); self.get_clock_pause_mut().reset();
} }
// reset current clock
KeyCode::Char('r') => { KeyCode::Char('r') => {
// increase round before (!!) resetting the clock
if self.get_mode() == &Mode::Work && self.get_clock().is_done() {
self.round += 1;
}
self.get_clock_mut().reset(); self.get_clock_mut().reset();
} }
_ => return Some(event), _ => return Some(event),
@@ -177,12 +228,15 @@ impl EventHandler for Pomodoro {
} }
} }
pub struct PomodoroWidget; pub struct PomodoroWidget {
pub style: Style,
pub blink: bool,
}
impl StatefulWidget for PomodoroWidget { impl StatefulWidget for PomodoroWidget {
type State = Pomodoro; type State = PomodoroState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let clock_widget = ClockWidget::new(); let clock_widget = ClockWidget::new(self.style, self.blink);
let label = Line::raw( let label = Line::raw(
(format!( (format!(
"Pomodoro {} {}", "Pomodoro {} {}",
@@ -191,6 +245,7 @@ impl StatefulWidget for PomodoroWidget {
)) ))
.to_uppercase(), .to_uppercase(),
); );
let label_round = Line::raw((format!("round {}", state.get_round(),)).to_uppercase());
let area = center( let area = center(
area, area,
@@ -201,13 +256,25 @@ impl StatefulWidget for PomodoroWidget {
), ),
label.width() as u16, label.width() as u16,
)), )),
Constraint::Length(clock_widget.get_height() + 1 /* height of mode_str */), Constraint::Length(
// empty label + height of `label` + `label_round`
clock_widget.get_height() + 3,
),
); );
let [v1, v2] = let [v1, v2, v3, v4] = Layout::vertical(Constraint::from_lengths([
Layout::vertical(Constraint::from_lengths([clock_widget.get_height(), 1])).areas(area); 1,
clock_widget.get_height(),
1,
1,
]))
.areas(area);
clock_widget.render(v1, buf, state.get_clock_mut()); // empty line keep everything in center vertically comparing to other
label.centered().render(v2, buf); // views (which have one label below the clock only)
Line::raw("").centered().render(v1, buf);
clock_widget.render(v2, buf, state.get_clock_mut());
label.centered().render(v3, buf);
label_round.centered().render(v4, buf);
} }
} }

View File

@@ -1,8 +1,8 @@
use crate::{ use crate::{
common::Style, common::Style,
events::{Event, EventHandler}, events::{TuiEvent, TuiEventHandler},
utils::center, utils::center,
widgets::clock::{self, Clock, ClockWidget}, widgets::clock::{self, ClockState, ClockWidget},
}; };
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
@@ -13,58 +13,77 @@ use ratatui::{
}; };
use std::cmp::max; use std::cmp::max;
#[derive(Debug, Clone)] pub struct TimerState {
pub struct Timer { clock: ClockState<clock::Timer>,
clock: Clock<clock::Timer>,
} }
impl Timer { impl TimerState {
pub const fn new(clock: Clock<clock::Timer>) -> Self { pub const fn new(clock: ClockState<clock::Timer>) -> Self {
Self { clock } Self { clock }
} }
pub fn set_style(&mut self, style: Style) {
self.clock.style = style;
}
pub fn set_with_decis(&mut self, with_decis: bool) { pub fn set_with_decis(&mut self, with_decis: bool) {
self.clock.with_decis = with_decis; self.clock.with_decis = with_decis;
} }
pub fn get_clock(&self) -> &Clock<clock::Timer> { pub fn get_clock(&self) -> &ClockState<clock::Timer> {
&self.clock &self.clock
} }
} }
impl EventHandler for Timer { impl TuiEventHandler for TimerState {
fn update(&mut self, event: Event) -> Option<Event> { fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
let edit_mode = self.clock.is_edit_mode(); let edit_mode = self.clock.is_edit_mode();
match event { match event {
Event::Tick => { TuiEvent::Tick => {
self.clock.tick(); self.clock.tick();
self.clock.update_done_count();
} }
Event::Key(key) => match key.code { // EDIT mode
TuiEvent::Key(key) if edit_mode => match key.code {
// Skip changes
KeyCode::Esc => {
// Important: set current value first
self.clock.set_current_value(*self.clock.get_prev_value());
// before toggling back to non-edit mode
self.clock.toggle_edit();
}
// Apply changes
KeyCode::Char('s') => {
self.clock.toggle_edit();
}
// move change position to the left
KeyCode::Left => {
self.clock.edit_next();
}
// move change position to the right
KeyCode::Right => {
self.clock.edit_prev();
}
// change value up
KeyCode::Up => {
self.clock.edit_up();
}
// change value down
KeyCode::Down => {
self.clock.edit_down();
}
_ => return Some(event),
},
// default mode
TuiEvent::Key(key) => match key.code {
// Toggle run/pause
KeyCode::Char('s') => { KeyCode::Char('s') => {
self.clock.toggle_pause(); self.clock.toggle_pause();
} }
// reset clock
KeyCode::Char('r') => { KeyCode::Char('r') => {
self.clock.reset(); self.clock.reset();
} }
// enter edit mode
KeyCode::Char('e') => { KeyCode::Char('e') => {
self.clock.toggle_edit(); self.clock.toggle_edit();
} }
KeyCode::Left if edit_mode => {
self.clock.edit_next();
}
KeyCode::Right if edit_mode => {
self.clock.edit_prev();
}
KeyCode::Up if edit_mode => {
self.clock.edit_up();
}
KeyCode::Down if edit_mode => {
self.clock.edit_down();
}
_ => return Some(event), _ => return Some(event),
}, },
_ => return Some(event), _ => return Some(event),
@@ -73,13 +92,16 @@ impl EventHandler for Timer {
} }
} }
pub struct TimerWidget; pub struct Timer {
pub style: Style,
pub blink: bool,
}
impl StatefulWidget for &TimerWidget { impl StatefulWidget for Timer {
type State = Timer; type State = TimerState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let clock = &mut state.clock; let clock = &mut state.clock;
let clock_widget = ClockWidget::new(); let clock_widget = ClockWidget::new(self.style, self.blink);
let label = Line::raw((format!("Timer {}", clock.get_mode())).to_uppercase()); let label = Line::raw((format!("Timer {}", clock.get_mode())).to_uppercase());
let area = center( let area = center(