Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e700691ba | ||
|
|
c29f8c5d1b | ||
|
|
ad11ff2c48 | ||
|
|
3d9b235f12 | ||
|
|
e094d7d81b | ||
|
|
843c4d019d | ||
|
|
e95ecb9e9c | ||
|
|
886deb3311 | ||
|
|
7ff167368d | ||
|
|
a54b1b409a | ||
|
|
8f50bc5fc6 | ||
|
|
d3c436da0b | ||
|
|
97787f718d | ||
|
|
557fcf95f0 | ||
|
|
ec18da0664 | ||
|
|
59c99f4f5c | ||
|
|
6d2bf5ac09 | ||
|
|
b1efb1eb62 |
3
.github/workflows/ci.yml
vendored
3
.github/workflows/ci.yml
vendored
@@ -12,7 +12,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: DeterminateSystems/nix-installer-action@main
|
||||
- uses: DeterminateSystems/magic-nix-cache-action@main
|
||||
- name: Check formatting
|
||||
run: nix develop --command cargo fmt --all -- --check
|
||||
- name: Run clippy
|
||||
@@ -25,7 +24,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: DeterminateSystems/nix-installer-action@main
|
||||
- uses: DeterminateSystems/magic-nix-cache-action@main
|
||||
- name: Run tests
|
||||
run: nix develop --command cargo test
|
||||
|
||||
@@ -34,6 +32,5 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: DeterminateSystems/nix-installer-action@main
|
||||
- uses: DeterminateSystems/magic-nix-cache-action@main
|
||||
- name: Build project
|
||||
run: nix build .#timr
|
||||
|
||||
11
.github/workflows/release.yml
vendored
11
.github/workflows/release.yml
vendored
@@ -31,7 +31,7 @@ jobs:
|
||||
- os: ubuntu-latest
|
||||
os_target: linux
|
||||
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_target: windows
|
||||
binary_name: timr-tui.exe
|
||||
@@ -43,14 +43,17 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: DeterminateSystems/nix-installer-action@main
|
||||
- uses: DeterminateSystems/magic-nix-cache-action@main
|
||||
|
||||
- name: Build (windows)
|
||||
if: matrix.os_target == 'windows'
|
||||
run: nix build .#windows
|
||||
|
||||
- name: Build (linux/macos)
|
||||
if: matrix.os_target != 'windows'
|
||||
- name: Build (linux)
|
||||
if: matrix.os_target == 'linux'
|
||||
run: nix build .#linuxStatic
|
||||
|
||||
- name: Build (macos)
|
||||
if: matrix.os_target == 'macos'
|
||||
run: nix build
|
||||
|
||||
- name: Copy artifact
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -18,3 +18,6 @@ result/**/*
|
||||
#.idea/
|
||||
#
|
||||
.direnv
|
||||
|
||||
# ignore (possible) sound files
|
||||
**/*.{mp3,wav}
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
style_edition = "2024"
|
||||
reorder_imports = true
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
31
CHANGELOG.md
31
CHANGELOG.md
@@ -1,5 +1,36 @@
|
||||
# Changelog
|
||||
|
||||
## 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` 🎉
|
||||
|
||||
1597
Cargo.lock
generated
1597
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
18
Cargo.toml
18
Cargo.toml
@@ -1,9 +1,10 @@
|
||||
[package]
|
||||
name = "timr-tui"
|
||||
version = "1.0.0"
|
||||
version = "1.2.0"
|
||||
description = "TUI to organize your time: Pomodoro, Countdown, Timer."
|
||||
edition = "2021"
|
||||
rust-version = "1.82.0"
|
||||
edition = "2024"
|
||||
# Reminder: Always keep `channel` in `rust-toolchain.toml` in sync with `rust-version`.
|
||||
rust-version = "1.85.0"
|
||||
homepage = "https://github.com/sectore/timr-tui"
|
||||
repository = "https://github.com/sectore/timr-tui"
|
||||
readme = "README.md"
|
||||
@@ -13,7 +14,7 @@ categories = ["command-line-utilities"]
|
||||
|
||||
[dependencies]
|
||||
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"
|
||||
futures = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
@@ -27,3 +28,12 @@ tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
|
||||
directories = "5.0.1"
|
||||
clap = { version = "4.5.23", features = ["derive"] }
|
||||
time = { version = "0.3.37", features = ["formatting", "local-offset"] }
|
||||
notify-rust = "4.11.4"
|
||||
rodio = { version = "0.20.1", features = [
|
||||
"symphonia-mp3",
|
||||
"symphonia-wav",
|
||||
], default-features = false, optional = true }
|
||||
thiserror = { version = "2.0.11", optional = true }
|
||||
|
||||
[features]
|
||||
sound = ["dep:rodio", "dep:thiserror"]
|
||||
|
||||
65
README.md
65
README.md
@@ -68,18 +68,27 @@ timr-tui --help
|
||||
Usage: timr-tui [OPTIONS]
|
||||
|
||||
Options:
|
||||
-c, --countdown <COUNTDOWN> Countdown time to start from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss' [default: 10:00]
|
||||
-w, --work <WORK> Work time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss' [default: 25:00]
|
||||
-p, --pause <PAUSE> Pause time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss' [default: 5:00]
|
||||
-d, --decis Wether to show deciseconds or not. [default: false]
|
||||
-m, --mode <MODE> Mode to start with. [possible values: countdown, timer, pomodoro] [default: timer]
|
||||
--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] [default: full]
|
||||
-r, --reset Reset stored values to default.
|
||||
-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'
|
||||
-p, --pause <PAUSE> Pause time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss'
|
||||
-d, --decis Show deciseconds.
|
||||
-m, --mode <MODE> Mode to start with. [possible values: countdown, timer, pomodoro]
|
||||
-s, --style <STYLE> Style to display time with. [possible values: full, light, medium, dark, thick, cross, braille]
|
||||
--menu Open the menu.
|
||||
-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
|
||||
-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.
|
||||
```
|
||||
|
||||
|
||||
# Installation
|
||||
|
||||
## Cargo
|
||||
@@ -131,20 +140,26 @@ If you have [`direnv`](https://direnv.net) installed, run `direnv allow` once to
|
||||
### Commands
|
||||
|
||||
```sh
|
||||
just --list
|
||||
just
|
||||
|
||||
Available recipes:
|
||||
build # build app
|
||||
b # alias for `build`
|
||||
default
|
||||
format # format files
|
||||
f # alias for `format`
|
||||
lint # lint
|
||||
l # alias for `lint`
|
||||
run # run app
|
||||
r # alias for `run`
|
||||
test # run tests
|
||||
t # alias for `test`
|
||||
build # build app [alias: b]
|
||||
default # list commands
|
||||
demo-blink # build demo: blink animation [alias: db]
|
||||
demo-countdown # build demo: countdown [alias: dc]
|
||||
demo-countdown-met # build demo: countdown + met [alias: dcm]
|
||||
demo-decis # build demo: deciseconds [alias: dd]
|
||||
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]
|
||||
format # format files [alias: f]
|
||||
lint # lint [alias: l]
|
||||
run # run app [alias: r]
|
||||
run-sound path # run app while sound feature is enabled. It expects a path to a sound file. [alias: rs]
|
||||
test # run tests [alias: t]
|
||||
```
|
||||
|
||||
### Build
|
||||
@@ -152,6 +167,8 @@ Available recipes:
|
||||
- Linux
|
||||
```sh
|
||||
nix build
|
||||
# or for bulding w/ statically linked binaries
|
||||
nix build .#linuxStatic
|
||||
```
|
||||
|
||||
- Windows (cross-compilation)
|
||||
@@ -176,7 +193,9 @@ C:/Users/{user}/AppData/Local/timr-tui/data/app.data
|
||||
|
||||
## 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
|
||||
# Linux
|
||||
@@ -186,3 +205,5 @@ In `debug` mode only. Locations:
|
||||
# `Windows`
|
||||
C:/Users/{user}/AppData/Local/timr-tui/logs/app.log
|
||||
```
|
||||
|
||||
Optional: You can use a custom directory by passing it via `--log` arg.
|
||||
|
||||
BIN
demo/blink.gif
Normal file
BIN
demo/blink.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
23
demo/blink.tape
Normal file
23
demo/blink.tape
Normal 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
|
||||
24
flake.lock
generated
24
flake.lock
generated
@@ -2,11 +2,11 @@
|
||||
"nodes": {
|
||||
"crane": {
|
||||
"locked": {
|
||||
"lastModified": 1733286231,
|
||||
"narHash": "sha256-mlIDSv1/jqWnH8JTiOV7GMUNPCXL25+6jmD+7hdxx5o=",
|
||||
"lastModified": 1739936662,
|
||||
"narHash": "sha256-x4syUjNUuRblR07nDPeLDP7DpphaBVbUaSoeZkFbGSk=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "af1556ecda8bcf305820f68ec2f9d77b41d9cc80",
|
||||
"rev": "19de14aaeb869287647d9461cbd389187d8ecdb7",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -23,11 +23,11 @@
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1732689334,
|
||||
"narHash": "sha256-yKI1KiZ0+bvDvfPTQ1ZT3oP/nIu3jPYm4dnbRd6hYg4=",
|
||||
"lastModified": 1740378829,
|
||||
"narHash": "sha256-cwmm7F73aQFJY6YN1roNibNKwxT6FlfXkG3MEbpSp7Q=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "a8a983027ca02b363dfc82fbe3f7d9548a8d3dce",
|
||||
"rev": "92823f1b0c919d7e2d806956aaf98e90f3761ab7",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -56,11 +56,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1733212471,
|
||||
"narHash": "sha256-M1+uCoV5igihRfcUKrr1riygbe73/dzNnzPsmaLCmpo=",
|
||||
"lastModified": 1740367490,
|
||||
"narHash": "sha256-WGaHVAjcrv+Cun7zPlI41SerRtfknGQap281+AakSAw=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "55d15ad12a74eb7d4646254e13638ad0c4128776",
|
||||
"rev": "0196c0175e9191c474c26ab5548db27ef5d34b05",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -81,11 +81,11 @@
|
||||
"rust-analyzer-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1732633904,
|
||||
"narHash": "sha256-7VKcoLug9nbAN2txqVksWHHJplqK9Ou8dXjIZAIYSGc=",
|
||||
"lastModified": 1740329432,
|
||||
"narHash": "sha256-eKQ7aBkNvF5AhUpyJ1cW450jxomZ4gTIaYir5qsNl7Y=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "8d5e91c94f80c257ce6dbdfba7bd63a5e8a03fa6",
|
||||
"rev": "6d68c475c7aaf7534251182662456a4bf4216dfe",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
66
flake.nix
66
flake.nix
@@ -1,7 +1,5 @@
|
||||
{
|
||||
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";
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
crane.url = "github:ipetkov/crane";
|
||||
@@ -20,34 +18,40 @@
|
||||
}:
|
||||
flake-utils.lib.eachDefaultSystem (system: let
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
# Using stable toolchain as base
|
||||
toolchain = with fenix.packages.${system};
|
||||
combine [
|
||||
minimal.rustc
|
||||
minimal.cargo
|
||||
targets.x86_64-pc-windows-gnu.latest.rust-std
|
||||
];
|
||||
|
||||
toolchain =
|
||||
fenix.packages.${system}.fromToolchainFile
|
||||
{
|
||||
file = ./rust-toolchain.toml;
|
||||
# sha256 = nixpkgs.lib.fakeSha256;
|
||||
sha256 = "sha256-AJ6LX/Q/Er9kS15bn9iflkUwcgYqRQxiOIL2ToVAXaU=";
|
||||
};
|
||||
|
||||
craneLib = (crane.mkLib pkgs).overrideToolchain toolchain;
|
||||
|
||||
# Common build inputs for both native and cross compilation
|
||||
commonArgs = {
|
||||
src = craneLib.cleanCargoSource ./.;
|
||||
cargoArtifacts = craneLib.buildDepsOnly {
|
||||
src = craneLib.cleanCargoSource ./.;
|
||||
};
|
||||
strictDeps = true;
|
||||
doCheck = false; # skip tests during nix build
|
||||
};
|
||||
|
||||
cargoArtifacts = craneLib.buildDepsOnly commonArgs;
|
||||
|
||||
# Native build
|
||||
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
|
||||
# @see https://crane.dev/examples/cross-windows.html
|
||||
crossBuild = craneLib.buildPackage {
|
||||
src = craneLib.cleanCargoSource ./.;
|
||||
|
||||
strictDeps = true;
|
||||
doCheck = false;
|
||||
windowsBuild = craneLib.buildPackage {
|
||||
inherit (commonArgs) src strictDeps doCheck;
|
||||
|
||||
CARGO_BUILD_TARGET = "x86_64-pc-windows-gnu";
|
||||
|
||||
@@ -68,24 +72,32 @@
|
||||
packages = {
|
||||
inherit timr;
|
||||
default = timr;
|
||||
windows = crossBuild;
|
||||
linuxStatic = staticLinuxBuild;
|
||||
windows = windowsBuild;
|
||||
};
|
||||
|
||||
# Development shell with all necessary tools
|
||||
devShell = with nixpkgs.legacyPackages.${system};
|
||||
mkShell {
|
||||
buildInputs = with fenix.packages.${system}.stable; [
|
||||
rust-analyzer
|
||||
clippy
|
||||
rustfmt
|
||||
devShells.default = with nixpkgs.legacyPackages.${system};
|
||||
craneLib.devShell {
|
||||
packages =
|
||||
[
|
||||
toolchain
|
||||
pkgs.just
|
||||
pkgs.nixd
|
||||
pkgs.alejandra
|
||||
]
|
||||
# some extra pkgs needed to play sound on Linux
|
||||
++ lib.optionals stdenv.isLinux [
|
||||
pkgs.pkg-config
|
||||
pkgs.alsa-lib.dev
|
||||
pkgs.pipewire
|
||||
];
|
||||
|
||||
inherit (commonArgs) src;
|
||||
RUST_SRC_PATH = "${toolchain}/lib/rustlib/src/rust/library";
|
||||
|
||||
ALSA_PLUGIN_DIR =
|
||||
if stdenv.isLinux
|
||||
then "${pkgs.pipewire}/lib/alsa-lib/"
|
||||
else "";
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
34
justfile
34
justfile
@@ -2,79 +2,105 @@
|
||||
|
||||
set unstable := true
|
||||
|
||||
# list commands
|
||||
default:
|
||||
@just --list
|
||||
|
||||
alias b := build
|
||||
alias f := format
|
||||
alias l := lint
|
||||
alias t := test
|
||||
alias r := run
|
||||
|
||||
# build app
|
||||
build:
|
||||
cargo build
|
||||
|
||||
alias t := test
|
||||
|
||||
# run tests
|
||||
test:
|
||||
cargo test
|
||||
|
||||
alias f := format
|
||||
|
||||
# format files
|
||||
format:
|
||||
just --fmt
|
||||
cargo fmt
|
||||
|
||||
alias l := lint
|
||||
|
||||
# lint
|
||||
lint:
|
||||
cargo clippy --no-deps
|
||||
|
||||
alias r := run
|
||||
|
||||
# run app
|
||||
run:
|
||||
cargo run
|
||||
|
||||
alias rs := run-sound
|
||||
|
||||
# run app while sound feature is enabled. It expects a path to a sound file.
|
||||
run-sound path:
|
||||
cargo run --features sound -- --sound={{ path }}
|
||||
|
||||
# demos
|
||||
|
||||
alias dp := demo-pomodoro
|
||||
|
||||
# build demo: pomodoro
|
||||
demo-pomodoro:
|
||||
vhs demo/pomodoro.tape
|
||||
|
||||
alias dt := demo-timer
|
||||
|
||||
# build demo: timer
|
||||
demo-timer:
|
||||
vhs demo/timer.tape
|
||||
|
||||
alias dc := demo-countdown
|
||||
|
||||
# build demo: countdown
|
||||
demo-countdown:
|
||||
vhs demo/countdown.tape
|
||||
|
||||
alias dcm := demo-countdown-met
|
||||
|
||||
# build demo: countdown + met
|
||||
demo-countdown-met:
|
||||
vhs demo/countdown-met.tape
|
||||
|
||||
alias ds := demo-style
|
||||
|
||||
# build demo: styles
|
||||
demo-style:
|
||||
vhs demo/style.tape
|
||||
|
||||
alias dd := demo-decis
|
||||
|
||||
# build demo: deciseconds
|
||||
demo-decis:
|
||||
vhs demo/decis.tape
|
||||
|
||||
alias dm := demo-menu
|
||||
|
||||
# build demo: menu
|
||||
demo-menu:
|
||||
vhs demo/menu.tape
|
||||
|
||||
alias dlt := demo-local-time
|
||||
|
||||
# build demo: local time
|
||||
demo-local-time:
|
||||
vhs demo/local-time.tape
|
||||
|
||||
alias drc := demo-rocket-countdown
|
||||
|
||||
# build demo: rocket countdown
|
||||
demo-rocket-countdown:
|
||||
vhs demo/met.tape
|
||||
|
||||
alias db := demo-blink
|
||||
|
||||
# build demo: blink animation
|
||||
demo-blink:
|
||||
vhs demo/blink.tape
|
||||
|
||||
6
rust-toolchain.toml
Normal file
6
rust-toolchain.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
[toolchain]
|
||||
# Reminder: Always keep `rust-version` in `Cargo.toml` in sync with `channel`.
|
||||
channel = "1.85.0"
|
||||
components = ["clippy", "rustfmt", "rust-src", "rust-analyzer"]
|
||||
targets = ["x86_64-pc-windows-gnu", "x86_64-unknown-linux-musl"]
|
||||
profile = "minimal"
|
||||
258
src/app.rs
258
src/app.rs
@@ -1,19 +1,23 @@
|
||||
use crate::{
|
||||
args::Args,
|
||||
common::{AppTime, AppTimeFormat, Content, Style},
|
||||
common::{AppEditMode, AppTime, AppTimeFormat, ClockTypeId, Content, Style, Toggle},
|
||||
constants::TICK_VALUE_MS,
|
||||
events::{Event, EventHandler, Events},
|
||||
events::{self, TuiEventHandler},
|
||||
storage::AppStorage,
|
||||
terminal::Terminal,
|
||||
widgets::{
|
||||
clock::{self, ClockState, ClockStateArgs},
|
||||
countdown::{Countdown, CountdownState},
|
||||
countdown::{Countdown, CountdownState, CountdownStateArgs},
|
||||
footer::{Footer, FooterState},
|
||||
header::Header,
|
||||
pomodoro::{Mode as PomodoroMode, PomodoroState, PomodoroStateArgs, PomodoroWidget},
|
||||
timer::{Timer, TimerState},
|
||||
},
|
||||
};
|
||||
|
||||
#[cfg(feature = "sound")]
|
||||
use crate::sound::Sound;
|
||||
|
||||
use color_eyre::Result;
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
@@ -21,9 +25,10 @@ use ratatui::{
|
||||
layout::{Constraint, Layout, Rect},
|
||||
widgets::{StatefulWidget, Widget},
|
||||
};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use time::OffsetDateTime;
|
||||
use tracing::debug;
|
||||
use tracing::{debug, error};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
@@ -31,10 +36,13 @@ enum Mode {
|
||||
Quit,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct App {
|
||||
content: Content,
|
||||
mode: Mode,
|
||||
notification: Toggle,
|
||||
blink: Toggle,
|
||||
#[allow(dead_code)] // w/ `--features sound` available only
|
||||
sound_path: Option<PathBuf>,
|
||||
app_time: AppTime,
|
||||
countdown: CountdownState,
|
||||
timer: TimerState,
|
||||
@@ -47,6 +55,8 @@ pub struct App {
|
||||
pub struct AppArgs {
|
||||
pub style: Style,
|
||||
pub with_decis: bool,
|
||||
pub notification: Toggle,
|
||||
pub blink: Toggle,
|
||||
pub show_menu: bool,
|
||||
pub app_time_format: AppTimeFormat,
|
||||
pub content: Content,
|
||||
@@ -59,15 +69,27 @@ pub struct AppArgs {
|
||||
pub current_value_countdown: Duration,
|
||||
pub elapsed_value_countdown: Duration,
|
||||
pub current_value_timer: Duration,
|
||||
pub app_tx: events::AppEventTx,
|
||||
pub sound_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Getting `AppArgs` by merging `Args` and `AppStorage`.
|
||||
/// `Args` wins btw.
|
||||
impl From<(Args, AppStorage)> for AppArgs {
|
||||
fn from((args, stg): (Args, AppStorage)) -> Self {
|
||||
AppArgs {
|
||||
pub struct FromAppArgs {
|
||||
pub args: Args,
|
||||
pub stg: AppStorage,
|
||||
pub app_tx: events::AppEventTx,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
show_menu: args.menu || stg.show_menu,
|
||||
notification: args.notification.unwrap_or(stg.notification),
|
||||
blink: args.blink.unwrap_or(stg.blink),
|
||||
app_time_format: stg.app_time_format,
|
||||
content: args.mode.unwrap_or(stg.content),
|
||||
style: args.style.unwrap_or(stg.style),
|
||||
@@ -83,7 +105,12 @@ impl From<(Args, AppStorage)> for AppArgs {
|
||||
current_value_countdown: args.countdown.unwrap_or(stg.current_value_countdown),
|
||||
elapsed_value_countdown: stg.elapsed_value_countdown,
|
||||
current_value_timer: stg.current_value_timer,
|
||||
}
|
||||
app_tx,
|
||||
#[cfg(feature = "sound")]
|
||||
sound_path: args.sound,
|
||||
#[cfg(not(feature = "sound"))]
|
||||
sound_path: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,28 +138,40 @@ impl App {
|
||||
content,
|
||||
with_decis,
|
||||
pomodoro_mode,
|
||||
notification,
|
||||
blink,
|
||||
sound_path,
|
||||
app_tx,
|
||||
} = args;
|
||||
let app_time = get_app_time();
|
||||
|
||||
Self {
|
||||
mode: Mode::Running,
|
||||
notification,
|
||||
blink,
|
||||
sound_path,
|
||||
content,
|
||||
app_time: get_app_time(),
|
||||
app_time,
|
||||
style,
|
||||
with_decis,
|
||||
countdown: CountdownState::new(
|
||||
ClockState::<clock::Countdown>::new(ClockStateArgs {
|
||||
countdown: CountdownState::new(CountdownStateArgs {
|
||||
initial_value: initial_value_countdown,
|
||||
current_value: current_value_countdown,
|
||||
tick_value: Duration::from_millis(TICK_VALUE_MS),
|
||||
elapsed_value: elapsed_value_countdown,
|
||||
app_time,
|
||||
with_decis,
|
||||
app_tx: app_tx.clone(),
|
||||
}),
|
||||
elapsed_value_countdown,
|
||||
),
|
||||
timer: TimerState::new(ClockState::<clock::Timer>::new(ClockStateArgs {
|
||||
timer: TimerState::new(
|
||||
ClockState::<clock::Timer>::new(ClockStateArgs {
|
||||
initial_value: Duration::ZERO,
|
||||
current_value: current_value_timer,
|
||||
tick_value: Duration::from_millis(TICK_VALUE_MS),
|
||||
with_decis,
|
||||
})),
|
||||
app_tx: Some(app_tx.clone()),
|
||||
})
|
||||
.with_name("Timer".to_owned()),
|
||||
),
|
||||
pomodoro: PomodoroState::new(PomodoroStateArgs {
|
||||
mode: pomodoro_mode,
|
||||
initial_value_work,
|
||||
@@ -140,32 +179,111 @@ impl App {
|
||||
initial_value_pause,
|
||||
current_value_pause,
|
||||
with_decis,
|
||||
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> {
|
||||
while self.is_running() {
|
||||
if let Some(event) = events.next().await {
|
||||
if matches!(event, Event::Tick) {
|
||||
self.app_time = get_app_time();
|
||||
pub async fn run(
|
||||
mut self,
|
||||
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') | KeyCode::Esc => 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
|
||||
if let Some(unhandled) = match self.content {
|
||||
Content::Countdown => self.countdown.update(event.clone()),
|
||||
Content::Timer => self.timer.update(event.clone()),
|
||||
Content::Pomodoro => self.pomodoro.update(event.clone()),
|
||||
if let Some(unhandled) = match app.content {
|
||||
Content::Countdown => app.countdown.update(event.clone()),
|
||||
Content::Timer => app.timer.update(event.clone()),
|
||||
Content::Pomodoro => app.pomodoro.update(event.clone()),
|
||||
} {
|
||||
match unhandled {
|
||||
Event::Render | Event::Resize => {
|
||||
self.draw(&mut terminal)?;
|
||||
events::TuiEvent::Render | events::TuiEvent::Resize => {
|
||||
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!("{:?} {name} done!", type_id),
|
||||
};
|
||||
// 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)
|
||||
@@ -175,11 +293,32 @@ impl App {
|
||||
self.mode != Mode::Quit
|
||||
}
|
||||
|
||||
fn is_edit_mode(&self) -> bool {
|
||||
fn get_edit_mode(&self) -> AppEditMode {
|
||||
match self.content {
|
||||
Content::Countdown => self.countdown.get_clock().is_edit_mode(),
|
||||
Content::Timer => self.timer.get_clock().is_edit_mode(),
|
||||
Content::Pomodoro => self.pomodoro.get_clock().is_edit_mode(),
|
||||
Content::Countdown => {
|
||||
if self.countdown.is_clock_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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,33 +338,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,
|
||||
// toogle app time format
|
||||
KeyCode::Char(':') => self.footer.toggle_app_time_format(),
|
||||
// toogle menu
|
||||
KeyCode::Char('m') => self.footer.set_show_menu(!self.footer.get_show_menu()),
|
||||
KeyCode::Char(',') => {
|
||||
self.style = self.style.next();
|
||||
}
|
||||
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.footer.set_show_menu(true),
|
||||
KeyCode::Down => self.footer.set_show_menu(false),
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
|
||||
fn draw(&mut self, terminal: &mut Terminal) -> Result<()> {
|
||||
terminal.draw(|frame| {
|
||||
frame.render_stateful_widget(AppWidget, frame.area(), self);
|
||||
@@ -237,6 +349,8 @@ impl App {
|
||||
AppStorage {
|
||||
content: self.content,
|
||||
show_menu: self.footer.get_show_menu(),
|
||||
notification: self.notification,
|
||||
blink: self.blink,
|
||||
app_time_format: *self.footer.app_time_format(),
|
||||
style: self.style,
|
||||
with_decis: self.with_decis,
|
||||
@@ -265,14 +379,22 @@ impl AppWidget {
|
||||
fn render_content(&self, area: Rect, buf: &mut Buffer, state: &mut App) {
|
||||
match state.content {
|
||||
Content::Timer => {
|
||||
Timer { style: state.style }.render(area, buf, &mut state.timer);
|
||||
Timer {
|
||||
style: state.style,
|
||||
blink: state.blink == Toggle::On,
|
||||
}
|
||||
Content::Countdown => {
|
||||
Countdown { style: state.style }.render(area, buf, &mut state.countdown)
|
||||
.render(area, buf, &mut state.timer);
|
||||
}
|
||||
Content::Pomodoro => {
|
||||
PomodoroWidget { style: state.style }.render(area, buf, &mut state.pomodoro)
|
||||
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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -298,7 +420,7 @@ impl StatefulWidget for AppWidget {
|
||||
Footer {
|
||||
running_clock: state.clock_is_running(),
|
||||
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, &mut state.footer);
|
||||
|
||||
59
src/args.rs
59
src/args.rs
@@ -1,10 +1,15 @@
|
||||
use crate::{
|
||||
common::{Content, Style},
|
||||
common::{Content, Style, Toggle},
|
||||
duration,
|
||||
};
|
||||
#[cfg(feature = "sound")]
|
||||
use crate::{sound, sound::SoundError};
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
pub const LOG_DIRECTORY_DEFAULT_MISSING_VALUE: &str = " "; // empty string
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version)]
|
||||
pub struct Args {
|
||||
@@ -23,7 +28,7 @@ pub struct Args {
|
||||
)]
|
||||
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,
|
||||
|
||||
#[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.")]
|
||||
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,
|
||||
|
||||
#[arg(long, short = 'r', help = "Reset stored values to default.")]
|
||||
#[arg(long, short = 'r', help = "Reset stored values to default values.")]
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use clap::ValueEnum;
|
||||
use ratatui::symbols::shade;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::format_description;
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description;
|
||||
|
||||
#[derive(
|
||||
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Default, Serialize, Deserialize,
|
||||
@@ -17,6 +17,12 @@ pub enum Content {
|
||||
Pomodoro,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ClockTypeId {
|
||||
Countdown,
|
||||
Timer,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, ValueEnum, Default, Serialize, Deserialize)]
|
||||
pub enum Style {
|
||||
#[default]
|
||||
@@ -128,6 +134,22 @@ impl AppTime {
|
||||
}
|
||||
}
|
||||
|
||||
#[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 {
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use crate::constants::APP_NAME;
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use color_eyre::eyre::{Result, eyre};
|
||||
use directories::ProjectDirs;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct Config {
|
||||
pub log_dir: PathBuf,
|
||||
pub data_dir: PathBuf,
|
||||
@@ -10,8 +11,11 @@ pub struct Config {
|
||||
|
||||
impl Config {
|
||||
pub fn init() -> Result<Self> {
|
||||
// default logs dir
|
||||
let log_dir = get_default_state_dir()?.join("logs");
|
||||
fs::create_dir_all(&log_dir)?;
|
||||
|
||||
// default data dir
|
||||
let data_dir = get_default_state_dir()?.join("data");
|
||||
fs::create_dir_all(&data_dir)?;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use color_eyre::{
|
||||
eyre::{ensure, eyre},
|
||||
Report,
|
||||
eyre::{ensure, eyre},
|
||||
};
|
||||
use std::fmt;
|
||||
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
|
||||
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)]
|
||||
pub struct DurationEx {
|
||||
inner: Duration,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use crossterm::event::{Event as CrosstermEvent, EventStream, KeyEvent, KeyEventKind};
|
||||
use futures::{Stream, StreamExt};
|
||||
use std::{pin::Pin, time::Duration};
|
||||
use tokio::sync::mpsc;
|
||||
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};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
||||
@@ -12,8 +14,9 @@ enum StreamKey {
|
||||
Render,
|
||||
Crossterm,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Event {
|
||||
pub enum TuiEvent {
|
||||
Error,
|
||||
Tick,
|
||||
Render,
|
||||
@@ -21,8 +24,17 @@ pub enum Event {
|
||||
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 {
|
||||
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 {
|
||||
@@ -33,31 +45,46 @@ impl Default for Events {
|
||||
(StreamKey::Render, render_stream()),
|
||||
(StreamKey::Crossterm, crossterm_stream()),
|
||||
]),
|
||||
app_channel: mpsc::unbounded_channel(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Event {
|
||||
Terminal(TuiEvent),
|
||||
App(AppEvent),
|
||||
}
|
||||
|
||||
impl Events {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
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)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_app_event_tx(&self) -> AppEventTx {
|
||||
self.app_channel.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn tick_stream() -> Pin<Box<dyn Stream<Item = Event>>> {
|
||||
fn tick_stream() -> Pin<Box<dyn Stream<Item = TuiEvent>>> {
|
||||
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));
|
||||
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(
|
||||
EventStream::new()
|
||||
.fuse()
|
||||
@@ -65,16 +92,16 @@ fn crossterm_stream() -> Pin<Box<dyn Stream<Item = Event>>> {
|
||||
.filter_map(|event| async move {
|
||||
match event {
|
||||
Ok(CrosstermEvent::Key(key)) if key.kind == KeyEventKind::Press => {
|
||||
Some(Event::Key(key))
|
||||
Some(TuiEvent::Key(key))
|
||||
}
|
||||
Ok(CrosstermEvent::Resize(_, _)) => Some(Event::Resize),
|
||||
Err(_) => Some(Event::Error),
|
||||
Ok(CrosstermEvent::Resize(_, _)) => Some(TuiEvent::Resize),
|
||||
Err(_) => Some(TuiEvent::Error),
|
||||
_ => None,
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub trait EventHandler {
|
||||
fn update(&mut self, _: Event) -> Option<Event>;
|
||||
pub trait TuiEventHandler {
|
||||
fn update(&mut self, _: TuiEvent) -> Option<TuiEvent>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::{Result, eyre};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use tracing::level_filters::LevelFilter;
|
||||
@@ -17,7 +17,13 @@ impl Logger {
|
||||
|
||||
pub fn init(&self) -> Result<()> {
|
||||
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()
|
||||
.with_file(true)
|
||||
.with_line_number(true)
|
||||
|
||||
48
src/main.rs
48
src/main.rs
@@ -3,7 +3,6 @@ mod common;
|
||||
mod config;
|
||||
mod constants;
|
||||
mod events;
|
||||
#[cfg(debug_assertions)]
|
||||
mod logging;
|
||||
|
||||
mod args;
|
||||
@@ -13,24 +12,50 @@ mod terminal;
|
||||
mod utils;
|
||||
mod widgets;
|
||||
|
||||
use app::{App, AppArgs};
|
||||
use args::Args;
|
||||
#[cfg(feature = "sound")]
|
||||
mod sound;
|
||||
|
||||
use app::{App, FromAppArgs};
|
||||
use args::{Args, LOG_DIRECTORY_DEFAULT_MISSING_VALUE};
|
||||
use clap::Parser;
|
||||
use color_eyre::Result;
|
||||
use config::Config;
|
||||
use std::path::PathBuf;
|
||||
use storage::{AppStorage, Storage};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
// init `Config`
|
||||
let cfg = Config::init()?;
|
||||
#[cfg(debug_assertions)]
|
||||
logging::Logger::new(cfg.log_dir).init()?;
|
||||
|
||||
color_eyre::install()?;
|
||||
|
||||
// get args given by CLI
|
||||
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();
|
||||
|
||||
// check persistant storage
|
||||
@@ -42,9 +67,14 @@ async fn main() -> Result<()> {
|
||||
storage.load().unwrap_or_default()
|
||||
};
|
||||
|
||||
// merge `Args` and `AppStorage`.
|
||||
let app_args = AppArgs::from((args, stg));
|
||||
let app_storage = App::new(app_args).run(terminal, events).await?.to_storage();
|
||||
let app_storage = App::from(FromAppArgs {
|
||||
args,
|
||||
stg,
|
||||
app_tx: events.get_app_event_tx(),
|
||||
})
|
||||
.run(&mut terminal, events)
|
||||
.await?
|
||||
.to_storage();
|
||||
// store app state persistantly
|
||||
storage.save(app_storage)?;
|
||||
|
||||
|
||||
73
src/sound.rs
Normal file
73
src/sound.rs
Normal 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(())
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{
|
||||
common::{AppTimeFormat, Content, Style},
|
||||
common::{AppTimeFormat, Content, Style, Toggle},
|
||||
widgets::pomodoro::Mode as PomodoroMode,
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
@@ -12,6 +12,8 @@ use std::time::Duration;
|
||||
pub struct AppStorage {
|
||||
pub content: Content,
|
||||
pub show_menu: bool,
|
||||
pub notification: Toggle,
|
||||
pub blink: Toggle,
|
||||
pub app_time_format: AppTimeFormat,
|
||||
pub style: Style,
|
||||
pub with_decis: bool,
|
||||
@@ -38,6 +40,8 @@ impl Default for AppStorage {
|
||||
AppStorage {
|
||||
content: Content::default(),
|
||||
show_menu: true,
|
||||
notification: Toggle::Off,
|
||||
blink: Toggle::Off,
|
||||
app_time_format: AppTimeFormat::default(),
|
||||
style: Style::default(),
|
||||
with_decis: false,
|
||||
|
||||
@@ -5,13 +5,14 @@ use crossterm::{
|
||||
cursor, execute,
|
||||
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 fn setup() -> Result<Terminal> {
|
||||
let mut stdout = std::io::stdout();
|
||||
crossterm::terminal::enable_raw_mode()?;
|
||||
set_panic_hook();
|
||||
execute!(stdout, EnterAlternateScreen, cursor::Hide)?;
|
||||
let mut terminal = RatatuiTerminal::new(CrosstermBackend::new(stdout))?;
|
||||
terminal.clear()?;
|
||||
@@ -24,3 +25,13 @@ pub fn teardown() -> Result<()> {
|
||||
crossterm::terminal::disable_raw_mode()?;
|
||||
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);
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod clock_elements_test;
|
||||
#[cfg(test)]
|
||||
pub mod clock_test;
|
||||
pub mod countdown;
|
||||
pub mod edit_time;
|
||||
pub mod footer;
|
||||
pub mod header;
|
||||
pub mod pomodoro;
|
||||
|
||||
@@ -10,21 +10,15 @@ use ratatui::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
common::Style,
|
||||
duration::{
|
||||
DurationEx, MINS_PER_HOUR, ONE_DECI_SECOND, ONE_HOUR, ONE_MINUTE, ONE_SECOND,
|
||||
SECS_PER_MINUTE,
|
||||
},
|
||||
common::{ClockTypeId, Style},
|
||||
duration::{DurationEx, MAX_DURATION, ONE_DECI_SECOND, ONE_HOUR, ONE_MINUTE, ONE_SECOND},
|
||||
events::{AppEvent, AppEventTx},
|
||||
utils::center_horizontal,
|
||||
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)]
|
||||
pub enum Time {
|
||||
Decis,
|
||||
@@ -72,14 +66,24 @@ pub enum Format {
|
||||
HhMmSs,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
const RANGE_OF_DONE_COUNT: u64 = 4;
|
||||
const MAX_DONE_COUNT: u64 = RANGE_OF_DONE_COUNT * 5;
|
||||
|
||||
pub struct ClockState<T> {
|
||||
type_id: ClockTypeId,
|
||||
name: Option<String>,
|
||||
initial_value: DurationEx,
|
||||
current_value: DurationEx,
|
||||
tick_value: DurationEx,
|
||||
mode: Mode,
|
||||
format: Format,
|
||||
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>,
|
||||
}
|
||||
|
||||
@@ -88,9 +92,23 @@ pub struct ClockStateArgs {
|
||||
pub current_value: Duration,
|
||||
pub tick_value: Duration,
|
||||
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
|
||||
@@ -128,6 +146,11 @@ impl<T> ClockState<T> {
|
||||
&self.current_value
|
||||
}
|
||||
|
||||
pub fn set_current_value(&mut self, duration: DurationEx) {
|
||||
self.current_value = duration;
|
||||
self.update_format();
|
||||
}
|
||||
|
||||
pub fn toggle_edit(&mut self) {
|
||||
self.mode = match self.mode.clone() {
|
||||
Mode::Editable(_, prev) => {
|
||||
@@ -312,6 +335,18 @@ impl<T> ClockState<T> {
|
||||
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) {
|
||||
self.format = self.get_format();
|
||||
}
|
||||
@@ -331,6 +366,23 @@ impl<T> ClockState<T> {
|
||||
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)]
|
||||
@@ -343,8 +395,11 @@ impl ClockState<Countdown> {
|
||||
current_value,
|
||||
tick_value,
|
||||
with_decis,
|
||||
app_tx,
|
||||
} = args;
|
||||
let mut instance = Self {
|
||||
type_id: ClockTypeId::Countdown,
|
||||
name: None,
|
||||
initial_value: initial_value.into(),
|
||||
current_value: current_value.into(),
|
||||
tick_value: tick_value.into(),
|
||||
@@ -357,6 +412,8 @@ impl ClockState<Countdown> {
|
||||
},
|
||||
format: Format::S,
|
||||
with_decis,
|
||||
app_tx,
|
||||
done_count: None,
|
||||
phantom: PhantomData,
|
||||
};
|
||||
// update format once
|
||||
@@ -367,14 +424,14 @@ impl ClockState<Countdown> {
|
||||
pub fn tick(&mut self) {
|
||||
if self.mode == Mode::Tick {
|
||||
self.current_value = self.current_value.saturating_sub(self.tick_value);
|
||||
self.set_done();
|
||||
self.check_done();
|
||||
self.update_format();
|
||||
}
|
||||
}
|
||||
|
||||
fn set_done(&mut self) {
|
||||
fn check_done(&mut self) {
|
||||
if self.current_value.eq(&Duration::ZERO.into()) {
|
||||
self.mode = Mode::Done;
|
||||
self.done();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -411,8 +468,11 @@ impl ClockState<Timer> {
|
||||
current_value,
|
||||
tick_value,
|
||||
with_decis,
|
||||
app_tx,
|
||||
} = args;
|
||||
let mut instance = Self {
|
||||
type_id: ClockTypeId::Timer,
|
||||
name: None,
|
||||
initial_value: initial_value.into(),
|
||||
current_value: current_value.into(),
|
||||
tick_value: tick_value.into(),
|
||||
@@ -424,8 +484,10 @@ impl ClockState<Timer> {
|
||||
Mode::Pause
|
||||
},
|
||||
format: Format::S,
|
||||
phantom: PhantomData,
|
||||
with_decis,
|
||||
app_tx,
|
||||
done_count: None,
|
||||
phantom: PhantomData,
|
||||
};
|
||||
// update format once
|
||||
instance.update_format();
|
||||
@@ -435,14 +497,14 @@ impl ClockState<Timer> {
|
||||
pub fn tick(&mut self) {
|
||||
if self.mode == Mode::Tick {
|
||||
self.current_value = self.current_value.saturating_add(self.tick_value);
|
||||
self.set_done();
|
||||
self.check_done();
|
||||
self.update_format();
|
||||
}
|
||||
}
|
||||
|
||||
fn set_done(&mut self) {
|
||||
fn check_done(&mut self) {
|
||||
if self.current_value.ge(&MAX_DURATION.into()) {
|
||||
self.mode = Mode::Done;
|
||||
self.done();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,13 +525,12 @@ impl ClockState<Timer> {
|
||||
}
|
||||
}
|
||||
|
||||
const SPACE_WIDTH: u16 = 1;
|
||||
|
||||
pub struct ClockWidget<T>
|
||||
where
|
||||
T: std::fmt::Debug,
|
||||
{
|
||||
style: Style,
|
||||
blink: bool,
|
||||
phantom: PhantomData<T>,
|
||||
}
|
||||
|
||||
@@ -477,9 +538,10 @@ impl<T> ClockWidget<T>
|
||||
where
|
||||
T: std::fmt::Debug,
|
||||
{
|
||||
pub fn new(style: Style) -> Self {
|
||||
pub fn new(style: Style, blink: bool) -> Self {
|
||||
Self {
|
||||
style,
|
||||
blink,
|
||||
phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -499,15 +561,15 @@ where
|
||||
Format::HhMmSs => add_decis(
|
||||
vec![
|
||||
DIGIT_WIDTH, // h
|
||||
SPACE_WIDTH, // (space)
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // h
|
||||
COLON_WIDTH, // :
|
||||
DIGIT_WIDTH, // m
|
||||
SPACE_WIDTH, // (space)
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // m
|
||||
COLON_WIDTH, // :
|
||||
DIGIT_WIDTH, // s
|
||||
SPACE_WIDTH, // (space)
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // s
|
||||
],
|
||||
with_decis,
|
||||
@@ -517,11 +579,11 @@ where
|
||||
DIGIT_WIDTH, // h
|
||||
COLON_WIDTH, // :
|
||||
DIGIT_WIDTH, // m
|
||||
SPACE_WIDTH, // (space)
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // m
|
||||
COLON_WIDTH, // :
|
||||
DIGIT_WIDTH, // s
|
||||
SPACE_WIDTH, // (space)
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // s
|
||||
],
|
||||
with_decis,
|
||||
@@ -529,11 +591,11 @@ where
|
||||
Format::MmSs => add_decis(
|
||||
vec![
|
||||
DIGIT_WIDTH, // m
|
||||
SPACE_WIDTH, // (space)
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // m
|
||||
COLON_WIDTH, // :
|
||||
DIGIT_WIDTH, // s
|
||||
SPACE_WIDTH, // (space)
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // s
|
||||
],
|
||||
with_decis,
|
||||
@@ -543,7 +605,7 @@ where
|
||||
DIGIT_WIDTH, // m
|
||||
COLON_WIDTH, // :
|
||||
DIGIT_WIDTH, // s
|
||||
SPACE_WIDTH, // (space)
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // s
|
||||
],
|
||||
with_decis,
|
||||
@@ -551,7 +613,7 @@ where
|
||||
Format::Ss => add_decis(
|
||||
vec![
|
||||
DIGIT_WIDTH, // s
|
||||
SPACE_WIDTH, // (space)
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // s
|
||||
],
|
||||
with_decis,
|
||||
@@ -572,6 +634,17 @@ where
|
||||
pub fn get_height(&self) -> u16 {
|
||||
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>
|
||||
@@ -583,7 +656,13 @@ where
|
||||
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
||||
let with_decis = state.with_decis;
|
||||
let format = state.format;
|
||||
let symbol = self.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 area = center_horizontal(
|
||||
area,
|
||||
|
||||
@@ -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 COLON_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]
|
||||
const DIGIT_0: [u8; DIGIT_SIZE * DIGIT_SIZE] = [
|
||||
|
||||
@@ -1,34 +1,33 @@
|
||||
use crate::{
|
||||
common::ClockTypeId,
|
||||
duration::{ONE_DECI_SECOND, ONE_HOUR, ONE_MINUTE, ONE_SECOND},
|
||||
widgets::clock::*,
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn test_toggle_edit() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
fn default_args() -> ClockStateArgs {
|
||||
ClockStateArgs {
|
||||
initial_value: ONE_HOUR,
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
});
|
||||
// off by default
|
||||
assert!(!c.is_edit_mode());
|
||||
// toggle on
|
||||
c.toggle_edit();
|
||||
assert!(c.is_edit_mode());
|
||||
// toggle off
|
||||
c.toggle_edit();
|
||||
assert!(!c.is_edit_mode());
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_type_id() {
|
||||
let c = ClockState::<Timer>::new(default_args());
|
||||
assert!(matches!(c.get_type_id(), ClockTypeId::Timer));
|
||||
let c = ClockState::<Countdown>::new(default_args());
|
||||
assert!(matches!(c.get_type_id(), ClockTypeId::Countdown));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_edit_mode_hhmmss() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_HOUR,
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
..default_args()
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -43,6 +42,7 @@ fn test_default_edit_mode_mmss() {
|
||||
current_value: ONE_MINUTE,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
// toggle on
|
||||
c.toggle_edit();
|
||||
@@ -56,6 +56,7 @@ fn test_default_edit_mode_ss() {
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
// toggle on
|
||||
c.toggle_edit();
|
||||
@@ -69,6 +70,7 @@ fn test_edit_next_hhmmssd() {
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -90,6 +92,7 @@ fn test_edit_next_hhmmss() {
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -109,6 +112,7 @@ fn test_edit_next_mmssd() {
|
||||
current_value: ONE_MINUTE,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -128,6 +132,7 @@ fn test_edit_next_mmss() {
|
||||
current_value: ONE_MINUTE,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -145,6 +150,7 @@ fn test_edit_next_ssd() {
|
||||
current_value: ONE_SECOND * 3,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -160,6 +166,7 @@ fn test_edit_next_ss() {
|
||||
current_value: ONE_SECOND * 3,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -176,6 +183,7 @@ fn test_edit_prev_hhmmssd() {
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -196,6 +204,7 @@ fn test_edit_prev_hhmmss() {
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -214,6 +223,7 @@ fn test_edit_prev_mmssd() {
|
||||
current_value: ONE_MINUTE,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -234,6 +244,7 @@ fn test_edit_prev_mmss() {
|
||||
current_value: ONE_MINUTE,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -252,6 +263,7 @@ fn test_edit_prev_ssd() {
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -270,6 +282,7 @@ fn test_edit_prev_ss() {
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -285,7 +298,8 @@ fn test_edit_up_ss() {
|
||||
initial_value: Duration::ZERO,
|
||||
current_value: Duration::ZERO,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -301,7 +315,8 @@ fn test_edit_up_mmss() {
|
||||
initial_value: Duration::ZERO,
|
||||
current_value: Duration::from_secs(60),
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -320,7 +335,8 @@ fn test_edit_up_hhmmss() {
|
||||
initial_value: Duration::ZERO,
|
||||
current_value: Duration::from_secs(3600),
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -341,7 +357,8 @@ fn test_edit_down_ss() {
|
||||
initial_value: Duration::ZERO,
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -361,7 +378,8 @@ fn test_edit_down_mmss() {
|
||||
initial_value: Duration::ZERO,
|
||||
current_value: Duration::from_secs(120),
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@@ -383,7 +401,8 @@ fn test_edit_down_hhmmss() {
|
||||
initial_value: Duration::ZERO,
|
||||
current_value: Duration::from_secs(3600),
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
|
||||
@@ -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::{
|
||||
buffer::Buffer,
|
||||
crossterm::event::KeyCode,
|
||||
@@ -5,36 +17,57 @@ use ratatui::{
|
||||
text::Line,
|
||||
widgets::{StatefulWidget, Widget},
|
||||
};
|
||||
use std::ops::Sub;
|
||||
use std::{cmp::max, time::Duration};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use crate::{
|
||||
common::Style,
|
||||
constants::TICK_VALUE_MS,
|
||||
duration::DurationEx,
|
||||
events::{Event, EventHandler},
|
||||
utils::center,
|
||||
widgets::clock::{self, ClockState, ClockStateArgs, ClockWidget, Mode as ClockMode},
|
||||
};
|
||||
pub struct CountdownStateArgs {
|
||||
pub initial_value: Duration,
|
||||
pub current_value: Duration,
|
||||
pub elapsed_value: Duration,
|
||||
pub app_time: AppTime,
|
||||
pub with_decis: bool,
|
||||
pub app_tx: AppEventTx,
|
||||
}
|
||||
|
||||
/// State for Countdown Widget
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CountdownState {
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
impl CountdownState {
|
||||
pub fn new(clock: ClockState<clock::Countdown>, elapsed_value: Duration) -> Self {
|
||||
pub fn new(args: CountdownStateArgs) -> Self {
|
||||
let CountdownStateArgs {
|
||||
initial_value,
|
||||
current_value,
|
||||
elapsed_value,
|
||||
with_decis,
|
||||
app_time,
|
||||
app_tx,
|
||||
} = args;
|
||||
|
||||
Self {
|
||||
clock,
|
||||
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
|
||||
@@ -43,6 +76,8 @@ impl CountdownState {
|
||||
} else {
|
||||
ClockMode::Initial
|
||||
}),
|
||||
app_time,
|
||||
edit_time: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,27 +97,84 @@ impl CountdownState {
|
||||
pub fn get_elapsed_value(&self) -> &DurationEx {
|
||||
self.elapsed_clock.get_current_value()
|
||||
}
|
||||
|
||||
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 EventHandler for CountdownState {
|
||||
fn update(&mut self, event: Event) -> Option<Event> {
|
||||
let edit_mode = self.clock.is_edit_mode();
|
||||
impl TuiEventHandler for CountdownState {
|
||||
fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
|
||||
let is_edit_clock = self.clock.is_edit_mode();
|
||||
let is_edit_time = self.edit_time.is_some();
|
||||
match event {
|
||||
Event::Tick => {
|
||||
TuiEvent::Tick => {
|
||||
if !self.clock.is_done() {
|
||||
self.clock.tick();
|
||||
} else {
|
||||
self.clock.update_done_count();
|
||||
self.elapsed_clock.tick();
|
||||
if self.elapsed_clock.is_initial() {
|
||||
self.elapsed_clock.run();
|
||||
}
|
||||
}
|
||||
let min_time = self.min_time_to_edit();
|
||||
let max_time = self.max_time_to_edit();
|
||||
if let Some(edit_time) = &mut self.edit_time {
|
||||
edit_time.set_min_time(min_time);
|
||||
edit_time.set_max_time(max_time);
|
||||
}
|
||||
Event::Key(key) => match key.code {
|
||||
}
|
||||
TuiEvent::Key(key) => match key.code {
|
||||
KeyCode::Char('r') => {
|
||||
// reset both clocks
|
||||
// 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
|
||||
@@ -91,30 +183,92 @@ impl EventHandler for CountdownState {
|
||||
} 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);
|
||||
}
|
||||
KeyCode::Char('e') => {
|
||||
}
|
||||
// STRG + e => toggle edit time
|
||||
KeyCode::Char('e') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
// stop editing clock
|
||||
if self.clock.is_edit_mode() {
|
||||
// toggle edit mode
|
||||
self.clock.toggle_edit();
|
||||
// stop + reset timer entering `edit` mode
|
||||
}
|
||||
|
||||
if let Some(edit_time) = &mut self.edit_time.clone() {
|
||||
self.edit_time_done(edit_time)
|
||||
} else {
|
||||
// update `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(),
|
||||
}));
|
||||
}
|
||||
|
||||
// stop `clock`
|
||||
if self.clock.is_running() {
|
||||
self.clock.toggle_pause();
|
||||
}
|
||||
|
||||
// stop `elapsed_clock`
|
||||
if self.elapsed_clock.is_running() {
|
||||
self.elapsed_clock.toggle_pause();
|
||||
}
|
||||
}
|
||||
KeyCode::Left if edit_mode => {
|
||||
// STRG + e => toggle edit clock
|
||||
KeyCode::Char('e') => {
|
||||
// toggle edit mode
|
||||
self.clock.toggle_edit();
|
||||
|
||||
// stop `elapsed_clock`
|
||||
if self.elapsed_clock.is_running() {
|
||||
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);
|
||||
}
|
||||
}
|
||||
KeyCode::Left if is_edit_clock => {
|
||||
self.clock.edit_next();
|
||||
}
|
||||
KeyCode::Right if edit_mode => {
|
||||
KeyCode::Left if is_edit_time => {
|
||||
// safe unwrap because of previous check in `is_edit_time`
|
||||
self.edit_time.as_mut().unwrap().next();
|
||||
}
|
||||
KeyCode::Right if is_edit_clock => {
|
||||
self.clock.edit_prev();
|
||||
}
|
||||
KeyCode::Up if edit_mode => {
|
||||
KeyCode::Right if is_edit_time => {
|
||||
// safe unwrap because of previous check in `is_edit_time`
|
||||
self.edit_time.as_mut().unwrap().prev();
|
||||
}
|
||||
KeyCode::Up if is_edit_clock => {
|
||||
self.clock.edit_up();
|
||||
// whenever `clock`'s value is changed, reset `elapsed_clock`
|
||||
self.elapsed_clock.reset();
|
||||
}
|
||||
KeyCode::Down if edit_mode => {
|
||||
KeyCode::Up if is_edit_time => {
|
||||
// safe unwrap because of previous check in `is_edit_time`
|
||||
self.edit_time.as_mut().unwrap().up();
|
||||
// whenever `clock`'s value is changed, reset `elapsed_clock`
|
||||
self.elapsed_clock.reset();
|
||||
}
|
||||
KeyCode::Down if is_edit_clock => {
|
||||
self.clock.edit_down();
|
||||
// whenever clock value is changed, reset timer
|
||||
self.elapsed_clock.reset();
|
||||
}
|
||||
KeyCode::Down if is_edit_time => {
|
||||
// safe unwrap because of previous check in `is_edit_time`
|
||||
self.edit_time.as_mut().unwrap().down();
|
||||
// whenever clock value is changed, reset timer
|
||||
self.elapsed_clock.reset();
|
||||
}
|
||||
_ => return Some(event),
|
||||
},
|
||||
_ => return Some(event),
|
||||
@@ -125,13 +279,43 @@ impl EventHandler for CountdownState {
|
||||
|
||||
pub struct Countdown {
|
||||
pub style: Style,
|
||||
pub blink: bool,
|
||||
}
|
||||
|
||||
fn human_days_diff(a: &OffsetDateTime, b: &OffsetDateTime) -> String {
|
||||
let days_diff = (a.date() - b.date()).whole_days();
|
||||
match days_diff {
|
||||
0 => "today".to_owned(),
|
||||
1 => "tomorrow".to_owned(),
|
||||
n => format!("+{}days", n),
|
||||
}
|
||||
}
|
||||
|
||||
impl StatefulWidget for Countdown {
|
||||
type State = CountdownState;
|
||||
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
||||
let clock = ClockWidget::new(self.style);
|
||||
// render `edit_time` OR `clock`
|
||||
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 {
|
||||
@@ -155,19 +339,20 @@ impl StatefulWidget for Countdown {
|
||||
}
|
||||
.to_uppercase(),
|
||||
);
|
||||
|
||||
let widget = ClockWidget::new(self.style, self.blink);
|
||||
let area = center(
|
||||
area,
|
||||
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,
|
||||
)),
|
||||
Constraint::Length(clock.get_height() + 1 /* height of label */),
|
||||
Constraint::Length(widget.get_height() + 1 /* height of label */),
|
||||
);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
231
src/widgets/edit_time.rs
Normal file
231
src/widgets/edit_time.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::common::{AppTime, AppTimeFormat, Content};
|
||||
use crate::common::{AppEditMode, AppTime, AppTimeFormat, Content};
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::{Constraint, Layout, Rect},
|
||||
@@ -45,7 +45,7 @@ impl FooterState {
|
||||
pub struct Footer {
|
||||
pub running_clock: bool,
|
||||
pub selected_content: Content,
|
||||
pub edit_mode: bool,
|
||||
pub app_edit_mode: AppEditMode,
|
||||
pub app_time: AppTime,
|
||||
}
|
||||
|
||||
@@ -139,21 +139,8 @@ impl StatefulWidget for Footer {
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Cell::from(Line::from({
|
||||
if self.edit_mode {
|
||||
vec![
|
||||
Span::from("[e]dit done"),
|
||||
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 {
|
||||
match self.app_edit_mode {
|
||||
AppEditMode::None => {
|
||||
let mut spans = vec![
|
||||
Span::from(if self.running_clock {
|
||||
"[s]top"
|
||||
@@ -165,6 +152,12 @@ impl StatefulWidget for Footer {
|
||||
Span::from(SPACE),
|
||||
Span::from("[e]dit"),
|
||||
];
|
||||
if self.selected_content == Content::Countdown {
|
||||
spans.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
Span::from("[^e]dit by local time"),
|
||||
]);
|
||||
}
|
||||
if self.selected_content == Content::Pomodoro {
|
||||
spans.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
@@ -173,6 +166,24 @@ impl StatefulWidget for Footer {
|
||||
}
|
||||
spans
|
||||
}
|
||||
others => vec![
|
||||
Span::from(match others {
|
||||
AppEditMode::Clock => "[e]dit done",
|
||||
AppEditMode::Time => "[^e]dit done",
|
||||
_ => "",
|
||||
}),
|
||||
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)), // ↓,
|
||||
],
|
||||
}
|
||||
})),
|
||||
]),
|
||||
],
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use crate::{
|
||||
common::Style,
|
||||
constants::TICK_VALUE_MS,
|
||||
events::{Event, EventHandler},
|
||||
events::{AppEventTx, TuiEvent, TuiEventHandler},
|
||||
utils::center,
|
||||
widgets::clock::{ClockState, ClockWidget, Countdown},
|
||||
widgets::clock::{ClockState, ClockStateArgs, ClockWidget, Countdown},
|
||||
};
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
@@ -12,13 +12,9 @@ use ratatui::{
|
||||
text::Line,
|
||||
widgets::{StatefulWidget, Widget},
|
||||
};
|
||||
use std::{cmp::max, time::Duration};
|
||||
|
||||
use strum::Display;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::clock::ClockStateArgs;
|
||||
use std::{cmp::max, time::Duration};
|
||||
use strum::Display;
|
||||
|
||||
#[derive(Debug, Clone, Display, Hash, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub enum Mode {
|
||||
@@ -26,7 +22,6 @@ pub enum Mode {
|
||||
Pause,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClockMap {
|
||||
work: ClockState<Countdown>,
|
||||
pause: ClockState<Countdown>,
|
||||
@@ -47,7 +42,6 @@ impl ClockMap {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PomodoroState {
|
||||
mode: Mode,
|
||||
clock_map: ClockMap,
|
||||
@@ -60,6 +54,7 @@ pub struct PomodoroStateArgs {
|
||||
pub initial_value_pause: Duration,
|
||||
pub current_value_pause: Duration,
|
||||
pub with_decis: bool,
|
||||
pub app_tx: AppEventTx,
|
||||
}
|
||||
|
||||
impl PomodoroState {
|
||||
@@ -71,6 +66,7 @@ impl PomodoroState {
|
||||
initial_value_pause,
|
||||
current_value_pause,
|
||||
with_decis,
|
||||
app_tx,
|
||||
} = args;
|
||||
Self {
|
||||
mode,
|
||||
@@ -80,13 +76,17 @@ impl PomodoroState {
|
||||
current_value: current_value_work,
|
||||
tick_value: Duration::from_millis(TICK_VALUE_MS),
|
||||
with_decis,
|
||||
}),
|
||||
app_tx: Some(app_tx.clone()),
|
||||
})
|
||||
.with_name("Work".to_owned()),
|
||||
pause: ClockState::<Countdown>::new(ClockStateArgs {
|
||||
initial_value: initial_value_pause,
|
||||
current_value: current_value_pause,
|
||||
tick_value: Duration::from_millis(TICK_VALUE_MS),
|
||||
with_decis,
|
||||
}),
|
||||
app_tx: Some(app_tx),
|
||||
})
|
||||
.with_name("Pause".to_owned()),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -124,14 +124,15 @@ impl PomodoroState {
|
||||
}
|
||||
}
|
||||
|
||||
impl EventHandler for PomodoroState {
|
||||
fn update(&mut self, event: Event) -> Option<Event> {
|
||||
impl TuiEventHandler for PomodoroState {
|
||||
fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
|
||||
let edit_mode = self.get_clock().is_edit_mode();
|
||||
match event {
|
||||
Event::Tick => {
|
||||
TuiEvent::Tick => {
|
||||
self.get_clock_mut().tick();
|
||||
self.get_clock_mut().update_done_count();
|
||||
}
|
||||
Event::Key(key) => match key.code {
|
||||
TuiEvent::Key(key) => match key.code {
|
||||
KeyCode::Char('s') => {
|
||||
self.get_clock_mut().toggle_pause();
|
||||
}
|
||||
@@ -170,12 +171,13 @@ impl EventHandler for PomodoroState {
|
||||
|
||||
pub struct PomodoroWidget {
|
||||
pub style: Style,
|
||||
pub blink: bool,
|
||||
}
|
||||
|
||||
impl StatefulWidget for PomodoroWidget {
|
||||
type State = PomodoroState;
|
||||
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
||||
let clock_widget = ClockWidget::new(self.style);
|
||||
let clock_widget = ClockWidget::new(self.style, self.blink);
|
||||
let label = Line::raw(
|
||||
(format!(
|
||||
"Pomodoro {} {}",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
common::Style,
|
||||
events::{Event, EventHandler},
|
||||
events::{TuiEvent, TuiEventHandler},
|
||||
utils::center,
|
||||
widgets::clock::{self, ClockState, ClockWidget},
|
||||
};
|
||||
@@ -13,7 +13,6 @@ use ratatui::{
|
||||
};
|
||||
use std::cmp::max;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TimerState {
|
||||
clock: ClockState<clock::Timer>,
|
||||
}
|
||||
@@ -32,14 +31,15 @@ impl TimerState {
|
||||
}
|
||||
}
|
||||
|
||||
impl EventHandler for TimerState {
|
||||
fn update(&mut self, event: Event) -> Option<Event> {
|
||||
impl TuiEventHandler for TimerState {
|
||||
fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
|
||||
let edit_mode = self.clock.is_edit_mode();
|
||||
match event {
|
||||
Event::Tick => {
|
||||
TuiEvent::Tick => {
|
||||
self.clock.tick();
|
||||
self.clock.update_done_count();
|
||||
}
|
||||
Event::Key(key) => match key.code {
|
||||
TuiEvent::Key(key) => match key.code {
|
||||
KeyCode::Char('s') => {
|
||||
self.clock.toggle_pause();
|
||||
}
|
||||
@@ -71,13 +71,14 @@ impl EventHandler for TimerState {
|
||||
|
||||
pub struct Timer {
|
||||
pub style: Style,
|
||||
pub blink: bool,
|
||||
}
|
||||
|
||||
impl StatefulWidget for Timer {
|
||||
type State = TimerState;
|
||||
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
||||
let clock = &mut state.clock;
|
||||
let clock_widget = ClockWidget::new(self.style);
|
||||
let clock_widget = ClockWidget::new(self.style, self.blink);
|
||||
let label = Line::raw((format!("Timer {}", clock.get_mode())).to_uppercase());
|
||||
|
||||
let area = center(
|
||||
|
||||
Reference in New Issue
Block a user