Compare commits
78 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca9d17f1ee | ||
|
|
1bebfb897a | ||
|
|
90c0e50f1c | ||
|
|
27cb8c7e33 | ||
|
|
513f1fec11 | ||
|
|
1742d68c61 | ||
|
|
4ec52545e5 | ||
|
|
dfe3cfcc80 | ||
|
|
c637a82deb | ||
|
|
361a82ee08 | ||
|
|
95d914c757 | ||
|
|
e11dcaa913 | ||
|
|
d2f41e04e2 | ||
|
|
51f83e5b06 | ||
|
|
b5f3c709bf | ||
|
|
56e6ce66fa | ||
|
|
758a72fbf6 | ||
|
|
6b6221803c | ||
|
|
4594bc722e | ||
|
|
e2cd536079 | ||
|
|
99032834be | ||
|
|
f79813ac6b | ||
|
|
6437795c9f | ||
|
|
0c4f507ebf | ||
|
|
eb376e4015 | ||
|
|
ac2863cebc | ||
|
|
3f4acec9f5 | ||
|
|
2277eeb033 | ||
|
|
cb6c2d5142 | ||
|
|
6dc7eb81c2 | ||
|
|
816741f842 | ||
|
|
40eb602953 | ||
|
|
d5bf7f32a6 | ||
|
|
9ff65e5c8e | ||
|
|
24eb471df8 | ||
|
|
0521c57695 | ||
|
|
f9a2e18179 | ||
|
|
bac2e356e1 | ||
|
|
60392b40ed | ||
|
|
901cf69472 | ||
|
|
c494f0e829 | ||
|
|
637c1da21b | ||
|
|
3439e4aa8d | ||
|
|
5bc37f005f | ||
|
|
bfa40fd8f1 | ||
|
|
93a3cde396 | ||
|
|
d27587a44a | ||
|
|
5f4c5bb8ed | ||
|
|
44af71c01c | ||
|
|
c370d3096b | ||
|
|
aae5c38cd6 | ||
|
|
5ad09b9848 | ||
|
|
52ed8267be | ||
|
|
6b068bbd09 | ||
|
|
c96432779a | ||
|
|
509cf73cdd | ||
|
|
e6291a3131 | ||
|
|
90d9988e7a | ||
|
|
028a067419 | ||
|
|
675428cfb0 | ||
|
|
28c5d7194c | ||
|
|
5b445afe25 | ||
|
|
beb12d5ec2 | ||
|
|
d9399eafc9 | ||
|
|
ffad78e093 | ||
|
|
e7a5a1b2da | ||
|
|
6f0df4d488 | ||
|
|
3d9b235f12 | ||
|
|
e094d7d81b | ||
|
|
843c4d019d | ||
|
|
e95ecb9e9c | ||
|
|
886deb3311 | ||
|
|
7ff167368d | ||
|
|
a54b1b409a | ||
|
|
8f50bc5fc6 | ||
|
|
d3c436da0b | ||
|
|
97787f718d | ||
|
|
557fcf95f0 |
2
.github/workflows/release.yml
vendored
@ -4,8 +4,6 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- "release/**"
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
get-version:
|
||||
|
||||
7
.gitignore
vendored
@ -18,3 +18,10 @@ result/**/*
|
||||
#.idea/
|
||||
#
|
||||
.direnv
|
||||
|
||||
# ignore (possible) sound files
|
||||
**/*.{mp3,wav}
|
||||
|
||||
|
||||
CLAUDE.md
|
||||
.claude
|
||||
|
||||
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
24
AGENTS.md
Normal file
@ -0,0 +1,24 @@
|
||||
# About
|
||||
|
||||
`timr-tui` is a TUI to maintain productivity and focus by providing different timers: Pomodoro, Countdown, Timer, Events.
|
||||
|
||||
Built with Rust using `Ratatui` as the main library.
|
||||
|
||||
# Development, Build, Tests
|
||||
|
||||
Check [README](./README.md) chapter `Development` to get all information about how to run, build, test the app.
|
||||
|
||||
# Code Guidelines
|
||||
|
||||
- Idiomatic Rust everywhere
|
||||
- DRY whenever it makes sense
|
||||
- Rare or no comments are preferred instead of commenting everything which the code already describes
|
||||
- Keep tests compact and simple
|
||||
|
||||
# Agent Guidelines
|
||||
|
||||
- Keep your answers compact, but explicit. An user will ask if something is missing.
|
||||
- For complex tasks provide a plan.
|
||||
- Structure plans as small as possible.
|
||||
- Solve complex problems step by step, never all at once.
|
||||
- Act as a pair programmer, not as a vibe-coding provider. That's an user should guide you, not the opposite. Always ask if something is not clear to you.
|
||||
139
CHANGELOG.md
@ -1,5 +1,144 @@
|
||||
# Changelog
|
||||
|
||||
## [unreleased]
|
||||
|
||||
### Misc.
|
||||
|
||||
- (deps) Rust 1.91.0 [#140](https://github.com/sectore/timr-tui/pull/140)
|
||||
|
||||
## v1.6.1 - 2025-10-29
|
||||
|
||||
### Fix
|
||||
|
||||
- (event) Ignore all key events except `KeyEventKind::Press` [#137](https://github.com/sectore/timr-tui/issues/137)
|
||||
|
||||
### Misc.
|
||||
|
||||
- (docs) Update all demos [#135](https://github.com/sectore/timr-tui/pull/135), [513f1fe](https://github.com/sectore/timr-tui/commit/513f1fec11ab8bdad46ca565b0c3f08ed37d6219)
|
||||
|
||||
## v1.6.0 - 2025-10-16
|
||||
|
||||
### Features
|
||||
|
||||
- (event) New `event` screen to count custom date times in the future or past. [#117](https://github.com/sectore/timr-tui/pull/117), [#120](https://github.com/sectore/timr-tui/pull/120), [#122](https://github.com/sectore/timr-tui/pull/122), [#123](https://github.com/sectore/timr-tui/pull/123), [#124](https://github.com/sectore/timr-tui/pull/124), [#125](https://github.com/sectore/timr-tui/pull/125), [#129](https://github.com/sectore/timr-tui/pull/129), [#130](https://github.com/sectore/timr-tui/pull/130), [#131](https://github.com/sectore/timr-tui/pull/131), [#132](https://github.com/sectore/timr-tui/pull/132)
|
||||
- (keybindings) Switch screens by `←` or `→` keys [#127](https://github.com/sectore/timr-tui/pull/127)
|
||||
- (duration) Inrease `MAX_DURATION` to `9999y 364d 23:59:59.9` [#128](https://github.com/sectore/timr-tui/pull/128)
|
||||
|
||||
### Breaking change
|
||||
|
||||
- (pomodoro)! New keybindings `ctrl+←` or `ctrl+→` to switch `work`/`pause` [#127](https://github.com/sectore/timr-tui/pull/127)
|
||||
- (keybindings)! Change keys for `screens` [#126](https://github.com/sectore/timr-tui/pull/126)
|
||||
- (cli)! Remove `--countdown-target` argument [#121](https://github.com/sectore/timr-tui/pull/121)
|
||||
|
||||
### Misc.
|
||||
|
||||
- Add `AGENTS.md` [#133](https://github.com/sectore/timr-tui/pull/133)
|
||||
|
||||
## v1.5.0 - 2025-10-03
|
||||
|
||||
### Features
|
||||
|
||||
- (cli) Accept `years` and `days` for `--countdown` argument [#114](https://github.com/sectore/timr-tui/pull/114)
|
||||
- (cli) New `--countdown-target` argument to parse `countdown` values by given time in the future or past [#112](https://github.com/sectore/timr-tui/pull/112)
|
||||
- (localtime) Show `date` [#111](https://github.com/sectore/timr-tui/pull/111)
|
||||
- (edit) Change any value by `10x` up or down [#110](https://github.com/sectore/timr-tui/pull/110)
|
||||
- (timer/countdown): Support `days` and `years` up to `999y 364d 23:59:59` [#96](https://github.com/sectore/timr-tui/pull/96)
|
||||
|
||||
### Fix
|
||||
|
||||
- (edit) Auto jump to next possible value while decreasing, but ignoring `zero` values [#109](https://github.com/sectore/timr-tui/pull/109)
|
||||
- (format) Improve format handling + fix `days` (no zero-padding) [#107](https://github.com/sectore/timr-tui/pull/107)
|
||||
|
||||
### Misc.
|
||||
|
||||
- (deps) Upgrade dependencies [#113](https://github.com/sectore/timr-tui/pull/113)
|
||||
- (deps) Rust 1.90.0 [#95](https://github.com/sectore/timr-tui/pull/95)
|
||||
- (guide) Add contributing guidelines [#94](https://github.com/sectore/timr-tui/pull/94)
|
||||
|
||||
## v1.4.0 - 2025-09-02
|
||||
|
||||
### Features
|
||||
|
||||
- (screen) Local Time [#89](https://github.com/sectore/timr-tui/pull/89), [#90](https://github.com/sectore/timr-tui/pull/90), [#91](https://github.com/sectore/timr-tui/pull/91)
|
||||
|
||||
### Misc.
|
||||
|
||||
- (deps) Rust 1.89.0 [#87](https://github.com/sectore/timr-tui/pull/87)
|
||||
|
||||
## v1.3.1 - 2025-07-03
|
||||
|
||||
### Features
|
||||
|
||||
- (args) set `content` by given duration [#81](https://github.com/sectore/timr-tui/pull/81)
|
||||
|
||||
### Fixes
|
||||
|
||||
- (pomodoro) `ctrl+r` resets rounds AND both clocks [#83](https://github.com/sectore/timr-tui/pull/83)
|
||||
- (pomodoro) reset active clock only [#82](https://github.com/sectore/timr-tui/pull/82)
|
||||
|
||||
### Misc.
|
||||
|
||||
- (deps) Rust 1.88.0 [#85](https://github.com/sectore/timr-tui/pull/85)
|
||||
|
||||
## v1.3.0 - 2025-05-06
|
||||
|
||||
###
|
||||
|
||||
- (pomodoro) Count WORK rounds [#75](https://github.com/sectore/timr-tui/pull/75), [6b068bb](https://github.com/sectore/timr-tui/commit/6b068bbd094d9ec1a36b47598fadfc71296d9590)
|
||||
- (pomodoro/countdown) Change initial value [#79](https://github.com/sectore/timr-tui/pull/79), [aae5c38](https://github.com/sectore/timr-tui/commit/aae5c38cd6a666d5ba418b12fb67879a2146b9a2)
|
||||
|
||||
### Changes
|
||||
|
||||
- Update keybindings [#76](https://github.com/sectore/timr-tui/pull/76)
|
||||
|
||||
### Misc.
|
||||
|
||||
- (flake) use alsa-lib-with-plugins [#77](https://github.com/sectore/timr-tui/pull/77)
|
||||
- (readme) add keybindings + toc [#78](https://github.com/sectore/timr-tui/pull/78)
|
||||
|
||||
## v1.2.1 - 2025-04-17
|
||||
|
||||
### Fixes
|
||||
|
||||
- (countdown) Reset `Mission Elapsed Time (MET)` if `countdown` is set by _cli arguments_ [#71](https://github.com/sectore/timr-tui/pull/71)
|
||||
- (countdown) Reset `Mission Elapsed Time (MET)` while setting `countdown` by _local time_ [#72](https://github.com/sectore/timr-tui/pull/72)
|
||||
|
||||
### Misc.
|
||||
|
||||
- (deps) Use latest `Rust 1.86` [#73](https://github.com/sectore/timr-tui/pull/73)
|
||||
- (cargo) Exclude files for packaging [e7a5a1b](https://github.com/sectore/timr-tui/commit/e7a5a1b2da7a7967f2602a0b92f391ac768ca638)
|
||||
- (just) `group` commands [#70](https://github.com/sectore/timr-tui/pull/70)
|
||||
|
||||
## v1.2.0 - 2025-02-26
|
||||
|
||||
### Features
|
||||
|
||||
- (notification) Clock animation (blink) by reaching `done` mode (optional) [#65](https://github.com/sectore/timr-tui/pull/65)
|
||||
- (notification) Native desktop notification (optional, experimental) [#59](https://github.com/sectore/timr-tui/pull/59)
|
||||
- (notification) Sound notification (optional, experimental, available in local build only) [#62](https://github.com/sectore/timr-tui/pull/62)
|
||||
- (logging) Add `--log` arg to enable logs [e094d7d](https://github.com/sectore/timr-tui/commit/e094d7d81b99f58f0d3bc50124859a4e1f6dbe4f)
|
||||
|
||||
### Misc.
|
||||
|
||||
- (refactor) Extend event handling for using a `mpsc` channel to send `AppEvent`'s from anywhere. [#61](https://github.com/sectore/timr-tui/pull/61)
|
||||
- (extension) Use `set_panic_hook` for better error handling [#67](https://github.com/sectore/timr-tui/pull/67)
|
||||
- (deps) Use latest `Rust 1.85` and `Rust 2024 Edition`. Refactor `flake` to consider `rust-toolchain.toml` etc. [#68](https://github.com/sectore/timr-tui/pull/68)
|
||||
|
||||
## v1.1.0 - 2025-01-22
|
||||
|
||||
### Features
|
||||
|
||||
- (countdown) Edit countdown by local time [#49](https://github.com/sectore/timr-tui/pull/49)
|
||||
|
||||
### Fixes
|
||||
|
||||
- (ci) Build statically linked binaries for Linux [#55](https://github.com/sectore/timr-tui/pull/55)
|
||||
- (ci) Remove magic nix cache action (#57) [#56](https://github.com/sectore/timr-tui/issues/56)
|
||||
|
||||
### Misc.
|
||||
|
||||
- (deps) Latest Rust 1.84, update deps [#48](https://github.com/sectore/timr-tui/pull/48)
|
||||
|
||||
## v1.0.0 - 2025-01-10
|
||||
|
||||
Happy `v1.0.0` 🎉
|
||||
|
||||
18
CONTRIBUTING.md
Normal file
@ -0,0 +1,18 @@
|
||||
# Contributing
|
||||
|
||||
Any feedback / contribution are welcome. Just open an `issue`, a `PR` or start a `discussion`.
|
||||
|
||||
## Code style / conventions
|
||||
|
||||
- Try to write [clean, idiomatic Rust code](https://github.com/mre/idiomatic-rust).
|
||||
- Keep code [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) whenever it makes sense.
|
||||
- Before pushing any code make sure to run `clippy` and `fmt`. Check provided [`just`](./jusfile) file to run such commands, [CI](https://github.com/sectore/timr-tui/blob/main/.github/workflows/ci.yml) will do the same.
|
||||
- Have fun to write code.
|
||||
|
||||
## Design files
|
||||
|
||||
Use [Figma Design file](https://www.figma.com/community/file/1553076532392275586/timr-tui) to suggest design changes
|
||||
|
||||
## AI
|
||||
|
||||
Always understand what AI provides to you. Never push any code based on [`vibe coding`](https://en.wikipedia.org/wiki/Vibe_coding) you or anybody else can't follow. Make sure your agent still follows all code styles and conventions suggested above. Use AI for better, not for worse code.
|
||||
2100
Cargo.lock
generated
42
Cargo.toml
@ -1,29 +1,49 @@
|
||||
[package]
|
||||
name = "timr-tui"
|
||||
version = "1.1.0-alpha"
|
||||
version = "1.6.1"
|
||||
description = "TUI to organize your time: Pomodoro, Countdown, Timer."
|
||||
edition = "2021"
|
||||
rust-version = "1.84.0"
|
||||
edition = "2024"
|
||||
# Reminder: Always keep `channel` in `rust-toolchain.toml` in sync with `rust-version`.
|
||||
rust-version = "1.91.0"
|
||||
homepage = "https://github.com/sectore/timr-tui"
|
||||
repository = "https://github.com/sectore/timr-tui"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
keywords = ["tui", "timer", "countdown", "pomodoro"]
|
||||
categories = ["command-line-utilities"]
|
||||
exclude = [
|
||||
".github/*",
|
||||
"demo/*.tape",
|
||||
"result/*",
|
||||
"*.mp3",
|
||||
".claude",
|
||||
"CLAUDE.md",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
ratatui = "0.29.0"
|
||||
crossterm = {version = "0.28.1", features = ["event-stream", "serde"] }
|
||||
color-eyre = "0.6.2"
|
||||
crossterm = { version = "0.28.1", features = ["event-stream", "serde"] }
|
||||
color-eyre = "0.6.5"
|
||||
futures = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
strum = { version = "0.26.3", features = ["derive"] }
|
||||
tokio = { version = "1.41.1", features = ["full"] }
|
||||
tokio-stream = "0.1.16"
|
||||
tokio-util = "0.7.12"
|
||||
tokio = { version = "1.47.1", features = ["full"] }
|
||||
tokio-stream = "0.1.17"
|
||||
tokio-util = "0.7.16"
|
||||
tracing = "0.1.41"
|
||||
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
|
||||
tracing-subscriber = { version = "0.3.20", features = ["env-filter"] }
|
||||
directories = "5.0.1"
|
||||
clap = { version = "4.5.23", features = ["derive"] }
|
||||
time = { version = "0.3.37", features = ["formatting", "local-offset"] }
|
||||
clap = { version = "4.5.48", features = ["derive"] }
|
||||
time = { version = "0.3.44", features = ["formatting", "local-offset", "parsing", "macros", "serde"] }
|
||||
notify-rust = "4.11.7"
|
||||
rodio = { version = "0.20.1", features = [
|
||||
"symphonia-mp3",
|
||||
"symphonia-wav",
|
||||
], default-features = false, optional = true }
|
||||
thiserror = { version = "2.0.17", optional = true }
|
||||
tui-input = "0.14.0"
|
||||
|
||||
|
||||
[features]
|
||||
sound = ["dep:rodio", "dep:thiserror"]
|
||||
|
||||
2
LICENSE
@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Jens K.
|
||||
Copyright (c) 2024-2025 Jens Krause
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
243
README.md
@ -1,16 +1,29 @@
|
||||
# timr-tui
|
||||
|
||||
TUI to organize your time: Pomodoro, Countdown, Timer.
|
||||
TUI to organize your time: Pomodoro, Countdown, Timer, Event.
|
||||
|
||||
- `[t]imer` Check the time on anything you are you doing.
|
||||
- `[c]ountdown` Use it for your workout, yoga session, meditation, handstand or whatever.
|
||||
- `[p]omodoro` Organize your working time to be focused all the time by following the [Pomodoro Technique](https://en.wikipedia.org/wiki/Pomodoro_Technique).
|
||||
- `[1] countdown` Use it for your workout, yoga/breathing sessions, meditation, handstand or whatever.
|
||||
- `[2] timer` Check the time on anything you are you doing.
|
||||
- `[3] pomodoro` Organize your working time to be focused all the time by following the [Pomodoro Technique](https://en.wikipedia.org/wiki/Pomodoro_Technique).
|
||||
- `[4] event` Count the time for any event in the future or past.
|
||||
|
||||
Built with [Ratatui](https://ratatui.rs/) / [Rust 🦀](https://www.rust-lang.org/).
|
||||
|
||||
# Features
|
||||
|
||||
_Side note:_ Theme colors depend on your terminal preferences.
|
||||
# Table of Contents
|
||||
|
||||
- [Preview](./#preview)
|
||||
- [CLI](./#cli)
|
||||
- [Keybindings](./#keybindings)
|
||||
- [Installation](./#installation)
|
||||
- [Development](./#development)
|
||||
- [Misc](./#misc)
|
||||
- [Contributing](./#contributing)
|
||||
- [License](./#license)
|
||||
|
||||
# Preview
|
||||
|
||||
_(theme depends on your terminal preferences)_
|
||||
|
||||
## Pomodoro
|
||||
|
||||
@ -24,16 +37,28 @@ _Side note:_ Theme colors depend on your terminal preferences.
|
||||
<img alt="pomodoro" src="demo/timer.gif" />
|
||||
</a>
|
||||
|
||||
## Countdown
|
||||
## Countdown (*incl. [Mission Elapsed Time](https://en.wikipedia.org/wiki/Mission_Elapsed_Time)*)
|
||||
|
||||
<a href="demo/countdown.gif">
|
||||
<img alt="countdown" src="demo/countdown.gif" />
|
||||
</a>
|
||||
|
||||
## Change style
|
||||
## Event (*past/future*)
|
||||
|
||||
<a href="demo/style.gif">
|
||||
<img alt="style" src="demo/style.gif" />
|
||||
<a href="demo/event.gif">
|
||||
<img alt="event" src="demo/event.gif" />
|
||||
</a>
|
||||
|
||||
## Local time
|
||||
|
||||
<a href="demo/local-time.gif">
|
||||
<img alt="local time" src="demo/local-time.gif" />
|
||||
</a>
|
||||
|
||||
## Local time (*footer*)
|
||||
|
||||
<a href="demo/local-time-footer.gif">
|
||||
<img alt="local time at footer" src="demo/local-time-footer.gif" />
|
||||
</a>
|
||||
|
||||
## Toggle deciseconds
|
||||
@ -42,24 +67,25 @@ _Side note:_ Theme colors depend on your terminal preferences.
|
||||
<img alt="deciseconds" src="demo/decis.gif" />
|
||||
</a>
|
||||
|
||||
## Maximum (*`9999y`* *`364d`* *`23:59:59.9`*)
|
||||
|
||||
<a href="demo/timer-max.png">
|
||||
<img alt="maximum" src="demo/timer-max.png" />
|
||||
</a>
|
||||
|
||||
|
||||
## Change style
|
||||
|
||||
<a href="demo/style.gif">
|
||||
<img alt="style" src="demo/style.gif" />
|
||||
</a>
|
||||
|
||||
## Menu
|
||||
|
||||
<a href="demo/menu.gif">
|
||||
<img alt="menu" src="demo/menu.gif" />
|
||||
</a>
|
||||
|
||||
## Local time
|
||||
|
||||
<a href="demo/local-time.gif">
|
||||
<img alt="menu" src="demo/local-time.gif" />
|
||||
</a>
|
||||
|
||||
## Mission Elapsed Time ([MET](https://en.wikipedia.org/wiki/Mission_Elapsed_Time))
|
||||
|
||||
<a href="demo/countdown-met.gif">
|
||||
<img alt="menu" src="demo/countdown-met.gif" />
|
||||
</a>
|
||||
|
||||
# CLI
|
||||
|
||||
```sh
|
||||
@ -68,18 +94,100 @@ 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.
|
||||
-h, --help Print help
|
||||
-V, --version Print version
|
||||
-c, --countdown <COUNTDOWN> Countdown time to start from. Formats: 'Yy Dd hh:mm:ss', 'Dd hh:mm:ss', 'Yy mm:ss', 'Dd mm:ss', 'Yy ss', 'Dd ss', 'hh:mm:ss', 'mm:ss', 'ss'. Examples: '1y 5d 10:30:00', '2d 4:00', '1d 10', '5:03'.
|
||||
-w, --work <WORK> Work time to count down from. Formats: 'ss', 'mm:ss', 'hh:mm:ss'
|
||||
-p, --pause <PAUSE> Pause time to count down from. Formats: 'ss', 'mm:ss', 'hh:mm:ss'
|
||||
-e, --event <EVENT> Event date time and title (optional). Format: 'YYYY-MM-DD HH:MM:SS' or 'time=YYYY-MM-DD HH:MM:SS[,title=...]'. Examples: '2025-10-10 14:30:00' or 'time=2025-10-10 14:30:00,title=My Event'.
|
||||
-d, --decis Show deciseconds.
|
||||
-m, --mode <MODE> Mode to start with. [possible values: countdown, timer, pomodoro, event, localtime]
|
||||
-s, --style <STYLE> Style to display time with. [possible values: full, light, medium, dark, thick, cross, braille]
|
||||
--menu Open menu.
|
||||
-r, --reset Reset stored values to defaults.
|
||||
-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 for 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.
|
||||
```
|
||||
|
||||
# Keybindings
|
||||
|
||||
## Menu
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| <kbd>↑</kbd> / <kbd>↓</kbd> or <kbd>m</kbd> | Toggle menu |
|
||||
|
||||
## Screens
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| <kbd>1</kbd> | Pomodoro |
|
||||
| <kbd>2</kbd> | Countdown |
|
||||
| <kbd>3</kbd> | Timer |
|
||||
| <kbd>4</kbd> | Event |
|
||||
| <kbd>0</kbd> | Local Time |
|
||||
| <kbd>→</kbd> | next screen |
|
||||
| <kbd>←</kbd> | previous screen |
|
||||
|
||||
## Controls
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| <kbd>s</kbd> | start |
|
||||
| <kbd>r</kbd> | reset |
|
||||
| <kbd>e</kbd> | enter edit mode |
|
||||
| <kbd>q</kbd> | quit |
|
||||
|
||||
**In `edit` mode only:**
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| <kbd>s</kbd> | save changes |
|
||||
| <kbd>Esc</kbd> | skip changes |
|
||||
| <kbd>←</kbd> or <kbd>→</kbd> | change selection |
|
||||
| <kbd>↑</kbd> | edit to go up |
|
||||
| <kbd>ctrl+↑</kbd> | edit to go up 10x |
|
||||
| <kbd>↓</kbd> | edit to go down |
|
||||
| <kbd>ctrl+↓</kbd> | edit to go down 10x |
|
||||
|
||||
**In `Event` `edit` mode only:**
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| <kbd>Enter</kbd> | save changes |
|
||||
| <kbd>Esc</kbd> | skip changes |
|
||||
| <kbd>Tab</kbd> | switch input |
|
||||
|
||||
**In `Pomodoro` screen only:**
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| <kbd>ctrl+←</kbd> or <kbd>ctrl+→</kbd> | switch work/pause |
|
||||
| <kbd>ctrl+r</kbd> | reset round |
|
||||
| <kbd>ctrl+s</kbd> | save initial value |
|
||||
|
||||
**In `Countdown` screen only:**
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| <kbd>ctrl+e</kbd> | edit by local time |
|
||||
| <kbd>ctrl+s</kbd> | save initial value |
|
||||
|
||||
## Appearance
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| <kbd>,</kbd> | toggle styles |
|
||||
| <kbd>.</kbd> | toggle deciseconds |
|
||||
| <kbd>:</kbd> | toggle local time |
|
||||
|
||||
# Installation
|
||||
|
||||
## Cargo
|
||||
@ -104,12 +212,10 @@ Install [from the AUR](https://aur.archlinux.org/packages/timr/):
|
||||
paru -S timr
|
||||
```
|
||||
|
||||
|
||||
## Release binaries
|
||||
|
||||
Pre-built artifacts are available to download from [latest GitHub release](https://github.com/sectore/timr-tui/releases).
|
||||
|
||||
|
||||
# Development
|
||||
|
||||
## Requirements
|
||||
@ -120,7 +226,6 @@ Pre-built artifacts are available to download from [latest GitHub release](https
|
||||
|
||||
If you have [`direnv`](https://direnv.net) installed, run `direnv allow` once to install dependencies. In other case run `nix develop`.
|
||||
|
||||
|
||||
### Non Nix users
|
||||
|
||||
- [`Rust`](https://www.rust-lang.org/learn/get-started)
|
||||
@ -131,34 +236,64 @@ 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`
|
||||
default # list commands
|
||||
|
||||
[build]
|
||||
build # build app [alias: b]
|
||||
|
||||
[demo]
|
||||
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-event # build demo: event [alias: de]
|
||||
demo-local-time # build demo: local time [alias: dlt]
|
||||
demo-local-time-footer # build demo: local time (footer) [alias: dltf]
|
||||
demo-menu # build demo: menu [alias: dm]
|
||||
demo-pomodoro # build demo: pomodoro [alias: dp]
|
||||
demo-rocket-countdown # build demo: rocket countdown [alias: drc]
|
||||
demo-style # build demo: styles [alias: ds]
|
||||
demo-timer # build demo: timer [alias: dt]
|
||||
|
||||
[dev]
|
||||
run # run app [alias: r]
|
||||
run-args args # run app with arguments. It expects arguments as a string (e.g. "-c 5:00"). [alias: ra]
|
||||
run-sound path # run app while sound feature is enabled. It expects a path to a sound file. [alias: rs]
|
||||
run-sound-args path args # run app while sound feature is enabled by adding a path to a sound file and other arguments as string (e.g. "-c 5:00"). [alias: rsa]
|
||||
|
||||
[misc]
|
||||
format # format files [alias: f]
|
||||
lint # lint [alias: l]
|
||||
|
||||
[test]
|
||||
test # run tests [alias: t]
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
- Linux
|
||||
|
||||
```sh
|
||||
nix build
|
||||
# or for bulding w/ statically linked binaries
|
||||
nix build .#linuxStatic
|
||||
```
|
||||
|
||||
- Windows (cross-compilation)
|
||||
|
||||
```sh
|
||||
nix build .#windows
|
||||
```
|
||||
|
||||
### Run tests
|
||||
|
||||
```sh
|
||||
cargo test
|
||||
```
|
||||
|
||||
# Misc.
|
||||
|
||||
## Persistant app state
|
||||
@ -176,7 +311,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 +323,13 @@ 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.
|
||||
|
||||
# Contributing
|
||||
|
||||
[CONTRIBUTING.md](./CONTRIBUTING.md)
|
||||
|
||||
# License
|
||||
|
||||
[MIT License](./LICENSE)
|
||||
|
||||
BIN
demo/blink.gif
Normal file
|
After Width: | Height: | Size: 46 KiB |
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 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Set LoopOffset 4
|
||||
Hide
|
||||
# countdown 1.0s
|
||||
Type "cargo run -- -r -m countdown -d -c 1 --blink=on"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Type "m"
|
||||
Type ":::"
|
||||
Show
|
||||
Type "s"
|
||||
Sleep 4
|
||||
BIN
demo/countdown-max.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
19
demo/countdown-max.tape
Normal file
@ -0,0 +1,19 @@
|
||||
|
||||
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
|
||||
Set Theme "Retro"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Type 'cargo run -- -r -d -c "10000y"'
|
||||
Enter
|
||||
Sleep .2
|
||||
Type "m"
|
||||
# --- SCREENSHOT ---
|
||||
Sleep 1s
|
||||
Screenshot demo/countdown-max.png
|
||||
Sleep 1s
|
||||
|
Before Width: | Height: | Size: 43 KiB |
@ -1,22 +0,0 @@
|
||||
Output demo/countdown-met.gif
|
||||
|
||||
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
|
||||
Set Theme "iceberg-light"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 800
|
||||
Set Height 400
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Set LoopOffset 4
|
||||
Hide
|
||||
Type "cargo run -- -m c -c 3"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Show
|
||||
Type "s"
|
||||
Sleep 6
|
||||
Type "r"
|
||||
Sleep 1
|
||||
|
Before Width: | Height: | Size: 83 KiB After Width: | Height: | Size: 81 KiB |
@ -1,23 +1,24 @@
|
||||
Output demo/countdown.gif
|
||||
|
||||
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
|
||||
Set Theme "Builtin Solarized Light"
|
||||
Set Theme "iceberg-light"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 800
|
||||
Set Height 400
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Set LoopOffset 4
|
||||
Hide
|
||||
Type "cargo run -- -r -d -m c"
|
||||
Type "cargo run -- -r -d -c 10:00"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Sleep .2
|
||||
Type "m" # hide menu
|
||||
Show
|
||||
# --- COUNTDOWN ---
|
||||
Sleep 1
|
||||
Sleep .5
|
||||
Type "s"
|
||||
Sleep 1.4
|
||||
Type "s"
|
||||
@ -28,6 +29,5 @@ Type "e"
|
||||
Sleep 0.1
|
||||
Down@10ms 65
|
||||
Sleep 0.1
|
||||
Type "e"
|
||||
Sleep 0.1
|
||||
Type "s"
|
||||
Sleep 3
|
||||
|
||||
BIN
demo/decis.gif
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 35 KiB |
@ -4,8 +4,8 @@ Output demo/decis.gif
|
||||
Set Theme "nord-light"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 800
|
||||
Set Height 400
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
@ -14,7 +14,8 @@ Set LoopOffset 4
|
||||
Hide
|
||||
Type "cargo run -- -r -m t"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Sleep .2
|
||||
Type "m" # hide menu
|
||||
Show
|
||||
# --- STYLES ---
|
||||
Type "s"
|
||||
|
||||
BIN
demo/event.gif
Normal file
|
After Width: | Height: | Size: 87 KiB |
31
demo/event.tape
Normal file
@ -0,0 +1,31 @@
|
||||
Output demo/event.gif
|
||||
|
||||
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
|
||||
Set Theme "Builtin Solarized Dark"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Set LoopOffset 4
|
||||
Hide
|
||||
Type "cargo run -- -r -e 'time=2010-01-10 10:00:00,title=hello world'"
|
||||
Enter
|
||||
Type "m"
|
||||
Sleep 0.2
|
||||
Show
|
||||
# --- EVENT ---
|
||||
Sleep 1
|
||||
Type "e"
|
||||
Backspace@1ms 17
|
||||
Type@20ms "50-01-01 01:00:01"
|
||||
Enter
|
||||
Type "e"
|
||||
Tab
|
||||
Backspace@10ms 11
|
||||
Type@20ms "hello future"
|
||||
Enter
|
||||
Sleep 1
|
||||
BIN
demo/local-time-footer.gif
Normal file
|
After Width: | Height: | Size: 16 KiB |
21
demo/local-time-footer.tape
Normal file
@ -0,0 +1,21 @@
|
||||
Output demo/local-time-footer.gif
|
||||
|
||||
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
|
||||
Set Theme "AtomOneLight"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Set LoopOffset 4
|
||||
Hide
|
||||
Type "cargo run -- -r -m c"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Type "m" # hide menu
|
||||
Show
|
||||
# --- toggle local time ---
|
||||
Type@1s ":::"
|
||||
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 24 KiB |
@ -1,22 +1,21 @@
|
||||
Output demo/local-time.gif
|
||||
|
||||
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
|
||||
Set Theme "AtomOneLight"
|
||||
Set Theme "Atom"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 800
|
||||
Set Height 400
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Set LoopOffset 4
|
||||
Hide
|
||||
Type "cargo run -- -m c"
|
||||
Type "cargo run -- -m l"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Sleep .2
|
||||
Type "m" # hide menu
|
||||
Show
|
||||
Sleep 1
|
||||
# --- toggle local time ---
|
||||
Type@1.5s ":::"
|
||||
Sleep 1.5
|
||||
Type@1s ":::"
|
||||
|
||||
BIN
demo/menu.gif
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 179 KiB |
@ -4,27 +4,24 @@ Output demo/menu.gif
|
||||
Set Theme "Apple Classic"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 800
|
||||
Set Height 400
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Set LoopOffset 4
|
||||
Hide
|
||||
Type "cargo run -- -r -m p"
|
||||
Type "cargo run -- -r -m c"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Type@200ms "m" # hide menu
|
||||
Show
|
||||
# --- STYLES ---
|
||||
Sleep 0.5
|
||||
Type "m"
|
||||
Sleep 0.5
|
||||
Type@0.5s "t"
|
||||
Type@0.5s "c"
|
||||
Type@0.5s "p"
|
||||
Type@0.5s "e"
|
||||
Right@0.5s
|
||||
Left@0.5s
|
||||
Type@0.5s "e"
|
||||
Sleep 0.5
|
||||
Sleep 0.3s
|
||||
Type@0.3s "m" # show menu
|
||||
Type@0.3s "2"
|
||||
Type@0.3s "3"
|
||||
Type@0.3s "e"
|
||||
Escape@0.3s
|
||||
Type@0.3s "4"
|
||||
Type@0.3s "0"
|
||||
|
||||
|
Before Width: | Height: | Size: 166 KiB After Width: | Height: | Size: 185 KiB |
@ -1,33 +1,35 @@
|
||||
# Note: PR "support ctrl + arrow keys" https://github.com/charmbracelet/vhs/pull/673 needs to be merged to run this `tape`.
|
||||
|
||||
Output demo/pomodoro.gif
|
||||
|
||||
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
|
||||
Set Theme "Catppuccin Frappe"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 800
|
||||
Set Height 400
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Set LoopOffset 4
|
||||
Hide
|
||||
Type "cargo run -- -r -d -m p"
|
||||
Type "cargo run -- -r -d -m p --blink on"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Sleep .2
|
||||
Type "m" # hide menu
|
||||
Show
|
||||
# --- POMODORO WORK ---
|
||||
Sleep 1
|
||||
Type "s"
|
||||
Sleep .5
|
||||
Type "s" # start
|
||||
Sleep 2.3
|
||||
Type "e"
|
||||
Sleep 0.2
|
||||
Down@30ms 80
|
||||
Sleep 100ms
|
||||
Type "e"
|
||||
Sleep 3
|
||||
Type "s" # save
|
||||
Sleep 4
|
||||
# --- POMODORO PAUSE ---
|
||||
Right
|
||||
Ctrl+Right
|
||||
Sleep 0.5
|
||||
Type "s"
|
||||
Sleep 2.3
|
||||
@ -35,5 +37,5 @@ Type "e"
|
||||
Sleep 0.2
|
||||
Down@30ms 60
|
||||
Sleep 100ms
|
||||
Type "e"
|
||||
Sleep 3
|
||||
Type "s" # save
|
||||
Sleep 4
|
||||
|
||||
|
Before Width: | Height: | Size: 24 KiB |
BIN
demo/style.gif
|
Before Width: | Height: | Size: 139 KiB After Width: | Height: | Size: 142 KiB |
@ -4,8 +4,8 @@ Output demo/style.gif
|
||||
Set Theme "OneDark"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 800
|
||||
Set Height 400
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
@ -15,6 +15,7 @@ Hide
|
||||
Type "cargo run -- -r -d -m c"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Type "m" # hide menu
|
||||
Show
|
||||
# --- STYLES ---
|
||||
Sleep 0.5
|
||||
|
||||
BIN
demo/timer-max.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
37
demo/timer-max.tape
Normal file
@ -0,0 +1,37 @@
|
||||
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
|
||||
Set Theme "SeaShells"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
# --- START ---
|
||||
Type 'cargo run -- -r -m t'
|
||||
Enter
|
||||
Type "m"
|
||||
Type "e"
|
||||
Up@1ms 60 # ss
|
||||
Left
|
||||
Up@1ms 60 # mm
|
||||
Left
|
||||
Up@1ms 23 # hh
|
||||
Left
|
||||
Up@1ms 363 # ddd
|
||||
Left
|
||||
Up@1ms 9999 # yyyy
|
||||
Right 4
|
||||
Down # ss
|
||||
Left
|
||||
Down ## mm
|
||||
Left 2
|
||||
Down ## ddd
|
||||
Up 2
|
||||
Type "."
|
||||
Type "s" # save
|
||||
Type "s" # start to reach DONE
|
||||
Sleep 2s
|
||||
# --- SCREENSHOT ---
|
||||
Screenshot demo/timer-max.png
|
||||
Sleep 1s
|
||||
BIN
demo/timer.gif
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 66 KiB |
@ -4,8 +4,8 @@ Output demo/timer.gif
|
||||
Set Theme "Belafonte Day"
|
||||
|
||||
Set FontSize 14
|
||||
Set Width 800
|
||||
Set Height 400
|
||||
Set Width 1000
|
||||
Set Height 500
|
||||
Set Padding 0
|
||||
Set Margin 1
|
||||
|
||||
@ -15,6 +15,7 @@ Hide
|
||||
Type "cargo run -- -r -d -m t"
|
||||
Enter
|
||||
Sleep 0.2
|
||||
Type "m" # hide menu
|
||||
Show
|
||||
# --- TIMER ---
|
||||
Type "s"
|
||||
@ -27,5 +28,5 @@ Type "e"
|
||||
Sleep 0.2
|
||||
Up@30ms 57
|
||||
Sleep 0.7
|
||||
Type "e"
|
||||
Type "s"
|
||||
Sleep 4
|
||||
|
||||
24
flake.lock
generated
@ -2,11 +2,11 @@
|
||||
"nodes": {
|
||||
"crane": {
|
||||
"locked": {
|
||||
"lastModified": 1736566337,
|
||||
"narHash": "sha256-SC0eDcZPqISVt6R0UfGPyQLrI0+BppjjtQ3wcSlk0oI=",
|
||||
"lastModified": 1760924934,
|
||||
"narHash": "sha256-tuuqY5aU7cUkR71sO2TraVKK2boYrdW3gCSXUkF4i44=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "9172acc1ee6c7e1cbafc3044ff850c568c75a5a3",
|
||||
"rev": "c6b4d5308293d0d04fcfeee92705017537cad02f",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -23,11 +23,11 @@
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1736577158,
|
||||
"narHash": "sha256-ngnAENZ+vmzOFgnj0EDtHj22nuH7MQB+EqzUmdbvaqA=",
|
||||
"lastModified": 1762065744,
|
||||
"narHash": "sha256-c04mxJoCb8f6BBrdaREWmdQq+pfp395olXhC+B0G7DI=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "05dcdb02ea657f81b13d99bd0ca36b09d25f4c43",
|
||||
"rev": "e0f24085a4a0da1c32adc308ec4c518ae886ff35",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -56,11 +56,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1736344531,
|
||||
"narHash": "sha256-8YVQ9ZbSfuUk2bUf2KRj60NRraLPKPS0Q4QFTbc+c2c=",
|
||||
"lastModified": 1761907660,
|
||||
"narHash": "sha256-kJ8lIZsiPOmbkJypG+B5sReDXSD1KGu2VEPNqhRa/ew=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "bffc22eb12172e6db3c5dde9e3e5628f8e3e7912",
|
||||
"rev": "2fb006b87f04c4d3bdf08cfdbc7fab9c13d94a15",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -81,11 +81,11 @@
|
||||
"rust-analyzer-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1736517563,
|
||||
"narHash": "sha256-YJ5ajpMsyXITc91ZfnI0Mdocd+tmCFkZ3BLozUkB44M=",
|
||||
"lastModified": 1762016333,
|
||||
"narHash": "sha256-PT8hXDYyeRjh9BGyLF/nZWm9TqRwP2EzeKuqUFH0M3w=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "4f35021ca9a8e7f9ed4344139b9eaf770a2e5725",
|
||||
"rev": "fca718c0f2074bdccf9a996bb37b0fcaff80dc97",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
55
flake.nix
@ -18,31 +18,32 @@
|
||||
}:
|
||||
flake-utils.lib.eachDefaultSystem (system: let
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
toolchain = with fenix.packages.${system};
|
||||
combine [
|
||||
minimal.rustc
|
||||
minimal.cargo
|
||||
targets.x86_64-pc-windows-gnu.latest.rust-std
|
||||
targets.x86_64-unknown-linux-musl.latest.rust-std
|
||||
];
|
||||
|
||||
toolchain =
|
||||
fenix.packages.${system}.fromToolchainFile
|
||||
{
|
||||
file = ./rust-toolchain.toml;
|
||||
# sha256 = nixpkgs.lib.fakeSha256;
|
||||
sha256 = "sha256-2eWc3xVTKqg5wKSHGwt1XoM/kUBC6y3MWfKg74Zn+fY=";
|
||||
};
|
||||
|
||||
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";
|
||||
});
|
||||
@ -75,21 +76,27 @@
|
||||
windows = windowsBuild;
|
||||
};
|
||||
|
||||
# Development shell with all necessary tools
|
||||
devShell = with nixpkgs.legacyPackages.${system};
|
||||
mkShell {
|
||||
buildInputs = with fenix.packages.${system}.stable; [
|
||||
rust-analyzer
|
||||
clippy
|
||||
rustfmt
|
||||
toolchain
|
||||
pkgs.just
|
||||
pkgs.nixd
|
||||
pkgs.alejandra
|
||||
];
|
||||
devShells.default = with nixpkgs.legacyPackages.${system};
|
||||
craneLib.devShell {
|
||||
packages =
|
||||
[
|
||||
toolchain
|
||||
pkgs.just
|
||||
pkgs.nixd
|
||||
pkgs.alejandra
|
||||
]
|
||||
# pkgs needed to play sound on Linux
|
||||
++ lib.optionals stdenv.isLinux [
|
||||
pkgs.pkg-config
|
||||
pkgs.pipewire
|
||||
pkgs.alsa-lib
|
||||
];
|
||||
|
||||
inherit (commonArgs) src;
|
||||
RUST_SRC_PATH = "${toolchain}/lib/rustlib/src/rust/library";
|
||||
|
||||
# Environment variables needed discover ALSA/PipeWire properly on Linux
|
||||
LD_LIBRARY_PATH = lib.optionalString stdenv.isLinux "${pkgs.alsa-lib}/lib:${pkgs.pipewire}/lib";
|
||||
ALSA_PLUGIN_DIR = lib.optionalString stdenv.isLinux "${pkgs.pipewire}/lib/alsa-lib";
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
103
justfile
@ -2,79 +2,174 @@
|
||||
|
||||
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
|
||||
[group('build')]
|
||||
build:
|
||||
cargo build
|
||||
|
||||
alias t := test
|
||||
|
||||
# run tests
|
||||
[group('test')]
|
||||
test:
|
||||
cargo test
|
||||
|
||||
alias f := format
|
||||
|
||||
# format files
|
||||
[group('misc')]
|
||||
format:
|
||||
just --fmt
|
||||
cargo fmt
|
||||
|
||||
alias l := lint
|
||||
|
||||
# lint
|
||||
[group('misc')]
|
||||
lint:
|
||||
cargo clippy --no-deps
|
||||
|
||||
alias r := run
|
||||
|
||||
# run app
|
||||
[group('dev')]
|
||||
run:
|
||||
cargo run
|
||||
|
||||
alias ra := run-args
|
||||
|
||||
# run app with arguments. It expects arguments as a string (e.g. "-c 5:00").
|
||||
[group('dev')]
|
||||
run-args args:
|
||||
cargo run -- {{ args }}
|
||||
|
||||
alias rs := run-sound
|
||||
|
||||
# run app while sound feature is enabled. It expects a path to a sound file.
|
||||
[group('dev')]
|
||||
run-sound path:
|
||||
cargo run --features sound -- --sound={{ path }}
|
||||
|
||||
alias rsa := run-sound-args
|
||||
|
||||
# run app while sound feature is enabled by adding a path to a sound file and other arguments as string (e.g. "-c 5:00").
|
||||
[group('dev')]
|
||||
run-sound-args path args:
|
||||
cargo run --features sound -- --sound={{ path }} {{ args }}
|
||||
|
||||
# demos
|
||||
|
||||
alias da := demo-all
|
||||
|
||||
# build all demos
|
||||
[group('demo')]
|
||||
demo-all:
|
||||
#!/usr/bin/env bash
|
||||
for tape in demo/*.tape; do
|
||||
echo "Building demo: $tape"
|
||||
vhs "$tape"
|
||||
done
|
||||
|
||||
alias dp := demo-pomodoro
|
||||
|
||||
# build demo: pomodoro
|
||||
[group('demo')]
|
||||
demo-pomodoro:
|
||||
vhs demo/pomodoro.tape
|
||||
|
||||
alias dt := demo-timer
|
||||
|
||||
# build demo: timer
|
||||
[group('demo')]
|
||||
demo-timer:
|
||||
vhs demo/timer.tape
|
||||
|
||||
alias dc := demo-countdown
|
||||
|
||||
# build demo: countdown
|
||||
[group('demo')]
|
||||
demo-countdown:
|
||||
vhs demo/countdown.tape
|
||||
|
||||
alias dcm := demo-countdown-met
|
||||
|
||||
# build demo: countdown + met
|
||||
[group('demo')]
|
||||
demo-countdown-met:
|
||||
vhs demo/countdown-met.tape
|
||||
|
||||
alias ds := demo-style
|
||||
|
||||
# build demo: styles
|
||||
[group('demo')]
|
||||
demo-style:
|
||||
vhs demo/style.tape
|
||||
|
||||
alias dd := demo-decis
|
||||
|
||||
# build demo: deciseconds
|
||||
[group('demo')]
|
||||
demo-decis:
|
||||
vhs demo/decis.tape
|
||||
|
||||
alias dm := demo-menu
|
||||
|
||||
# build demo: menu
|
||||
[group('demo')]
|
||||
demo-menu:
|
||||
vhs demo/menu.tape
|
||||
|
||||
alias dlt := demo-local-time
|
||||
|
||||
# build demo: local time
|
||||
[group('demo')]
|
||||
demo-local-time:
|
||||
vhs demo/local-time.tape
|
||||
|
||||
alias dltf := demo-local-time-footer
|
||||
|
||||
# build demo: local time (footer)
|
||||
[group('demo')]
|
||||
demo-local-time-footer:
|
||||
vhs demo/local-time-footer.tape
|
||||
|
||||
alias drc := demo-rocket-countdown
|
||||
|
||||
# build demo: rocket countdown
|
||||
[group('demo')]
|
||||
demo-rocket-countdown:
|
||||
vhs demo/met.tape
|
||||
|
||||
alias db := demo-blink
|
||||
|
||||
# build demo: blink animation
|
||||
[group('demo')]
|
||||
demo-blink:
|
||||
vhs demo/blink.tape
|
||||
|
||||
alias de := demo-event
|
||||
|
||||
# build demo: event
|
||||
[group('demo')]
|
||||
demo-event:
|
||||
vhs demo/event.tape
|
||||
|
||||
alias dcmx := demo-countdown-max
|
||||
|
||||
# build demo: timer-max
|
||||
[group('demo')]
|
||||
demo-countdown-max:
|
||||
vhs demo/countdown-max.tape
|
||||
|
||||
alias dtm := demo-timer-max
|
||||
|
||||
# build demo: timer-max
|
||||
[group('demo')]
|
||||
demo-timer-max:
|
||||
vhs demo/timer-max.tape
|
||||
|
||||
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.91.0"
|
||||
components = ["clippy", "rustfmt", "rust-src", "rust-analyzer"]
|
||||
targets = ["x86_64-pc-windows-gnu", "x86_64-unknown-linux-musl"]
|
||||
profile = "minimal"
|
||||
410
src/app.rs
@ -1,29 +1,38 @@
|
||||
use crate::{
|
||||
args::Args,
|
||||
common::{AppEditMode, AppTime, AppTimeFormat, Content, Style},
|
||||
common::{AppEditMode, AppTime, AppTimeFormat, ClockTypeId, Content, Style, Toggle},
|
||||
constants::TICK_VALUE_MS,
|
||||
events::{Event, EventHandler, Events},
|
||||
event::Event,
|
||||
events::{self, TuiEventHandler},
|
||||
storage::AppStorage,
|
||||
terminal::Terminal,
|
||||
widgets::{
|
||||
clock::{self, ClockState, ClockStateArgs},
|
||||
countdown::{Countdown, CountdownState},
|
||||
countdown::{Countdown, CountdownState, CountdownStateArgs},
|
||||
event::{EventState, EventStateArgs, EventWidget},
|
||||
footer::{Footer, FooterState},
|
||||
header::Header,
|
||||
local_time::{LocalTimeState, LocalTimeStateArgs, LocalTimeWidget},
|
||||
pomodoro::{Mode as PomodoroMode, PomodoroState, PomodoroStateArgs, PomodoroWidget},
|
||||
timer::{Timer, TimerState},
|
||||
},
|
||||
};
|
||||
|
||||
use crossterm::event::Event as CrosstermEvent;
|
||||
|
||||
#[cfg(feature = "sound")]
|
||||
use crate::sound::Sound;
|
||||
|
||||
use color_eyre::Result;
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
crossterm::event::{KeyCode, KeyEvent},
|
||||
layout::{Constraint, Layout, Rect},
|
||||
layout::{Constraint, Layout, Position, 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,26 +40,36 @@ 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,
|
||||
app_time_format: AppTimeFormat,
|
||||
countdown: CountdownState,
|
||||
timer: TimerState,
|
||||
pomodoro: PomodoroState,
|
||||
event: EventState,
|
||||
local_time: LocalTimeState,
|
||||
style: Style,
|
||||
with_decis: bool,
|
||||
footer: FooterState,
|
||||
cursor_position: Option<Position>,
|
||||
}
|
||||
|
||||
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,
|
||||
pub pomodoro_mode: PomodoroMode,
|
||||
pub pomodoro_round: u64,
|
||||
pub initial_value_work: Duration,
|
||||
pub current_value_work: Duration,
|
||||
pub initial_value_pause: Duration,
|
||||
@ -59,19 +78,51 @@ pub struct AppArgs {
|
||||
pub current_value_countdown: Duration,
|
||||
pub elapsed_value_countdown: Duration,
|
||||
pub current_value_timer: Duration,
|
||||
pub event: Event,
|
||||
pub app_tx: events::AppEventTx,
|
||||
pub sound_path: Option<PathBuf>,
|
||||
pub footer_toggle_app_time: Toggle,
|
||||
}
|
||||
|
||||
/// 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),
|
||||
// Check args to set a possible mode to start with.
|
||||
content: match args.mode {
|
||||
Some(mode) => mode,
|
||||
// check other args (especially durations)
|
||||
None => {
|
||||
if args.work.is_some() || args.pause.is_some() {
|
||||
Content::Pomodoro
|
||||
} else if args.countdown.is_some() {
|
||||
Content::Countdown
|
||||
} else if args.event.is_some() {
|
||||
Content::Event
|
||||
}
|
||||
// in other case just use latest stored state
|
||||
else {
|
||||
stg.content
|
||||
}
|
||||
}
|
||||
},
|
||||
style: args.style.unwrap_or(stg.style),
|
||||
pomodoro_mode: stg.pomodoro_mode,
|
||||
pomodoro_round: stg.pomodoro_count,
|
||||
initial_value_work: args.work.unwrap_or(stg.inital_value_work),
|
||||
// invalidate `current_value_work` if an initial value is set via args
|
||||
current_value_work: args.work.unwrap_or(stg.current_value_work),
|
||||
@ -80,17 +131,21 @@ impl From<(Args, AppStorage)> for AppArgs {
|
||||
current_value_pause: args.pause.unwrap_or(stg.current_value_pause),
|
||||
initial_value_countdown: args.countdown.unwrap_or(stg.inital_value_countdown),
|
||||
// invalidate `current_value_countdown` if an initial value is set via args
|
||||
current_value_countdown: args.countdown.unwrap_or(stg.current_value_countdown),
|
||||
elapsed_value_countdown: stg.elapsed_value_countdown,
|
||||
current_value_countdown: args.countdown.unwrap_or(stg.inital_value_countdown),
|
||||
elapsed_value_countdown: match args.countdown {
|
||||
// reset value if countdown is set by arguments
|
||||
Some(_) => Duration::ZERO,
|
||||
None => stg.elapsed_value_countdown,
|
||||
},
|
||||
current_value_timer: stg.current_value_timer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_app_time() -> AppTime {
|
||||
match OffsetDateTime::now_local() {
|
||||
Ok(t) => AppTime::Local(t),
|
||||
Err(_) => AppTime::Utc(OffsetDateTime::now_utc()),
|
||||
event: args.event.unwrap_or(stg.event),
|
||||
app_tx,
|
||||
#[cfg(feature = "sound")]
|
||||
sound_path: args.sound,
|
||||
#[cfg(not(feature = "sound"))]
|
||||
sound_path: None,
|
||||
footer_toggle_app_time: stg.footer_app_time,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -111,30 +166,44 @@ impl App {
|
||||
content,
|
||||
with_decis,
|
||||
pomodoro_mode,
|
||||
pomodoro_round,
|
||||
event,
|
||||
notification,
|
||||
blink,
|
||||
sound_path,
|
||||
app_tx,
|
||||
footer_toggle_app_time,
|
||||
} = args;
|
||||
let app_time = get_app_time();
|
||||
let app_time = AppTime::new();
|
||||
|
||||
Self {
|
||||
mode: Mode::Running,
|
||||
notification,
|
||||
blink,
|
||||
sound_path,
|
||||
content,
|
||||
app_time,
|
||||
app_time_format,
|
||||
style,
|
||||
with_decis,
|
||||
countdown: CountdownState::new(
|
||||
ClockState::<clock::Countdown>::new(ClockStateArgs {
|
||||
initial_value: initial_value_countdown,
|
||||
current_value: current_value_countdown,
|
||||
countdown: CountdownState::new(CountdownStateArgs {
|
||||
initial_value: initial_value_countdown,
|
||||
current_value: current_value_countdown,
|
||||
elapsed_value: elapsed_value_countdown,
|
||||
app_time,
|
||||
with_decis,
|
||||
app_tx: app_tx.clone(),
|
||||
}),
|
||||
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,
|
||||
}),
|
||||
elapsed_value_countdown,
|
||||
app_time,
|
||||
app_tx: Some(app_tx.clone()),
|
||||
})
|
||||
.with_name("Timer".to_owned()),
|
||||
),
|
||||
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,
|
||||
})),
|
||||
pomodoro: PomodoroState::new(PomodoroStateArgs {
|
||||
mode: pomodoro_mode,
|
||||
initial_value_work,
|
||||
@ -142,33 +211,181 @@ impl App {
|
||||
initial_value_pause,
|
||||
current_value_pause,
|
||||
with_decis,
|
||||
round: pomodoro_round,
|
||||
app_tx: app_tx.clone(),
|
||||
}),
|
||||
footer: FooterState::new(show_menu, app_time_format),
|
||||
local_time: LocalTimeState::new(LocalTimeStateArgs {
|
||||
app_time,
|
||||
app_time_format,
|
||||
}),
|
||||
event: EventState::new(EventStateArgs {
|
||||
app_time,
|
||||
event,
|
||||
with_decis,
|
||||
app_tx: app_tx.clone(),
|
||||
}),
|
||||
footer: FooterState::new(
|
||||
show_menu,
|
||||
if footer_toggle_app_time == Toggle::On {
|
||||
Some(app_time_format)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
),
|
||||
cursor_position: None,
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
self.countdown.set_app_time(self.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') => app.mode = Mode::Quit,
|
||||
KeyCode::Char('1') | KeyCode::Char('c') /* TODO: deprecated, remove it in next version */ => app.content = Content::Countdown,
|
||||
KeyCode::Char('2') | KeyCode::Char('t') /* TODO: deprecated, remove it in next version */ => app.content = Content::Timer,
|
||||
KeyCode::Char('3') | KeyCode::Char('p') /* TODO: deprecated, remove it in next version */ => app.content = Content::Pomodoro,
|
||||
KeyCode::Char('4') => app.content = Content::Event,
|
||||
// toogle app time format
|
||||
KeyCode::Char('0') | KeyCode::Char('l') /* TODO: deprecated, remove it in next version */ => app.content = Content::LocalTime,
|
||||
// switch `screens`
|
||||
KeyCode::Right => {
|
||||
app.content = app.content.next();
|
||||
}
|
||||
|
||||
// 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()),
|
||||
} {
|
||||
match unhandled {
|
||||
Event::Render | Event::Resize => {
|
||||
self.draw(&mut terminal)?;
|
||||
KeyCode::Left => {
|
||||
app.content = app.content.prev();
|
||||
}
|
||||
// toogle app time format
|
||||
KeyCode::Char(':') => {
|
||||
if app.content == Content::LocalTime {
|
||||
// For LocalTime content: just cycle through formats
|
||||
app.app_time_format = app.app_time_format.next();
|
||||
app.local_time.set_app_time_format(app.app_time_format);
|
||||
// Only update footer if it's currently showing time
|
||||
if app.footer.app_time_format().is_some() {
|
||||
app.footer.set_app_time_format(Some(app.app_time_format));
|
||||
}
|
||||
Event::Key(key) => self.handle_key_event(key),
|
||||
_ => {}
|
||||
} else {
|
||||
// For other content: allow footer to toggle between formats and None
|
||||
let new_format = match app.footer.app_time_format() {
|
||||
// footer is hidden -> show first format
|
||||
None => Some(AppTimeFormat::first()),
|
||||
Some(v) => {
|
||||
if v != &AppTimeFormat::last() {
|
||||
Some(v.next())
|
||||
} else {
|
||||
// reached last format -> hide footer time
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(format) = new_format {
|
||||
app.app_time_format = format;
|
||||
app.local_time.set_app_time_format(format);
|
||||
}
|
||||
app.footer.set_app_time_format(new_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);
|
||||
app.event.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 = AppTime::new();
|
||||
app.countdown.set_app_time(app.app_time);
|
||||
app.local_time.set_app_time(app.app_time);
|
||||
app.event.set_app_time(app.app_time);
|
||||
}
|
||||
|
||||
// Pipe events into subviews and handle only 'unhandled' events afterwards
|
||||
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()),
|
||||
Content::Event => app.event.update(event.clone()),
|
||||
Content::LocalTime => app.local_time.update(event.clone()),
|
||||
} {
|
||||
match unhandled {
|
||||
events::TuiEvent::Render
|
||||
| events::TuiEvent::Crossterm(crossterm::event::Event::Resize(_, _)) => {
|
||||
app.draw(terminal)?;
|
||||
}
|
||||
events::TuiEvent::Crossterm(CrosstermEvent::Key(key)) => {
|
||||
handle_key_event(app, key)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
#[allow(unused_variables)] // `app` is used by `--features sound` only
|
||||
// Closure to handle `AppEvent`'s
|
||||
let handle_app_events = |app: &mut Self, event: events::AppEvent| -> Result<()> {
|
||||
match event {
|
||||
events::AppEvent::ClockDone(type_id, name) => {
|
||||
debug!("AppEvent::ClockDone");
|
||||
|
||||
if app.notification == Toggle::On {
|
||||
let msg = match type_id {
|
||||
ClockTypeId::Timer => {
|
||||
format!("{name} stopped by reaching its maximum value.")
|
||||
}
|
||||
_ => format!("{type_id:?} {name} done!"),
|
||||
};
|
||||
// notification
|
||||
let result = notify_rust::Notification::new()
|
||||
.summary(&msg.to_uppercase())
|
||||
.show();
|
||||
if let Err(err) = result {
|
||||
error!("on_done {name} error: {err}");
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(feature = "sound")]
|
||||
if let Some(path) = app.sound_path.clone() {
|
||||
_ = Sound::new(path).and_then(|sound| sound.play()).or_else(
|
||||
|err| -> Result<()> {
|
||||
error!("Sound error: {:?}", err);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
events::AppEvent::SetCursor(position) => {
|
||||
app.cursor_position = position;
|
||||
}
|
||||
}
|
||||
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)
|
||||
@ -204,6 +421,14 @@ impl App {
|
||||
AppEditMode::None
|
||||
}
|
||||
}
|
||||
Content::Event => {
|
||||
if self.event.is_edit_mode() {
|
||||
AppEditMode::Event
|
||||
} else {
|
||||
AppEditMode::None
|
||||
}
|
||||
}
|
||||
Content::LocalTime => AppEditMode::None,
|
||||
}
|
||||
}
|
||||
|
||||
@ -212,6 +437,10 @@ impl App {
|
||||
Content::Countdown => self.countdown.is_running(),
|
||||
Content::Timer => self.timer.get_clock().is_running(),
|
||||
Content::Pomodoro => self.pomodoro.get_clock().is_running(),
|
||||
// Event clock runs forever
|
||||
Content::Event => true,
|
||||
// `LocalTime` does not use a `Clock`
|
||||
Content::LocalTime => false,
|
||||
}
|
||||
}
|
||||
|
||||
@ -220,39 +449,19 @@ impl App {
|
||||
Content::Countdown => Some(self.countdown.get_clock().get_percentage_done()),
|
||||
Content::Timer => None,
|
||||
Content::Pomodoro => Some(self.pomodoro.get_clock().get_percentage_done()),
|
||||
Content::Event => Some(self.event.get_percentage_done()),
|
||||
Content::LocalTime => None,
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
// Set cursor position if requested
|
||||
if let Some(position) = self.cursor_position {
|
||||
frame.set_cursor_position(position);
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@ -261,10 +470,13 @@ impl App {
|
||||
AppStorage {
|
||||
content: self.content,
|
||||
show_menu: self.footer.get_show_menu(),
|
||||
app_time_format: *self.footer.app_time_format(),
|
||||
notification: self.notification,
|
||||
blink: self.blink,
|
||||
app_time_format: self.app_time_format,
|
||||
style: self.style,
|
||||
with_decis: self.with_decis,
|
||||
pomodoro_mode: self.pomodoro.get_mode().clone(),
|
||||
pomodoro_count: self.pomodoro.get_round(),
|
||||
inital_value_work: Duration::from(*self.pomodoro.get_clock_work().get_initial_value()),
|
||||
current_value_work: Duration::from(*self.pomodoro.get_clock_work().get_current_value()),
|
||||
inital_value_pause: Duration::from(
|
||||
@ -279,6 +491,8 @@ impl App {
|
||||
),
|
||||
elapsed_value_countdown: Duration::from(*self.countdown.get_elapsed_value()),
|
||||
current_value_timer: Duration::from(*self.timer.get_clock().get_current_value()),
|
||||
event: self.event.get_event(),
|
||||
footer_app_time: self.footer.app_time_format().is_some().into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -289,13 +503,29 @@ 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,
|
||||
}
|
||||
.render(area, buf, &mut state.timer);
|
||||
}
|
||||
Content::Countdown => {
|
||||
Countdown { style: state.style }.render(area, buf, &mut state.countdown)
|
||||
Content::Countdown => Countdown {
|
||||
style: state.style,
|
||||
blink: state.blink == Toggle::On,
|
||||
}
|
||||
Content::Pomodoro => {
|
||||
PomodoroWidget { style: state.style }.render(area, buf, &mut state.pomodoro)
|
||||
.render(area, buf, &mut state.countdown),
|
||||
Content::Pomodoro => PomodoroWidget {
|
||||
style: state.style,
|
||||
blink: state.blink == Toggle::On,
|
||||
}
|
||||
.render(area, buf, &mut state.pomodoro),
|
||||
Content::Event => EventWidget {
|
||||
style: state.style,
|
||||
blink: state.blink == Toggle::On,
|
||||
}
|
||||
.render(area, buf, &mut state.event),
|
||||
Content::LocalTime => {
|
||||
LocalTimeWidget { style: state.style }.render(area, buf, &mut state.local_time);
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -307,7 +537,7 @@ impl StatefulWidget for AppWidget {
|
||||
let [v0, v1, v2] = Layout::vertical([
|
||||
Constraint::Length(1),
|
||||
Constraint::Percentage(100),
|
||||
Constraint::Length(if state.footer.get_show_menu() { 4 } else { 1 }),
|
||||
Constraint::Length(if state.footer.get_show_menu() { 5 } else { 1 }),
|
||||
])
|
||||
.areas(area);
|
||||
|
||||
|
||||
76
src/args.rs
@ -1,29 +1,43 @@
|
||||
use crate::{
|
||||
common::{Content, Style},
|
||||
common::{Content, Style, Toggle},
|
||||
duration,
|
||||
event::{Event, parse_event},
|
||||
};
|
||||
#[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 {
|
||||
#[arg(long, short, value_parser = duration::parse_duration,
|
||||
help = "Countdown time to start from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss'"
|
||||
#[arg(long, short, value_parser = duration::parse_long_duration,
|
||||
help = "Countdown time to start from. Formats: 'Yy Dd hh:mm:ss', 'Dd hh:mm:ss', 'Yy mm:ss', 'Dd mm:ss', 'Yy ss', 'Dd ss', 'hh:mm:ss', 'mm:ss', 'ss'. Examples: '1y 5d 10:30:00', '2d 4:00', '1d 10', '5:03'."
|
||||
)]
|
||||
pub countdown: Option<Duration>,
|
||||
|
||||
#[arg(long, short, value_parser = duration::parse_duration,
|
||||
help = "Work time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss'"
|
||||
help = "Work time to count down from. Formats: 'ss', 'mm:ss', 'hh:mm:ss'"
|
||||
)]
|
||||
pub work: Option<Duration>,
|
||||
|
||||
#[arg(long, short, value_parser = duration::parse_duration,
|
||||
help = "Pause time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss'"
|
||||
help = "Pause time to count down from. Formats: 'ss', 'mm:ss', 'hh:mm:ss'"
|
||||
)]
|
||||
pub pause: Option<Duration>,
|
||||
|
||||
#[arg(long, short = 'd', help = "Whether to show deciseconds or not.")]
|
||||
#[arg(
|
||||
long,
|
||||
short = 'e',
|
||||
value_parser = parse_event,
|
||||
help = "Event date time and title (optional). Format: 'YYYY-MM-DD HH:MM:SS' or 'time=YYYY-MM-DD HH:MM:SS[,title=...]'. Examples: '2025-10-10 14:30:00' or 'time=2025-10-10 14:30:00,title=My Event'."
|
||||
)]
|
||||
pub event: Option<Event>,
|
||||
|
||||
#[arg(long, short = 'd', help = "Show deciseconds.")]
|
||||
pub decis: bool,
|
||||
|
||||
#[arg(long, short = 'm', value_enum, help = "Mode to start with.")]
|
||||
@ -32,9 +46,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 menu.")]
|
||||
pub menu: bool,
|
||||
|
||||
#[arg(long, short = 'r', help = "Reset stored values to default.")]
|
||||
#[arg(long, short = 'r', help = "Reset stored values to defaults.")]
|
||||
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 for 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)
|
||||
}
|
||||
|
||||
192
src/common.rs
@ -1,8 +1,8 @@
|
||||
use clap::ValueEnum;
|
||||
use ratatui::symbols::shade;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::format_description;
|
||||
use time::OffsetDateTime;
|
||||
use strum::EnumString;
|
||||
use time::{OffsetDateTime, format_description};
|
||||
|
||||
#[derive(
|
||||
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Default, Serialize, Deserialize,
|
||||
@ -15,6 +15,39 @@ pub enum Content {
|
||||
Timer,
|
||||
#[value(name = "pomodoro", alias = "p")]
|
||||
Pomodoro,
|
||||
#[value(name = "event", alias = "e")]
|
||||
Event,
|
||||
#[value(name = "localtime", alias = "l")]
|
||||
LocalTime,
|
||||
}
|
||||
|
||||
impl Content {
|
||||
pub fn next(&self) -> Self {
|
||||
match self {
|
||||
Content::Countdown => Content::Timer,
|
||||
Content::Timer => Content::Pomodoro,
|
||||
Content::Pomodoro => Content::Event,
|
||||
Content::Event => Content::LocalTime,
|
||||
Content::LocalTime => Content::Countdown,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prev(&self) -> Self {
|
||||
match self {
|
||||
Content::Countdown => Content::LocalTime,
|
||||
Content::Timer => Content::Countdown,
|
||||
Content::Pomodoro => Content::Timer,
|
||||
Content::Event => Content::Pomodoro,
|
||||
Content::LocalTime => Content::Event,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ClockTypeId {
|
||||
Countdown,
|
||||
Timer,
|
||||
Event,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, ValueEnum, Default, Serialize, Deserialize)]
|
||||
@ -65,7 +98,7 @@ impl Style {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, EnumString, Serialize, Deserialize)]
|
||||
pub enum AppTimeFormat {
|
||||
/// `hh:mm:ss`
|
||||
#[default]
|
||||
@ -74,17 +107,22 @@ pub enum AppTimeFormat {
|
||||
HhMm,
|
||||
/// `hh:mm AM` (or PM)
|
||||
Hh12Mm,
|
||||
/// `` (empty)
|
||||
Hidden,
|
||||
}
|
||||
|
||||
impl AppTimeFormat {
|
||||
pub const fn first() -> Self {
|
||||
Self::HhMmSs
|
||||
}
|
||||
|
||||
pub const fn last() -> Self {
|
||||
Self::Hh12Mm
|
||||
}
|
||||
|
||||
pub fn next(&self) -> Self {
|
||||
match self {
|
||||
AppTimeFormat::HhMmSs => AppTimeFormat::HhMm,
|
||||
AppTimeFormat::HhMm => AppTimeFormat::Hh12Mm,
|
||||
AppTimeFormat::Hh12Mm => AppTimeFormat::Hidden,
|
||||
AppTimeFormat::Hidden => AppTimeFormat::HhMmSs,
|
||||
AppTimeFormat::Hh12Mm => AppTimeFormat::HhMmSs,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -105,26 +143,64 @@ impl From<AppTime> for OffsetDateTime {
|
||||
}
|
||||
|
||||
impl AppTime {
|
||||
#[allow(clippy::new_without_default)]
|
||||
pub fn new() -> Self {
|
||||
match OffsetDateTime::now_local() {
|
||||
Ok(t) => AppTime::Local(t),
|
||||
Err(_) => AppTime::Utc(OffsetDateTime::now_utc()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format(&self, app_format: &AppTimeFormat) -> String {
|
||||
let parse_str = match app_format {
|
||||
AppTimeFormat::HhMmSs => Some("[hour]:[minute]:[second]"),
|
||||
AppTimeFormat::HhMm => Some("[hour]:[minute]"),
|
||||
AppTimeFormat::Hh12Mm => Some("[hour repr:12 padding:none]:[minute] [period]"),
|
||||
AppTimeFormat::Hidden => None,
|
||||
AppTimeFormat::HhMmSs => "[hour]:[minute]:[second]",
|
||||
AppTimeFormat::HhMm => "[hour]:[minute]",
|
||||
AppTimeFormat::Hh12Mm => "[hour repr:12 padding:none]:[minute] [period]",
|
||||
};
|
||||
|
||||
if let Some(str) = parse_str {
|
||||
format_description::parse(str)
|
||||
.map_err(|_| "parse error")
|
||||
.and_then(|fd| {
|
||||
OffsetDateTime::from(*self)
|
||||
.format(&fd)
|
||||
.map_err(|_| "format error")
|
||||
})
|
||||
.unwrap_or_else(|e| e.to_string())
|
||||
} else {
|
||||
"".to_owned()
|
||||
}
|
||||
format_description::parse(parse_str)
|
||||
.map_err(|_| "parse error")
|
||||
.and_then(|fd| {
|
||||
OffsetDateTime::from(*self)
|
||||
.format(&fd)
|
||||
.map_err(|_| "format error")
|
||||
})
|
||||
.unwrap_or_else(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn format_date(&self) -> String {
|
||||
format_description::parse("[year]-[month]-[day]")
|
||||
.map_err(|_| "parse error")
|
||||
.and_then(|fd| {
|
||||
OffsetDateTime::from(*self)
|
||||
.format(&fd)
|
||||
.map_err(|_| "format error")
|
||||
})
|
||||
.unwrap_or_else(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn get_period(&self) -> String {
|
||||
format_description::parse("[period]")
|
||||
.map_err(|_| "parse error")
|
||||
.and_then(|fd| {
|
||||
OffsetDateTime::from(*self)
|
||||
.format(&fd)
|
||||
.map_err(|_| "format error")
|
||||
})
|
||||
.unwrap_or_else(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Converts `AppTime` into a `Duration` representing elapsed time since midnight (today).
|
||||
pub fn as_duration_of_today(&self) -> std::time::Duration {
|
||||
let dt = OffsetDateTime::from(*self);
|
||||
let time = dt.time();
|
||||
|
||||
let total_nanos = u64::from(time.hour()) * 3_600_000_000_000
|
||||
+ u64::from(time.minute()) * 60_000_000_000
|
||||
+ u64::from(time.second()) * 1_000_000_000
|
||||
+ u64::from(time.nanosecond());
|
||||
|
||||
std::time::Duration::from_nanos(total_nanos)
|
||||
}
|
||||
}
|
||||
|
||||
@ -133,6 +209,25 @@ pub enum AppEditMode {
|
||||
None,
|
||||
Clock,
|
||||
Time,
|
||||
Event,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub enum Toggle {
|
||||
#[value(name = "on")]
|
||||
On,
|
||||
#[default]
|
||||
#[value(name = "off")]
|
||||
Off,
|
||||
}
|
||||
|
||||
impl From<bool> for Toggle {
|
||||
fn from(value: bool) -> Self {
|
||||
match value {
|
||||
true => Toggle::On,
|
||||
false => Toggle::Off,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@ -181,12 +276,49 @@ mod tests {
|
||||
"6:06 PM",
|
||||
"local"
|
||||
);
|
||||
// hidden
|
||||
assert_eq!(AppTime::Utc(dt).format(&AppTimeFormat::Hidden), "", "utc");
|
||||
assert_eq!(
|
||||
AppTime::Local(dt).format(&AppTimeFormat::Hidden),
|
||||
"",
|
||||
"local"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_content_next() {
|
||||
let start = Content::Countdown;
|
||||
let mut current = start;
|
||||
|
||||
// Cycle through: Countdown -> Timer -> Pomodoro -> Event -> LocalTime -> Countdown
|
||||
current = current.next();
|
||||
assert_eq!(current, Content::Timer);
|
||||
|
||||
current = current.next();
|
||||
assert_eq!(current, Content::Pomodoro);
|
||||
|
||||
current = current.next();
|
||||
assert_eq!(current, Content::Event);
|
||||
|
||||
current = current.next();
|
||||
assert_eq!(current, Content::LocalTime);
|
||||
|
||||
current = current.next();
|
||||
assert_eq!(current, start, "Should cycle back to start");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_content_prev() {
|
||||
let start = Content::Countdown;
|
||||
let mut current = start;
|
||||
|
||||
// Cycle backwards: Countdown -> LocalTime -> Event -> Pomodoro -> Timer -> Countdown
|
||||
current = current.prev();
|
||||
assert_eq!(current, Content::LocalTime);
|
||||
|
||||
current = current.prev();
|
||||
assert_eq!(current, Content::Event);
|
||||
|
||||
current = current.prev();
|
||||
assert_eq!(current, Content::Pomodoro);
|
||||
|
||||
current = current.prev();
|
||||
assert_eq!(current, Content::Timer);
|
||||
|
||||
current = current.prev();
|
||||
assert_eq!(current, start, "Should cycle back to start");
|
||||
}
|
||||
}
|
||||
|
||||
@ -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)?;
|
||||
|
||||
|
||||
753
src/duration.rs
@ -1,14 +1,11 @@
|
||||
use color_eyre::{
|
||||
eyre::{ensure, eyre},
|
||||
Report,
|
||||
eyre::{ensure, eyre},
|
||||
};
|
||||
use std::cmp::min;
|
||||
use std::fmt;
|
||||
use std::time::Duration;
|
||||
|
||||
pub const ONE_DECI_SECOND: Duration = Duration::from_millis(100);
|
||||
pub const ONE_SECOND: Duration = Duration::from_secs(1);
|
||||
pub const ONE_MINUTE: Duration = Duration::from_secs(SECS_PER_MINUTE);
|
||||
pub const ONE_HOUR: Duration = Duration::from_secs(MINS_PER_HOUR * SECS_PER_MINUTE);
|
||||
use time::OffsetDateTime;
|
||||
|
||||
// unstable
|
||||
// https://doc.rust-lang.org/src/core/time.rs.html#32
|
||||
@ -20,9 +17,219 @@ 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);
|
||||
pub const ONE_DECI_SECOND: Duration = Duration::from_millis(100);
|
||||
pub const ONE_SECOND: Duration = Duration::from_secs(1);
|
||||
pub const ONE_MINUTE: Duration = Duration::from_secs(SECS_PER_MINUTE);
|
||||
pub const ONE_HOUR: Duration = Duration::from_secs(MINS_PER_HOUR * SECS_PER_MINUTE);
|
||||
pub const ONE_DAY: Duration = Duration::from_secs(HOURS_PER_DAY * MINS_PER_HOUR * SECS_PER_MINUTE);
|
||||
pub const ONE_YEAR: Duration =
|
||||
Duration::from_secs(DAYS_PER_YEAR * HOURS_PER_DAY * MINS_PER_HOUR * SECS_PER_MINUTE);
|
||||
|
||||
// Days per year
|
||||
// "There are 365 days in a year in a common year of the Gregorian calendar and 366 days in a leap year.
|
||||
// Leap years occur every four years. The average number of days in a year is 365.2425 days."
|
||||
// ^ https://www.math.net/days-in-a-year
|
||||
const DAYS_PER_YEAR: u64 = 365; // ignore leap year of 366 days
|
||||
|
||||
// max. 9999y 364d 23:59:59.9 (10k years - 1 decisecond)
|
||||
pub const MAX_DURATION: Duration = ONE_YEAR
|
||||
.saturating_mul(10000)
|
||||
.saturating_sub(ONE_DECI_SECOND);
|
||||
|
||||
/// Trait for duration types that can be displayed in clock widgets.
|
||||
///
|
||||
/// This trait abstracts over different duration calculation strategies:
|
||||
/// - `DurationEx`: Uses fixed 365-day years (fast, simple)
|
||||
/// - `CalendarDuration`: Uses actual calendar dates (accounts for leap years)
|
||||
pub trait ClockDuration {
|
||||
/// Total years
|
||||
fn years(&self) -> u64;
|
||||
|
||||
/// Total days
|
||||
fn days(&self) -> u64;
|
||||
|
||||
/// Days within the current year (0-364 or 0-365 for leap years)
|
||||
fn days_mod(&self) -> u64;
|
||||
|
||||
/// Total hours
|
||||
fn hours(&self) -> u64;
|
||||
|
||||
/// Hours within the current day (0-23)
|
||||
fn hours_mod(&self) -> u64;
|
||||
|
||||
/// Hours as 12-hour clock (1-12)
|
||||
fn hours_mod_12(&self) -> u64;
|
||||
|
||||
/// Total minutes
|
||||
fn minutes(&self) -> u64;
|
||||
|
||||
/// Minutes within the current hour (0-59)
|
||||
fn minutes_mod(&self) -> u64;
|
||||
|
||||
/// Total seconds
|
||||
fn seconds(&self) -> u64;
|
||||
|
||||
/// Seconds within the current minute (0-59)
|
||||
fn seconds_mod(&self) -> u64;
|
||||
|
||||
/// Deciseconds (tenths of a second, 0-9)
|
||||
fn decis(&self) -> u64;
|
||||
|
||||
/// Total milliseconds
|
||||
fn millis(&self) -> u128;
|
||||
}
|
||||
|
||||
/// Calendar-aware duration that accounts for leap years.
|
||||
///
|
||||
/// Unlike `DurationEx` which uses fixed 365-day years, this calculates
|
||||
/// years and days based on actual calendar dates, properly handling leap years.
|
||||
///
|
||||
/// All calculations are performed on-demand from the stored dates.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CalendarDuration {
|
||||
earlier: OffsetDateTime,
|
||||
later: OffsetDateTime,
|
||||
direction: CalendarDurationDirection,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Clone, Copy)]
|
||||
pub enum CalendarDurationDirection {
|
||||
Since,
|
||||
Until,
|
||||
}
|
||||
|
||||
impl CalendarDuration {
|
||||
/// Create a new CalendarDuration by given two `OffsetDateTime`.
|
||||
///
|
||||
/// The order of arguments matters:
|
||||
/// First: `start_time` - `OffsetDateTime` to start from
|
||||
/// Second: `end_time` - `OffsetDateTime` for expected end
|
||||
pub fn from_start_end_times(start_time: OffsetDateTime, end_time: OffsetDateTime) -> Self {
|
||||
// To avoid negative values by calculating differences of `start` and `end` times,
|
||||
// we might switch those values internally by storing it as `earlier` and `later` values
|
||||
// It simplifies all calculations in `ClockDuration` trait later.
|
||||
// And `direction` will still help to still get original `start` and `end` times later.
|
||||
if start_time <= end_time {
|
||||
Self {
|
||||
earlier: start_time,
|
||||
later: end_time,
|
||||
direction: CalendarDurationDirection::Since,
|
||||
}
|
||||
} else {
|
||||
Self {
|
||||
earlier: end_time,
|
||||
later: start_time,
|
||||
direction: CalendarDurationDirection::Until,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn direction(&self) -> CalendarDurationDirection {
|
||||
self.direction
|
||||
}
|
||||
|
||||
pub fn is_since(&self) -> bool {
|
||||
self.direction == CalendarDurationDirection::Since
|
||||
}
|
||||
|
||||
pub fn start_time(&self) -> &OffsetDateTime {
|
||||
match self.direction {
|
||||
CalendarDurationDirection::Since => &self.earlier,
|
||||
CalendarDurationDirection::Until => &self.later,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn end_time(&self) -> &OffsetDateTime {
|
||||
match self.direction {
|
||||
CalendarDurationDirection::Since => &self.later,
|
||||
CalendarDurationDirection::Until => &self.earlier,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CalendarDuration> for Duration {
|
||||
fn from(cal_duration: CalendarDuration) -> Self {
|
||||
let diff = cal_duration.later - cal_duration.earlier;
|
||||
Duration::from_millis(diff.whole_milliseconds().max(0) as u64)
|
||||
}
|
||||
}
|
||||
|
||||
impl ClockDuration for CalendarDuration {
|
||||
fn years(&self) -> u64 {
|
||||
let mut years = (self.later.year() - self.earlier.year()) as i64;
|
||||
|
||||
// Check if we've completed a full year by comparing month/day/time
|
||||
let intermediate = self
|
||||
.earlier
|
||||
.replace_year(self.later.year())
|
||||
.unwrap_or(self.earlier);
|
||||
|
||||
if intermediate > self.later {
|
||||
years -= 1;
|
||||
}
|
||||
|
||||
years.max(0) as u64
|
||||
}
|
||||
|
||||
fn days_mod(&self) -> u64 {
|
||||
let year_count = self.years();
|
||||
|
||||
// Calculate intermediate date after adding complete years
|
||||
let target_year = self.earlier.year() + year_count as i32;
|
||||
let intermediate = self
|
||||
.earlier
|
||||
.replace_year(target_year)
|
||||
.unwrap_or(self.earlier);
|
||||
|
||||
let remaining = self.later - intermediate;
|
||||
remaining.whole_days().max(0) as u64
|
||||
}
|
||||
|
||||
fn days(&self) -> u64 {
|
||||
(self.later - self.earlier).whole_days().max(0) as u64
|
||||
}
|
||||
|
||||
fn hours_mod(&self) -> u64 {
|
||||
let total_hours = (self.later - self.earlier).whole_hours();
|
||||
(total_hours % 24).max(0) as u64
|
||||
}
|
||||
|
||||
fn hours(&self) -> u64 {
|
||||
(self.later - self.earlier).whole_hours().max(0) as u64
|
||||
}
|
||||
|
||||
fn hours_mod_12(&self) -> u64 {
|
||||
let hours = self.hours_mod();
|
||||
(hours + 11) % 12 + 1
|
||||
}
|
||||
|
||||
fn minutes_mod(&self) -> u64 {
|
||||
let total_minutes = (self.later - self.earlier).whole_minutes();
|
||||
(total_minutes % 60).max(0) as u64
|
||||
}
|
||||
|
||||
fn minutes(&self) -> u64 {
|
||||
(self.later - self.earlier).whole_minutes().max(0) as u64
|
||||
}
|
||||
|
||||
fn seconds_mod(&self) -> u64 {
|
||||
let total_seconds = (self.later - self.earlier).whole_seconds();
|
||||
(total_seconds % 60).max(0) as u64
|
||||
}
|
||||
|
||||
fn seconds(&self) -> u64 {
|
||||
(self.later - self.earlier).whole_seconds().max(0) as u64
|
||||
}
|
||||
|
||||
fn decis(&self) -> u64 {
|
||||
let total_millis = (self.later - self.earlier).whole_milliseconds();
|
||||
((total_millis % 1000) / 100).max(0) as u64
|
||||
}
|
||||
|
||||
fn millis(&self) -> u128 {
|
||||
(self.later - self.earlier).whole_milliseconds().max(0) as u128
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialOrd)]
|
||||
pub struct DurationEx {
|
||||
@ -47,40 +254,60 @@ impl From<DurationEx> for Duration {
|
||||
}
|
||||
}
|
||||
|
||||
impl DurationEx {
|
||||
pub fn seconds(&self) -> u64 {
|
||||
self.inner.as_secs()
|
||||
impl ClockDuration for DurationEx {
|
||||
fn years(&self) -> u64 {
|
||||
self.days() / DAYS_PER_YEAR
|
||||
}
|
||||
|
||||
pub fn seconds_mod(&self) -> u64 {
|
||||
self.seconds() % SECS_PER_MINUTE
|
||||
fn days(&self) -> u64 {
|
||||
self.hours() / HOURS_PER_DAY
|
||||
}
|
||||
|
||||
pub fn hours(&self) -> u64 {
|
||||
fn days_mod(&self) -> u64 {
|
||||
self.days() % DAYS_PER_YEAR
|
||||
}
|
||||
|
||||
fn hours(&self) -> u64 {
|
||||
self.seconds() / (SECS_PER_MINUTE * MINS_PER_HOUR)
|
||||
}
|
||||
|
||||
pub fn hours_mod(&self) -> u64 {
|
||||
fn hours_mod(&self) -> u64 {
|
||||
self.hours() % HOURS_PER_DAY
|
||||
}
|
||||
|
||||
pub fn minutes(&self) -> u64 {
|
||||
fn hours_mod_12(&self) -> u64 {
|
||||
// 0 => 12,
|
||||
// 1..=12 => hours,
|
||||
// 13..=23 => hours - 12,
|
||||
(self.hours_mod() + 11) % 12 + 1
|
||||
}
|
||||
|
||||
fn minutes(&self) -> u64 {
|
||||
self.seconds() / MINS_PER_HOUR
|
||||
}
|
||||
|
||||
pub fn minutes_mod(&self) -> u64 {
|
||||
fn minutes_mod(&self) -> u64 {
|
||||
self.minutes() % SECS_PER_MINUTE
|
||||
}
|
||||
|
||||
// deciseconds
|
||||
pub fn decis(&self) -> u64 {
|
||||
(self.inner.subsec_millis() / 100) as u64
|
||||
}
|
||||
// milliseconds
|
||||
pub fn millis(&self) -> u128 {
|
||||
self.inner.as_millis()
|
||||
fn seconds(&self) -> u64 {
|
||||
self.inner.as_secs()
|
||||
}
|
||||
|
||||
fn seconds_mod(&self) -> u64 {
|
||||
self.seconds() % SECS_PER_MINUTE
|
||||
}
|
||||
|
||||
fn decis(&self) -> u64 {
|
||||
(self.inner.subsec_millis() / 100) as u64
|
||||
}
|
||||
|
||||
fn millis(&self) -> u128 {
|
||||
self.inner.as_millis()
|
||||
}
|
||||
}
|
||||
|
||||
impl DurationEx {
|
||||
pub fn saturating_add(&self, ex: DurationEx) -> Self {
|
||||
let inner = self.inner.saturating_add(ex.inner);
|
||||
Self { inner }
|
||||
@ -98,7 +325,27 @@ impl DurationEx {
|
||||
|
||||
impl fmt::Display for DurationEx {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.hours() >= 10 {
|
||||
use ClockDuration as _; // Import trait methods
|
||||
if self.years() >= 1 {
|
||||
write!(
|
||||
f,
|
||||
"{}y {}d {:02}:{:02}:{:02}",
|
||||
self.years(),
|
||||
self.days_mod(),
|
||||
self.hours_mod(),
|
||||
self.minutes_mod(),
|
||||
self.seconds_mod(),
|
||||
)
|
||||
} else if self.hours() >= HOURS_PER_DAY {
|
||||
write!(
|
||||
f,
|
||||
"{}d {:02}:{:02}:{:02}",
|
||||
self.days_mod(),
|
||||
self.hours_mod(),
|
||||
self.minutes_mod(),
|
||||
self.seconds_mod(),
|
||||
)
|
||||
} else if self.hours() >= 10 {
|
||||
write!(
|
||||
f,
|
||||
"{:02}:{:02}:{:02}",
|
||||
@ -126,73 +373,166 @@ impl fmt::Display for DurationEx {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse seconds (must be < 60)
|
||||
fn parse_seconds(s: &str) -> Result<u8, Report> {
|
||||
let secs = s.parse::<u8>().map_err(|_| eyre!("Invalid seconds"))?;
|
||||
ensure!(secs < 60, "Seconds must be less than 60.");
|
||||
Ok(secs)
|
||||
}
|
||||
|
||||
/// Parse minutes (must be < 60)
|
||||
fn parse_minutes(m: &str) -> Result<u8, Report> {
|
||||
let mins = m.parse::<u8>().map_err(|_| eyre!("Invalid minutes"))?;
|
||||
ensure!(mins < 60, "Minutes must be less than 60.");
|
||||
Ok(mins)
|
||||
}
|
||||
|
||||
/// Parse hours
|
||||
fn parse_hours(h: &str) -> Result<u8, Report> {
|
||||
let hours = h.parse::<u8>().map_err(|_| eyre!("Invalid hours"))?;
|
||||
Ok(hours)
|
||||
}
|
||||
|
||||
/// Parses `Duration` from `hh:mm:ss`, `mm:ss` or `ss`
|
||||
pub fn parse_duration(arg: &str) -> Result<Duration, Report> {
|
||||
let parts: Vec<&str> = arg.split(':').rev().collect();
|
||||
let parts: Vec<&str> = arg.split(':').collect();
|
||||
|
||||
let parse_seconds = |s: &str| -> Result<u64, Report> {
|
||||
let secs = s.parse::<u64>().map_err(|_| eyre!("Invalid seconds"))?;
|
||||
ensure!(secs < 60, "Seconds must be less than 60.");
|
||||
Ok(secs)
|
||||
};
|
||||
|
||||
let parse_minutes = |m: &str| -> Result<u64, Report> {
|
||||
let mins = m.parse::<u64>().map_err(|_| eyre!("Invalid minutes"))?;
|
||||
ensure!(mins < 60, "Minutes must be less than 60.");
|
||||
Ok(mins)
|
||||
};
|
||||
|
||||
let parse_hours = |h: &str| -> Result<u64, Report> {
|
||||
let hours = h.parse::<u64>().map_err(|_| eyre!("Invalid hours"))?;
|
||||
ensure!(hours < 100, "Hours must be less than 100.");
|
||||
Ok(hours)
|
||||
};
|
||||
|
||||
let seconds = match parts.as_slice() {
|
||||
[ss] => parse_seconds(ss)?,
|
||||
[ss, mm] => {
|
||||
let (hours, minutes, seconds) = match parts.as_slice() {
|
||||
[ss] => {
|
||||
// Single part: seconds only
|
||||
let s = parse_seconds(ss)?;
|
||||
let m = parse_minutes(mm)?;
|
||||
m * 60 + s
|
||||
(0u64, 0u64, s as u64)
|
||||
}
|
||||
[ss, mm, hh] => {
|
||||
let s = parse_seconds(ss)?;
|
||||
[mm, ss] => {
|
||||
// Two parts: MM:SS
|
||||
let m = parse_minutes(mm)?;
|
||||
let s = parse_seconds(ss)?;
|
||||
(0u64, m as u64, s as u64)
|
||||
}
|
||||
[hh, mm, ss] => {
|
||||
// Three parts: HH:MM:SS
|
||||
let h = parse_hours(hh)?;
|
||||
h * 60 * 60 + m * 60 + s
|
||||
let m = parse_minutes(mm)?;
|
||||
let s = parse_seconds(ss)?;
|
||||
(h as u64, m as u64, s as u64)
|
||||
}
|
||||
_ => {
|
||||
return Err(eyre!(
|
||||
"Invalid time format. Use 'ss', 'mm:ss', or 'hh:mm:ss'"
|
||||
));
|
||||
}
|
||||
_ => return Err(eyre!("Invalid time format. Use 'ss', mm:ss, or hh:mm:ss")),
|
||||
};
|
||||
|
||||
Ok(Duration::from_secs(seconds))
|
||||
let total_seconds = hours * 3600 + minutes * 60 + seconds;
|
||||
Ok(Duration::from_secs(total_seconds))
|
||||
}
|
||||
|
||||
/// Similar to `parse_duration`, but it parses `years` and `days` in addition
|
||||
/// Formats: `Yy Dd`, `Yy` or `Dd` in any combination to other time formats
|
||||
/// Examples: `10y 3d 12:10:03`, `2d 10:00`, `101y 33`, `5:30`
|
||||
pub fn parse_long_duration(arg: &str) -> Result<Duration, Report> {
|
||||
let arg = arg.trim();
|
||||
|
||||
// parts are separated by whitespaces:
|
||||
// 3 parts: years, days, time
|
||||
let parts: Vec<&str> = arg.split_whitespace().collect();
|
||||
ensure!(parts.len() <= 3, "Invalid format. Too many parts.");
|
||||
|
||||
let mut total_duration = Duration::ZERO;
|
||||
let mut time_part: Option<&str> = None;
|
||||
|
||||
for part in parts {
|
||||
// years
|
||||
if let Some(years_str) = part.strip_suffix('y') {
|
||||
let years = years_str
|
||||
.parse::<u64>()
|
||||
.map_err(|_| eyre!("Invalid years value: '{}'", years_str))?;
|
||||
total_duration = total_duration.saturating_add(ONE_YEAR.saturating_mul(years as u32));
|
||||
}
|
||||
// days
|
||||
else if let Some(days_str) = part.strip_suffix('d') {
|
||||
let days = days_str
|
||||
.parse::<u64>()
|
||||
.map_err(|_| eyre!("Invalid days value: '{}'", days_str))?;
|
||||
total_duration = total_duration.saturating_add(ONE_DAY.saturating_mul(days as u32));
|
||||
}
|
||||
// possible time format
|
||||
else {
|
||||
time_part = Some(part);
|
||||
}
|
||||
}
|
||||
|
||||
// time format
|
||||
if let Some(time) = time_part {
|
||||
let time_duration = parse_duration(time)?;
|
||||
total_duration = total_duration.saturating_add(time_duration);
|
||||
}
|
||||
|
||||
// avoid overflow
|
||||
total_duration = min(MAX_DURATION, total_duration);
|
||||
|
||||
Ok(total_duration)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use super::ClockDuration;
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
const MINUTE_IN_SECONDS: u64 = ONE_MINUTE.as_secs();
|
||||
const HOUR_IN_SECONDS: u64 = ONE_HOUR.as_secs();
|
||||
const DAY_IN_SECONDS: u64 = ONE_DAY.as_secs();
|
||||
const YEAR_IN_SECONDS: u64 = ONE_YEAR.as_secs();
|
||||
|
||||
#[test]
|
||||
fn test_fmt() {
|
||||
// 1y Dd hh:mm:ss (single year)
|
||||
let ex: DurationEx =
|
||||
Duration::from_secs(YEAR_IN_SECONDS + 10 * DAY_IN_SECONDS + 36001).into();
|
||||
assert_eq!(format!("{ex}"), "1y 10d 10:00:01");
|
||||
// 5y Dd hh:mm:ss (multiple years)
|
||||
let ex: DurationEx = Duration::from_secs(
|
||||
5 * YEAR_IN_SECONDS + 100 * DAY_IN_SECONDS + 10 * HOUR_IN_SECONDS + 1,
|
||||
)
|
||||
.into();
|
||||
assert_eq!(format!("{ex}"), "5y 100d 10:00:01");
|
||||
// 150y Dd hh:mm:ss (more than 100 years)
|
||||
let ex: DurationEx = Duration::from_secs(
|
||||
150 * YEAR_IN_SECONDS + 200 * DAY_IN_SECONDS + 10 * HOUR_IN_SECONDS + 1,
|
||||
)
|
||||
.into();
|
||||
assert_eq!(format!("{ex}"), "150y 200d 10:00:01");
|
||||
// 366d hh:mm:ss (days more than a year)
|
||||
let ex: DurationEx =
|
||||
Duration::from_secs(366 * DAY_IN_SECONDS + 10 * HOUR_IN_SECONDS + 1).into();
|
||||
assert_eq!(format!("{ex}"), "1y 1d 10:00:01");
|
||||
// 1d hh:mm:ss (single day)
|
||||
let ex: DurationEx = Duration::from_secs(DAY_IN_SECONDS + 10 * HOUR_IN_SECONDS + 1).into();
|
||||
assert_eq!(format!("{ex}"), "1d 10:00:01");
|
||||
// 2d hh:mm:ss (multiple days)
|
||||
let ex: DurationEx =
|
||||
Duration::from_secs(2 * DAY_IN_SECONDS + 10 * HOUR_IN_SECONDS + 1).into();
|
||||
assert_eq!(format!("{ex}"), "2d 10:00:01");
|
||||
// hh:mm:ss
|
||||
let ex: DurationEx = Duration::from_secs(36001).into();
|
||||
assert_eq!(format!("{}", ex), "10:00:01");
|
||||
let ex: DurationEx = Duration::from_secs(10 * HOUR_IN_SECONDS + 1).into();
|
||||
assert_eq!(format!("{ex}"), "10:00:01");
|
||||
// h:mm:ss
|
||||
let ex: DurationEx = Duration::from_secs(3601).into();
|
||||
assert_eq!(format!("{}", ex), "1:00:01");
|
||||
let ex: DurationEx = Duration::from_secs(HOUR_IN_SECONDS + 1).into();
|
||||
assert_eq!(format!("{ex}"), "1:00:01");
|
||||
// mm:ss
|
||||
let ex: DurationEx = Duration::from_secs(71).into();
|
||||
assert_eq!(format!("{}", ex), "1:11");
|
||||
let ex: DurationEx = Duration::from_secs(MINUTE_IN_SECONDS + 11).into();
|
||||
assert_eq!(format!("{ex}"), "1:11");
|
||||
// m:ss
|
||||
let ex: DurationEx = Duration::from_secs(61).into();
|
||||
assert_eq!(format!("{}", ex), "1:01");
|
||||
let ex: DurationEx = Duration::from_secs(MINUTE_IN_SECONDS + 1).into();
|
||||
assert_eq!(format!("{ex}"), "1:01");
|
||||
// ss
|
||||
let ex: DurationEx = Duration::from_secs(11).into();
|
||||
assert_eq!(format!("{}", ex), "11");
|
||||
assert_eq!(format!("{ex}"), "11");
|
||||
// s
|
||||
let ex: DurationEx = Duration::from_secs(1).into();
|
||||
assert_eq!(format!("{}", ex), "1");
|
||||
assert_eq!(format!("{ex}"), "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -200,7 +540,7 @@ mod tests {
|
||||
let ex: DurationEx = Duration::from_secs(10).into();
|
||||
let ex2: DurationEx = Duration::from_secs(1).into();
|
||||
let ex3 = ex.saturating_sub(ex2);
|
||||
assert_eq!(format!("{}", ex3), "9");
|
||||
assert_eq!(format!("{ex3}"), "9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -208,7 +548,35 @@ mod tests {
|
||||
let ex: DurationEx = Duration::from_secs(10).into();
|
||||
let ex2: DurationEx = Duration::from_secs(1).into();
|
||||
let ex3 = ex.saturating_add(ex2);
|
||||
assert_eq!(format!("{}", ex3), "11");
|
||||
assert_eq!(format!("{ex3}"), "11");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hours_mod_12() {
|
||||
// 24 -> 12
|
||||
let ex: DurationEx = ONE_HOUR.saturating_mul(24).into();
|
||||
let result = ex.hours_mod_12();
|
||||
assert_eq!(result, 12);
|
||||
|
||||
// 12 -> 12
|
||||
let ex: DurationEx = ONE_HOUR.saturating_mul(12).into();
|
||||
let result = ex.hours_mod_12();
|
||||
assert_eq!(result, 12);
|
||||
|
||||
// 0 -> 12
|
||||
let ex: DurationEx = ONE_SECOND.into();
|
||||
let result = ex.hours_mod_12();
|
||||
assert_eq!(result, 12);
|
||||
|
||||
// 13 -> 1
|
||||
let ex: DurationEx = ONE_HOUR.saturating_mul(13).into();
|
||||
let result = ex.hours_mod_12();
|
||||
assert_eq!(result, 1);
|
||||
|
||||
// 1 -> 1
|
||||
let ex: DurationEx = ONE_HOUR.saturating_mul(1).into();
|
||||
let result = ex.hours_mod_12();
|
||||
assert_eq!(result, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -228,8 +596,257 @@ mod tests {
|
||||
// errors
|
||||
assert!(parse_duration("1:60").is_err()); // invalid seconds
|
||||
assert!(parse_duration("60:00").is_err()); // invalid minutes
|
||||
assert!(parse_duration("100:00:00").is_err()); // invalid hours
|
||||
assert!(parse_duration("abc").is_err()); // invalid input
|
||||
assert!(parse_duration("01:02:03:04").is_err()); // too many parts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_long_duration() {
|
||||
// `Yy`
|
||||
assert_eq!(
|
||||
parse_long_duration("10y").unwrap(),
|
||||
Duration::from_secs(10 * YEAR_IN_SECONDS)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_long_duration("101y").unwrap(),
|
||||
Duration::from_secs(101 * YEAR_IN_SECONDS)
|
||||
);
|
||||
|
||||
// `Dd`
|
||||
assert_eq!(
|
||||
parse_long_duration("2d").unwrap(),
|
||||
Duration::from_secs(2 * DAY_IN_SECONDS)
|
||||
);
|
||||
|
||||
// `Yy Dd`
|
||||
assert_eq!(
|
||||
parse_long_duration("10y 3d").unwrap(),
|
||||
Duration::from_secs(10 * YEAR_IN_SECONDS + 3 * DAY_IN_SECONDS)
|
||||
);
|
||||
|
||||
// `Yy Dd hh:mm:ss`
|
||||
assert_eq!(
|
||||
parse_long_duration("10y 3d 12:10:03").unwrap(),
|
||||
Duration::from_secs(
|
||||
10 * YEAR_IN_SECONDS
|
||||
+ 3 * DAY_IN_SECONDS
|
||||
+ 12 * HOUR_IN_SECONDS
|
||||
+ 10 * MINUTE_IN_SECONDS
|
||||
+ 3
|
||||
)
|
||||
);
|
||||
|
||||
// `Dd hh:mm`
|
||||
assert_eq!(
|
||||
parse_long_duration("2d 10:00").unwrap(),
|
||||
Duration::from_secs(2 * DAY_IN_SECONDS + 10 * 60)
|
||||
);
|
||||
|
||||
// `Yy ss`
|
||||
assert_eq!(
|
||||
parse_long_duration("101y 33").unwrap(),
|
||||
Duration::from_secs(101 * YEAR_IN_SECONDS + 33)
|
||||
);
|
||||
|
||||
// time formats (backward compatibility with `parse_duration`)
|
||||
assert_eq!(
|
||||
parse_long_duration("5:30").unwrap(),
|
||||
Duration::from_secs(5 * MINUTE_IN_SECONDS + 30)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_long_duration("01:30:45").unwrap(),
|
||||
Duration::from_secs(HOUR_IN_SECONDS + 30 * MINUTE_IN_SECONDS + 45)
|
||||
);
|
||||
assert_eq!(parse_long_duration("42").unwrap(), Duration::from_secs(42));
|
||||
|
||||
// `Dd ss`
|
||||
assert_eq!(
|
||||
parse_long_duration("5d 30").unwrap(),
|
||||
Duration::from_secs(5 * DAY_IN_SECONDS + 30)
|
||||
);
|
||||
|
||||
// `Yy hh:mm:ss`
|
||||
assert_eq!(
|
||||
parse_long_duration("1y 01:30:00").unwrap(),
|
||||
Duration::from_secs(YEAR_IN_SECONDS + HOUR_IN_SECONDS + 30 * MINUTE_IN_SECONDS)
|
||||
);
|
||||
|
||||
// Whitespace handling
|
||||
assert_eq!(
|
||||
parse_long_duration(" 2d 10:00 ").unwrap(),
|
||||
Duration::from_secs(2 * DAY_IN_SECONDS + 10 * MINUTE_IN_SECONDS)
|
||||
);
|
||||
|
||||
// MAX_DURATION clamping
|
||||
assert_eq!(parse_long_duration("10000y").unwrap(), MAX_DURATION);
|
||||
assert_eq!(
|
||||
parse_long_duration("9999y 364d 23:59:59").unwrap(),
|
||||
Duration::from_secs(
|
||||
9999 * YEAR_IN_SECONDS
|
||||
+ 364 * DAY_IN_SECONDS
|
||||
+ 23 * HOUR_IN_SECONDS
|
||||
+ 59 * MINUTE_IN_SECONDS
|
||||
+ 59
|
||||
)
|
||||
);
|
||||
|
||||
// errors
|
||||
assert!(parse_long_duration("10x").is_err()); // invalid unit
|
||||
assert!(parse_long_duration("abc").is_err()); // invalid input
|
||||
assert!(parse_long_duration("10y 60:00").is_err()); // invalid minutes in time part
|
||||
assert!(parse_long_duration("5d 1:60").is_err()); // invalid seconds in time part
|
||||
assert!(parse_long_duration("1y 2d 3d 4:00").is_err()); // too many parts (4 parts)
|
||||
assert!(parse_long_duration("1y 2d 3h 4m 5s").is_err()); // too many parts (5 parts)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_leap_year() {
|
||||
use time::macros::datetime;
|
||||
|
||||
// 2024 is a leap year (366 days)
|
||||
let start = datetime!(2024-01-01 00:00:00 UTC);
|
||||
let end = datetime!(2025-01-01 00:00:00 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(start, end);
|
||||
|
||||
assert_eq!(cal_dur.years(), 1, "Should be exactly 1 year");
|
||||
assert_eq!(cal_dur.days_mod(), 0, "Should be 0 remaining days");
|
||||
assert_eq!(cal_dur.days(), 366, "2024 has 366 days (leap year)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_non_leap_year() {
|
||||
use time::macros::datetime;
|
||||
|
||||
// 2023 is not a leap year (365 days)
|
||||
let start = datetime!(2023-01-01 00:00:00 UTC);
|
||||
let end = datetime!(2024-01-01 00:00:00 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(start, end);
|
||||
|
||||
assert_eq!(cal_dur.years(), 1, "Should be exactly 1 year");
|
||||
assert_eq!(cal_dur.days_mod(), 0, "Should be 0 remaining days");
|
||||
assert_eq!(cal_dur.days(), 365, "2023 has 365 days (non-leap year)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_partial_year_with_leap_day() {
|
||||
use time::macros::datetime;
|
||||
|
||||
// Span including Feb 29, 2024
|
||||
let start = datetime!(2024-02-01 00:00:00 UTC);
|
||||
let end = datetime!(2024-03-15 00:00:00 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(start, end);
|
||||
|
||||
assert_eq!(cal_dur.years(), 0, "Should be 0 years");
|
||||
// Feb 2024 has 29 days, so: 29 days (rest of Feb) + 15 days (March) = 44 days
|
||||
assert_eq!(
|
||||
cal_dur.days(),
|
||||
43,
|
||||
"Should be 43 days (29 in Feb + 14 partial March)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_partial_year_without_leap_day() {
|
||||
use time::macros::datetime;
|
||||
|
||||
// Same dates but in 2023 (non-leap year)
|
||||
let start = datetime!(2023-02-01 00:00:00 UTC);
|
||||
let end = datetime!(2023-03-15 00:00:00 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(start, end);
|
||||
|
||||
assert_eq!(cal_dur.years(), 0, "Should be 0 years");
|
||||
// Feb 2023 has 28 days, so: 28 days (rest of Feb) + 15 days (March) = 43 days
|
||||
assert_eq!(
|
||||
cal_dur.days(),
|
||||
42,
|
||||
"Should be 42 days (28 in Feb + 14 partial March)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_multiple_years_spanning_leap_years() {
|
||||
use time::macros::datetime;
|
||||
|
||||
// From 2023 (non-leap) through 2024 (leap) to 2025
|
||||
let start = datetime!(2023-03-01 10:00:00 UTC);
|
||||
let end = datetime!(2025-03-01 10:00:00 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(start, end);
|
||||
|
||||
assert_eq!(cal_dur.years(), 2, "Should be exactly 2 years");
|
||||
assert_eq!(cal_dur.days_mod(), 0, "Should be 0 remaining days");
|
||||
// Total days: 365 (2023 partial + 2024 partial) + 366 (full 2024 year conceptually included)
|
||||
// Actually: From 2023-03-01 to 2025-03-01 = 365 + 366 = 731 days
|
||||
assert_eq!(cal_dur.days(), 731, "Should be 731 total days");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_year_boundary() {
|
||||
use time::macros::datetime;
|
||||
|
||||
// Test incomplete year - just before year boundary
|
||||
let start = datetime!(2024-01-01 00:00:00 UTC);
|
||||
let end = datetime!(2024-12-31 23:59:59 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(start, end);
|
||||
|
||||
assert_eq!(cal_dur.years(), 0, "Should be 0 years (not complete)");
|
||||
assert_eq!(cal_dur.days(), 365, "Should be 365 days");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_hours_minutes_seconds() {
|
||||
use time::macros::datetime;
|
||||
|
||||
let start = datetime!(2024-01-01 10:30:45 UTC);
|
||||
let end = datetime!(2024-01-02 14:25:50 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(start, end);
|
||||
|
||||
assert_eq!(cal_dur.years(), 0);
|
||||
assert_eq!(cal_dur.days(), 1);
|
||||
assert_eq!(cal_dur.hours_mod(), 3, "Should be 3 hours past midnight");
|
||||
assert_eq!(cal_dur.minutes_mod(), 55, "Should be 55 minutes");
|
||||
assert_eq!(cal_dur.seconds_mod(), 5, "Should be 5 seconds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_reversed_dates() {
|
||||
use time::macros::datetime;
|
||||
|
||||
// CalendarDuration::between should handle reversed order
|
||||
let later = datetime!(2025-01-01 00:00:00 UTC);
|
||||
let earlier = datetime!(2024-01-01 00:00:00 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(later, earlier);
|
||||
|
||||
assert_eq!(cal_dur.years(), 1, "Should still calculate 1 year");
|
||||
assert_eq!(cal_dur.days(), 366, "Should still be 366 days");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_same_date() {
|
||||
use time::macros::datetime;
|
||||
|
||||
let date = datetime!(2024-06-15 12:00:00 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(date, date);
|
||||
|
||||
assert_eq!(cal_dur.years(), 0);
|
||||
assert_eq!(cal_dur.days(), 0);
|
||||
assert_eq!(cal_dur.hours(), 0);
|
||||
assert_eq!(cal_dur.minutes(), 0);
|
||||
assert_eq!(cal_dur.seconds(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calendar_duration_deciseconds() {
|
||||
use time::macros::datetime;
|
||||
|
||||
let start = datetime!(2024-01-01 00:00:00.000 UTC);
|
||||
let end = datetime!(2024-01-01 00:00:00.750 UTC);
|
||||
let cal_dur = CalendarDuration::from_start_end_times(start, end);
|
||||
|
||||
assert_eq!(
|
||||
cal_dur.decis(),
|
||||
7,
|
||||
"Should be 7 deciseconds (750ms = 7.5 decis, truncated to 7)"
|
||||
);
|
||||
assert_eq!(cal_dur.millis(), 750, "Should be 750 milliseconds");
|
||||
}
|
||||
}
|
||||
|
||||
169
src/event.rs
Normal file
@ -0,0 +1,169 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::macros::{datetime, format_description};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Event {
|
||||
pub date_time: time::PrimitiveDateTime,
|
||||
pub title: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Event {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
// Mario Bros. "...entered mass production in Japan on June 21" 1983
|
||||
// https://en.wikipedia.org/wiki/Mario_Bros.#Release
|
||||
date_time: datetime!(1983-06-21 00:00),
|
||||
title: Some("Release date of Mario Bros. in Japan".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses an `Event`
|
||||
/// Supports two formats:
|
||||
/// (1) "YYYY-MM-DD HH:MM:SS"
|
||||
/// (2) "time=YYYY-MM-DD HH:MM:SS,title=my event"
|
||||
pub fn parse_event(s: &str) -> Result<Event, String> {
|
||||
let s = s.trim();
|
||||
|
||||
// check + parse (2)
|
||||
if s.contains('=') {
|
||||
parse_event_key_value(s)
|
||||
} else {
|
||||
// parse (1)
|
||||
parse_event_date_time(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses an `Event` based on "YYYY-MM-DD HH:MM:SS" format
|
||||
fn parse_event_date_time(s: &str) -> Result<Event, String> {
|
||||
let time = time::PrimitiveDateTime::parse(
|
||||
s,
|
||||
format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"),
|
||||
)
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"Failed to parse event date_time '{}': {}. Expected format: 'YYYY-MM-DD HH:MM:SS'",
|
||||
s, e
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(Event {
|
||||
date_time: time,
|
||||
title: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses an `Event` defined by a `key=value` pair.
|
||||
/// Valid keys: `time` and `title`.
|
||||
/// Format: "time=YYYY-MM-DD HH:MM:SS,title=my event"
|
||||
fn parse_event_key_value(s: &str) -> Result<Event, String> {
|
||||
let mut time_str = None;
|
||||
let mut title_str = None;
|
||||
|
||||
// k/v pairs are splitted by commas
|
||||
for part in s.split(',') {
|
||||
let part = part.trim();
|
||||
if let Some((key, value)) = part.split_once('=') {
|
||||
match key.trim() {
|
||||
"time" => time_str = Some(value.trim()),
|
||||
"title" => title_str = Some(value.trim()),
|
||||
unknown => {
|
||||
return Err(format!(
|
||||
"Unknown key '{}'. Valid keys: 'time', 'title'",
|
||||
unknown
|
||||
));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err(format!(
|
||||
"Invalid key=value pair: '{}'. Expected format: 'key=value'",
|
||||
part
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let time_str = time_str.ok_or(
|
||||
"Missing required 'time' field. Expected format: 'time=YYYY-MM-DD HH:MM:SS[,title=...]'",
|
||||
)?;
|
||||
let time = time::PrimitiveDateTime::parse(
|
||||
time_str,
|
||||
format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"),
|
||||
)
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"Failed to parse event time '{}': {}. Expected format: 'YYYY-MM-DD HH:MM:SS'",
|
||||
time_str, e
|
||||
)
|
||||
})?;
|
||||
|
||||
let title = title_str.filter(|t| !t.is_empty()).map(|t| t.to_string());
|
||||
|
||||
Ok(Event {
|
||||
date_time: time,
|
||||
title,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use time::macros::datetime;
|
||||
|
||||
#[test]
|
||||
fn test_parse_event() {
|
||||
// Simple format: time only
|
||||
let result = parse_event("2024-01-01 14:30:00").unwrap();
|
||||
assert_eq!(result.date_time, datetime!(2024-01-01 14:30:00));
|
||||
assert_eq!(result.title, None);
|
||||
|
||||
// Simple format: with leading/trailing whitespace (outer trim works)
|
||||
let result = parse_event(" 2025-12-25 12:30:00 ").unwrap();
|
||||
assert_eq!(result.date_time, datetime!(2025-12-25 12:30:00));
|
||||
assert_eq!(result.title, None);
|
||||
|
||||
// Key=value format: time only
|
||||
let result = parse_event("time=2025-10-10 14:30:00").unwrap();
|
||||
assert_eq!(result.date_time, datetime!(2025-10-10 14:30:00));
|
||||
assert_eq!(result.title, None);
|
||||
|
||||
// Key=value format: time and title
|
||||
let result = parse_event("time=2025-10-10 14:30:00,title=Team Meeting").unwrap();
|
||||
assert_eq!(result.date_time, datetime!(2025-10-10 14:30:00));
|
||||
assert_eq!(result.title, Some("Team Meeting".to_string()));
|
||||
|
||||
// Key=value format: order independent
|
||||
let result = parse_event("title=Stand-up,time=2025-10-10 09:00:00").unwrap();
|
||||
assert_eq!(result.date_time, datetime!(2025-10-10 09:00:00));
|
||||
assert_eq!(result.title, Some("Stand-up".to_string()));
|
||||
|
||||
// Key=value format: title with spaces and special chars
|
||||
let result =
|
||||
parse_event("time=2025-10-10 14:30:00,title=Sprint Planning: Q1 Review").unwrap();
|
||||
assert_eq!(result.date_time, datetime!(2025-10-10 14:30:00));
|
||||
assert_eq!(result.title, Some("Sprint Planning: Q1 Review".to_string()));
|
||||
|
||||
// Key=value format: empty title treated as None
|
||||
let result = parse_event("time=2025-10-10 14:30:00,title=").unwrap();
|
||||
assert_eq!(result.date_time, datetime!(2025-10-10 14:30:00));
|
||||
assert_eq!(result.title, None);
|
||||
|
||||
// Key=value format: whitespace handling
|
||||
let result = parse_event(" time = 2025-10-10 14:30:00 , title = My Event ").unwrap();
|
||||
assert_eq!(result.date_time, datetime!(2025-10-10 14:30:00));
|
||||
assert_eq!(result.title, Some("My Event".to_string()));
|
||||
|
||||
// Error cases: invalid time format
|
||||
assert!(parse_event("2025-13-01 00:00:00").is_err());
|
||||
assert!(parse_event("invalid").is_err());
|
||||
assert!(parse_event("2025/10/10 14:30:00").is_err());
|
||||
|
||||
// Error cases: missing time in key=value format
|
||||
assert!(parse_event("title=My Event").is_err());
|
||||
|
||||
// Error cases: unknown key
|
||||
assert!(parse_event("time=2025-10-10 14:30:00,foo=bar").is_err());
|
||||
|
||||
// Error cases: malformed key=value pair
|
||||
assert!(parse_event("time=2025-10-10 14:30:00,notapair").is_err());
|
||||
}
|
||||
}
|
||||
@ -1,9 +1,12 @@
|
||||
use crossterm::event::{Event as CrosstermEvent, EventStream, KeyEvent, KeyEventKind};
|
||||
use crossterm::event::{Event as CrosstermEvent, EventStream, KeyEventKind};
|
||||
use futures::{Stream, StreamExt};
|
||||
use ratatui::layout::Position;
|
||||
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,17 +15,27 @@ enum StreamKey {
|
||||
Render,
|
||||
Crossterm,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Event {
|
||||
pub enum TuiEvent {
|
||||
Error,
|
||||
Tick,
|
||||
Render,
|
||||
Key(KeyEvent),
|
||||
Resize,
|
||||
Crossterm(CrosstermEvent),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum AppEvent {
|
||||
ClockDone(ClockTypeId, String),
|
||||
SetCursor(Option<Position>),
|
||||
}
|
||||
|
||||
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,48 +46,62 @@ 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()
|
||||
// we are not interested in all events
|
||||
.filter_map(|event| async move {
|
||||
match event {
|
||||
Ok(CrosstermEvent::Key(key)) if key.kind == KeyEventKind::Press => {
|
||||
Some(Event::Key(key))
|
||||
}
|
||||
Ok(CrosstermEvent::Resize(_, _)) => Some(Event::Resize),
|
||||
Err(_) => Some(Event::Error),
|
||||
_ => None,
|
||||
.filter_map(|result| async move {
|
||||
match result {
|
||||
// filter `KeyEventKind::Press` out to ignore all the other `CrosstermEvent::Key` events
|
||||
Ok(CrosstermEvent::Key(key)) => (key.kind == KeyEventKind::Press)
|
||||
.then_some(TuiEvent::Crossterm(CrosstermEvent::Key(key))),
|
||||
Ok(other) => Some(TuiEvent::Crossterm(other)),
|
||||
Err(_) => Some(TuiEvent::Error),
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
49
src/main.rs
@ -2,8 +2,8 @@ mod app;
|
||||
mod common;
|
||||
mod config;
|
||||
mod constants;
|
||||
mod event;
|
||||
mod events;
|
||||
#[cfg(debug_assertions)]
|
||||
mod logging;
|
||||
|
||||
mod args;
|
||||
@ -13,24 +13,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 +68,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
@ -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,21 +1,38 @@
|
||||
use crate::{
|
||||
common::{AppTimeFormat, Content, Style},
|
||||
common::{AppTimeFormat, Content, Style, Toggle},
|
||||
event::Event,
|
||||
widgets::pomodoro::Mode as PomodoroMode,
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
fn deserialize_app_time_format<'de, D>(deserializer: D) -> Result<AppTimeFormat, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
match s.as_str() {
|
||||
// Hidden is deprecated - use `default` value instead
|
||||
"Hidden" => Ok(AppTimeFormat::default()),
|
||||
_ => s.parse().map_err(serde::de::Error::custom),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct AppStorage {
|
||||
pub content: Content,
|
||||
pub show_menu: bool,
|
||||
pub notification: Toggle,
|
||||
pub blink: Toggle,
|
||||
#[serde(deserialize_with = "deserialize_app_time_format")]
|
||||
pub app_time_format: AppTimeFormat,
|
||||
pub style: Style,
|
||||
pub with_decis: bool,
|
||||
pub pomodoro_mode: PomodoroMode,
|
||||
pub pomodoro_count: u64,
|
||||
// pomodoro -> work
|
||||
pub inital_value_work: Duration,
|
||||
pub current_value_work: Duration,
|
||||
@ -28,6 +45,10 @@ pub struct AppStorage {
|
||||
pub elapsed_value_countdown: Duration,
|
||||
// timer
|
||||
pub current_value_timer: Duration,
|
||||
// event
|
||||
pub event: Event,
|
||||
// footer
|
||||
pub footer_app_time: Toggle,
|
||||
}
|
||||
|
||||
impl Default for AppStorage {
|
||||
@ -38,10 +59,13 @@ 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,
|
||||
pomodoro_mode: PomodoroMode::Work,
|
||||
pomodoro_count: 1,
|
||||
// pomodoro -> work
|
||||
inital_value_work: DEFAULT_WORK,
|
||||
current_value_work: DEFAULT_WORK,
|
||||
@ -54,6 +78,10 @@ impl Default for AppStorage {
|
||||
elapsed_value_countdown: Duration::ZERO,
|
||||
// timer
|
||||
current_value_timer: Duration::ZERO,
|
||||
// event
|
||||
event: Event::default(),
|
||||
// footer
|
||||
footer_app_time: Toggle::Off,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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);
|
||||
}));
|
||||
}
|
||||
|
||||
@ -6,8 +6,10 @@ pub mod clock_elements_test;
|
||||
pub mod clock_test;
|
||||
pub mod countdown;
|
||||
pub mod edit_time;
|
||||
pub mod event;
|
||||
pub mod footer;
|
||||
pub mod header;
|
||||
pub mod local_time;
|
||||
pub mod pomodoro;
|
||||
pub mod progressbar;
|
||||
pub mod timer;
|
||||
|
||||
1640
src/widgets/clock.rs
@ -7,9 +7,13 @@ use ratatui::{
|
||||
pub const DIGIT_SIZE: usize = 5;
|
||||
pub const DIGIT_WIDTH: u16 = DIGIT_SIZE as u16;
|
||||
pub const DIGIT_HEIGHT: u16 = DIGIT_SIZE as u16 + 1 /* border height */;
|
||||
pub const TWO_DIGITS_WIDTH: u16 = DIGIT_WIDTH + DIGIT_SPACE_WIDTH + DIGIT_WIDTH; // digit-space-digit
|
||||
pub const THREE_DIGITS_WIDTH: u16 = TWO_DIGITS_WIDTH + DIGIT_SPACE_WIDTH + DIGIT_WIDTH; // digit-space-digit-space-digit
|
||||
pub const FOUR_DIGITS_WIDTH: u16 = THREE_DIGITS_WIDTH + DIGIT_SPACE_WIDTH + DIGIT_WIDTH; // digit-space-digit-space-digit-space-digit
|
||||
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
|
||||
pub const DIGIT_LABEL_WIDTH: u16 = 3; // label (single char) incl. padding left + padding right
|
||||
|
||||
#[rustfmt::skip]
|
||||
const DIGIT_0: [u8; DIGIT_SIZE * DIGIT_SIZE] = [
|
||||
|
||||
@ -1,34 +1,314 @@
|
||||
use crate::{
|
||||
duration::{ONE_DECI_SECOND, ONE_HOUR, ONE_MINUTE, ONE_SECOND},
|
||||
common::ClockTypeId,
|
||||
duration::{
|
||||
DurationEx, MAX_DURATION, ONE_DAY, ONE_DECI_SECOND, ONE_HOUR, ONE_MINUTE, ONE_SECOND,
|
||||
ONE_YEAR,
|
||||
},
|
||||
widgets::clock::*,
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
fn default_args() -> ClockStateArgs {
|
||||
ClockStateArgs {
|
||||
initial_value: ONE_HOUR,
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_toggle_edit() {
|
||||
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_get_format_seconds() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_SECOND * 5,
|
||||
current_value: ONE_SECOND * 5,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
// S
|
||||
assert_eq!(c.get_format(), &Format::S);
|
||||
// Ss
|
||||
c.set_current_value(Duration::from_secs(15).into());
|
||||
assert_eq!(c.get_format(), &Format::Ss);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_format_minutes() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_MINUTE,
|
||||
current_value: ONE_MINUTE,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
// MSs
|
||||
assert_eq!(c.get_format(), &Format::MSs);
|
||||
// MmSs
|
||||
c.set_current_value((ONE_MINUTE * 11).into()); // 10+ minutes
|
||||
assert_eq!(c.get_format(), &Format::MmSs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_format_hours() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_HOUR,
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
// 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());
|
||||
// HMmSS
|
||||
assert_eq!(c.get_format(), &Format::HMmSs);
|
||||
// HhMmSs
|
||||
c.set_current_value((10 * ONE_HOUR).into());
|
||||
assert_eq!(c.get_format(), &Format::HhMmSs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_by_duration_boundaries() {
|
||||
// S
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(ONE_SECOND * 9).into()),
|
||||
Format::S
|
||||
);
|
||||
// Ss
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(10 * ONE_SECOND).into()),
|
||||
Format::Ss
|
||||
);
|
||||
// Ss
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(59 * ONE_SECOND).into()),
|
||||
Format::Ss
|
||||
);
|
||||
// MSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&ONE_MINUTE.into()),
|
||||
Format::MSs
|
||||
);
|
||||
// HhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(ONE_DAY.saturating_sub(ONE_SECOND)).into()),
|
||||
Format::HhMmSs
|
||||
);
|
||||
// DHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&ONE_DAY.into()),
|
||||
Format::DHhMmSs
|
||||
);
|
||||
// DHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&((10 * ONE_DAY).saturating_sub(ONE_SECOND)).into()),
|
||||
Format::DHhMmSs
|
||||
);
|
||||
// DdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(10 * ONE_DAY).into()),
|
||||
Format::DdHhMmSs
|
||||
);
|
||||
// DdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&((100 * ONE_DAY).saturating_sub(ONE_SECOND)).into()),
|
||||
Format::DdHhMmSs
|
||||
);
|
||||
// DddHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(100 * ONE_DAY).into()),
|
||||
Format::DddHhMmSs
|
||||
);
|
||||
// DddHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(ONE_YEAR.saturating_sub(ONE_SECOND).into())),
|
||||
Format::DddHhMmSs
|
||||
);
|
||||
// YDHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&ONE_YEAR.into()),
|
||||
Format::YDHhMmSs
|
||||
);
|
||||
// YDdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(
|
||||
&(ONE_YEAR + (100 * ONE_DAY).saturating_sub(ONE_SECOND)).into()
|
||||
),
|
||||
Format::YDdHhMmSs
|
||||
);
|
||||
// YDddHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(ONE_YEAR + 100 * ONE_DAY).into()),
|
||||
Format::YDddHhMmSs
|
||||
);
|
||||
// YDddHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&((10 * ONE_YEAR).saturating_sub(ONE_SECOND)).into()),
|
||||
Format::YDddHhMmSs
|
||||
);
|
||||
// YyDHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(10 * ONE_YEAR).into()),
|
||||
Format::YyDHhMmSs
|
||||
);
|
||||
// YyDdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(10 * ONE_YEAR + 10 * ONE_DAY).into()),
|
||||
Format::YyDdHhMmSs
|
||||
);
|
||||
// YyDdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(
|
||||
&(10 * ONE_YEAR + (100 * ONE_DAY).saturating_sub(ONE_SECOND)).into()
|
||||
),
|
||||
Format::YyDdHhMmSs
|
||||
);
|
||||
// YyDddHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(10 * ONE_YEAR + 100 * ONE_DAY).into()),
|
||||
Format::YyDddHhMmSs
|
||||
);
|
||||
// YyDddHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&((100 * ONE_YEAR).saturating_sub(ONE_SECOND)).into()),
|
||||
Format::YyDddHhMmSs
|
||||
);
|
||||
// YyyDHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(100 * ONE_YEAR).into()),
|
||||
Format::YyyDHhMmSs
|
||||
);
|
||||
// YyyDdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(100 * ONE_YEAR + 10 * ONE_DAY).into()),
|
||||
Format::YyyDdHhMmSs
|
||||
);
|
||||
// YyyDdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(
|
||||
&(100 * ONE_YEAR + (100 * ONE_DAY).saturating_sub(ONE_SECOND)).into()
|
||||
),
|
||||
Format::YyyDdHhMmSs
|
||||
);
|
||||
// YyyDddHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(100 * ONE_YEAR + 100 * ONE_DAY).into()),
|
||||
Format::YyyDddHhMmSs
|
||||
);
|
||||
|
||||
// YyyyDdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(1000 * ONE_YEAR + 10 * ONE_DAY).into()),
|
||||
Format::YyyyDdHhMmSs
|
||||
);
|
||||
// YyyyDdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(
|
||||
&(1000 * ONE_YEAR + (100 * ONE_DAY).saturating_sub(ONE_SECOND)).into()
|
||||
),
|
||||
Format::YyyyDdHhMmSs
|
||||
);
|
||||
// YyyyDddHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(1000 * ONE_YEAR + 100 * ONE_DAY).into()),
|
||||
Format::YyyyDddHhMmSs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_by_duration_days() {
|
||||
// DHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&ONE_DAY.into()),
|
||||
Format::DHhMmSs
|
||||
);
|
||||
// DdHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(10 * ONE_DAY).into()),
|
||||
Format::DdHhMmSs
|
||||
);
|
||||
// DddHhMmSs
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(101 * ONE_DAY).into()),
|
||||
Format::DddHhMmSs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_by_duration_years() {
|
||||
// YDHhMmSs (1 year, 0 days)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&ONE_YEAR.into()),
|
||||
Format::YDHhMmSs
|
||||
);
|
||||
|
||||
// YDHhMmSs (1 year, 1 day)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(ONE_YEAR + ONE_DAY).into()),
|
||||
Format::YDHhMmSs
|
||||
);
|
||||
|
||||
// YDdHhMmSs (1 year, 10 days)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(ONE_YEAR + 10 * ONE_DAY).into()),
|
||||
Format::YDdHhMmSs
|
||||
);
|
||||
|
||||
// YDddHhMmSs (1 year, 100 days)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(ONE_YEAR + 100 * ONE_DAY).into()),
|
||||
Format::YDddHhMmSs
|
||||
);
|
||||
|
||||
// YyDHhMmSs (10 years)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(10 * ONE_YEAR).into()),
|
||||
Format::YyDHhMmSs
|
||||
);
|
||||
|
||||
// YyDdHhMmSs (10 years, 10 days)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(10 * ONE_YEAR + 10 * ONE_DAY).into()),
|
||||
Format::YyDdHhMmSs
|
||||
);
|
||||
|
||||
// YyDddHhMmSs (10 years, 100 days)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(10 * ONE_YEAR + 100 * ONE_DAY).into()),
|
||||
Format::YyDddHhMmSs
|
||||
);
|
||||
|
||||
// YyyDHhMmSs (100 years)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(100 * ONE_YEAR).into()),
|
||||
Format::YyyDHhMmSs
|
||||
);
|
||||
|
||||
// YyyDdHhMmSs (100 years, 10 days)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(100 * ONE_YEAR + 10 * ONE_DAY).into()),
|
||||
Format::YyyDdHhMmSs
|
||||
);
|
||||
|
||||
// YyyDddHhMmSs (100 years, 100 days)
|
||||
assert_eq!(
|
||||
format_by_duration::<DurationEx>(&(100 * ONE_YEAR + 100 * ONE_DAY).into()),
|
||||
Format::YyyDddHhMmSs
|
||||
);
|
||||
}
|
||||
|
||||
#[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 +323,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,12 +337,285 @@ 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();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_up_stays_in_seconds() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_MINUTE - ONE_SECOND,
|
||||
current_value: ONE_MINUTE - ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_up();
|
||||
// Edit mode should stay on seconds
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_up_stays_in_minutes() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_HOUR - ONE_SECOND,
|
||||
current_value: ONE_HOUR - ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
c.edit_up();
|
||||
// Edit mode should stay on minutes
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_up_stays_in_hours() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_DAY - ONE_SECOND,
|
||||
current_value: ONE_DAY - ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_up();
|
||||
// Edit mode should stay on hours
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_up_stays_in_days() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_YEAR - ONE_DAY,
|
||||
current_value: ONE_YEAR - ONE_DAY,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
c.edit_next(); // Hours
|
||||
c.edit_next(); // Days
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_up();
|
||||
// Edit mode should stay on days
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_up_overflow_protection() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: MAX_DURATION.saturating_sub(ONE_SECOND),
|
||||
current_value: MAX_DURATION.saturating_sub(ONE_SECOND),
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
c.edit_next(); // Hours
|
||||
c.edit_next(); // Days
|
||||
c.edit_next(); // Years
|
||||
c.edit_up(); // +1y
|
||||
assert!(Duration::from(*c.get_current_value()) <= MAX_DURATION);
|
||||
c.edit_prev(); // Days
|
||||
c.edit_up(); // +1d
|
||||
assert!(Duration::from(*c.get_current_value()) <= MAX_DURATION);
|
||||
c.edit_prev(); // Hours
|
||||
c.edit_up(); // +1h
|
||||
assert!(Duration::from(*c.get_current_value()) <= MAX_DURATION);
|
||||
c.edit_prev(); // Minutes
|
||||
c.edit_up(); // +1m
|
||||
assert!(Duration::from(*c.get_current_value()) <= MAX_DURATION);
|
||||
c.edit_prev(); // Sec.
|
||||
c.edit_up(); // +1s
|
||||
c.edit_up(); // +1s
|
||||
c.edit_up(); // +1s
|
||||
assert!(Duration::from(*c.get_current_value()) <= MAX_DURATION);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_down_years_to_days() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_YEAR + ONE_DAY,
|
||||
current_value: ONE_YEAR + ONE_DAY,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
c.edit_next(); // Hours
|
||||
c.edit_next(); // Days
|
||||
c.edit_next(); // Years
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Years, _)));
|
||||
c.edit_down();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_down_days_to_hours() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_DAY + ONE_HOUR,
|
||||
current_value: ONE_DAY + ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
c.edit_next(); // Hours
|
||||
c.edit_next(); // Days
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_down();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_down_hours_to_minutes() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_HOUR + ONE_MINUTE,
|
||||
current_value: ONE_HOUR + ONE_MINUTE,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
c.edit_next(); // Hours
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_down();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_down_minutes_to_seconds() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_MINUTE,
|
||||
current_value: ONE_MINUTE,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
c.edit_down();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_next_ydddhhmmssd() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_YEAR,
|
||||
current_value: ONE_YEAR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on - should start at Minutes
|
||||
c.toggle_edit();
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Years, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Decis, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_hours_in_dhhmmss_format() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_DAY + ONE_HOUR,
|
||||
current_value: ONE_DAY + ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
c.toggle_edit();
|
||||
c.edit_next(); // Move to Hours
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
|
||||
// Increment hours - should stay in Hours edit mode
|
||||
c.edit_up();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
assert_eq!(
|
||||
Duration::from(*c.get_current_value()),
|
||||
ONE_DAY + 2 * ONE_HOUR
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_next_ydddhhmmss() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_YEAR,
|
||||
current_value: ONE_YEAR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on - should start at Minutes
|
||||
c.toggle_edit();
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Years, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_next_dhhmmssd() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_DAY,
|
||||
current_value: ONE_DAY,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on - should start at Minutes (following existing pattern)
|
||||
c.toggle_edit();
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Years, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Decis, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_next_hhmmssd() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
@ -69,6 +623,7 @@ fn test_edit_next_hhmmssd() {
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@ -76,6 +631,10 @@ fn test_edit_next_hhmmssd() {
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Years, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Decis, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
@ -90,6 +649,7 @@ fn test_edit_next_hhmmss() {
|
||||
current_value: ONE_HOUR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@ -97,6 +657,10 @@ fn test_edit_next_hhmmss() {
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Years, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
@ -109,6 +673,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 +693,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 +711,7 @@ fn test_edit_next_ssd() {
|
||||
current_value: ONE_SECOND * 3,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@ -153,6 +720,25 @@ fn test_edit_next_ssd() {
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Decis, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_next_sd() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_SECOND,
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Decis, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_next_ss() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
@ -160,15 +746,109 @@ fn test_edit_next_ss() {
|
||||
current_value: ONE_SECOND * 3,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
c.toggle_edit();
|
||||
c.edit_next();
|
||||
println!("mode -> {:?}", c.get_mode());
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_next_s() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_SECOND,
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_next();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_prev_ydddhhmmssd() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_YEAR,
|
||||
current_value: ONE_YEAR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on - should start at Minutes
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Decis, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Years, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_prev_ydddhhmmss() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_YEAR,
|
||||
current_value: ONE_YEAR,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on - should start at Minutes
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Years, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_prev_dhhmmssd() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_DAY,
|
||||
current_value: ONE_DAY,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on - should start at Minutes
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Decis, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Days, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Hours, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Minutes, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_prev_hhmmssd() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
@ -176,6 +856,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 +877,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 +896,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 +917,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 +936,26 @@ fn test_edit_prev_ssd() {
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Decis, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_prev_sd() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_SECOND,
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: true,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@ -270,6 +974,24 @@ fn test_edit_prev_ss() {
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
c.toggle_edit();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
c.edit_prev();
|
||||
assert!(matches!(c.get_mode(), Mode::Editable(Time::Seconds, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_prev_s() {
|
||||
let mut c = ClockState::<Timer>::new(ClockStateArgs {
|
||||
initial_value: ONE_SECOND,
|
||||
current_value: ONE_SECOND,
|
||||
tick_value: ONE_DECI_SECOND,
|
||||
with_decis: false,
|
||||
app_tx: None,
|
||||
});
|
||||
|
||||
// toggle on
|
||||
@ -285,7 +1007,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 +1024,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 +1044,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 +1066,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 +1087,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 +1110,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
|
||||
|
||||
@ -2,14 +2,14 @@ use crate::{
|
||||
common::{AppTime, Style},
|
||||
constants::TICK_VALUE_MS,
|
||||
duration::{DurationEx, MAX_DURATION},
|
||||
events::{Event, EventHandler},
|
||||
events::{AppEventTx, TuiEvent, TuiEventHandler},
|
||||
utils::center,
|
||||
widgets::{
|
||||
clock::{self, ClockState, ClockStateArgs, ClockWidget, Mode as ClockMode},
|
||||
edit_time::EditTimeState,
|
||||
edit_time::{EditTimeState, EditTimeStateArgs, EditTimeWidget},
|
||||
},
|
||||
};
|
||||
use crossterm::event::KeyModifiers;
|
||||
use crossterm::event::{Event as CrosstermEvent, KeyModifiers};
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
crossterm::event::KeyCode,
|
||||
@ -17,15 +17,20 @@ use ratatui::{
|
||||
text::Line,
|
||||
widgets::{StatefulWidget, Widget},
|
||||
};
|
||||
|
||||
use std::ops::Sub;
|
||||
use std::{cmp::max, time::Duration};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::edit_time::{EditTimeStateArgs, EditTimeWidget};
|
||||
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>,
|
||||
@ -37,19 +42,32 @@ pub struct CountdownState {
|
||||
}
|
||||
|
||||
impl CountdownState {
|
||||
pub fn new(
|
||||
clock: ClockState<clock::Countdown>,
|
||||
elapsed_value: Duration,
|
||||
app_time: AppTime,
|
||||
) -> 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
|
||||
@ -124,15 +142,14 @@ impl CountdownState {
|
||||
}
|
||||
}
|
||||
|
||||
impl EventHandler for CountdownState {
|
||||
fn update(&mut self, event: Event) -> Option<Event> {
|
||||
let is_edit_clock = self.clock.is_edit_mode();
|
||||
let is_edit_time = self.edit_time.is_some();
|
||||
impl TuiEventHandler for CountdownState {
|
||||
fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
|
||||
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();
|
||||
@ -145,7 +162,107 @@ impl EventHandler for CountdownState {
|
||||
edit_time.set_max_time(max_time);
|
||||
}
|
||||
}
|
||||
Event::Key(key) => match key.code {
|
||||
// EDIT CLOCK mode
|
||||
TuiEvent::Crossterm(CrosstermEvent::Key(key)) if self.is_clock_edit_mode() => {
|
||||
match key.code {
|
||||
// skip editing
|
||||
KeyCode::Esc => {
|
||||
// Important: set current value first
|
||||
self.clock.set_current_value(*self.clock.get_prev_value());
|
||||
// before toggling back to non-edit mode
|
||||
self.clock.toggle_edit();
|
||||
}
|
||||
// Apply changes and set new initial value
|
||||
KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
// toggle edit mode
|
||||
self.clock.toggle_edit();
|
||||
// set initial value
|
||||
self.clock
|
||||
.set_initial_value(*self.clock.get_current_value());
|
||||
// always reset `elapsed_clock`
|
||||
self.elapsed_clock.reset();
|
||||
}
|
||||
// Apply changes
|
||||
KeyCode::Char('s') => {
|
||||
// toggle edit mode
|
||||
self.clock.toggle_edit();
|
||||
// always reset `elapsed_clock`
|
||||
self.elapsed_clock.reset();
|
||||
}
|
||||
KeyCode::Right => {
|
||||
self.clock.edit_prev();
|
||||
}
|
||||
KeyCode::Left => {
|
||||
self.clock.edit_next();
|
||||
}
|
||||
KeyCode::Up if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
self.clock.edit_jump_up();
|
||||
}
|
||||
KeyCode::Up => {
|
||||
self.clock.edit_up();
|
||||
}
|
||||
KeyCode::Down if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
self.clock.edit_jump_down();
|
||||
}
|
||||
KeyCode::Down => {
|
||||
self.clock.edit_down();
|
||||
}
|
||||
_ => return Some(event),
|
||||
}
|
||||
}
|
||||
// EDIT LOCAL TIME mode
|
||||
TuiEvent::Crossterm(CrosstermEvent::Key(key)) if self.is_time_edit_mode() => {
|
||||
match key.code {
|
||||
// skip editing
|
||||
KeyCode::Esc => {
|
||||
self.edit_time = None;
|
||||
}
|
||||
// Apply changes and set new initial value
|
||||
KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
if let Some(edit_time) = &mut self.edit_time.clone() {
|
||||
// Order matters:
|
||||
// 1. update current value
|
||||
self.edit_time_done(edit_time);
|
||||
// 2. set initial value
|
||||
self.clock
|
||||
.set_initial_value(*self.clock.get_current_value());
|
||||
}
|
||||
// always reset `elapsed_clock`
|
||||
self.elapsed_clock.reset();
|
||||
}
|
||||
// Apply changes of editing by local time
|
||||
KeyCode::Char('s') => {
|
||||
if let Some(edit_time) = &mut self.edit_time.clone() {
|
||||
self.edit_time_done(edit_time)
|
||||
}
|
||||
// always reset `elapsed_clock`
|
||||
self.elapsed_clock.reset();
|
||||
}
|
||||
// move edit position to the left
|
||||
KeyCode::Left => {
|
||||
// safe unwrap because we are in `is_time_edit_mode`
|
||||
self.edit_time.as_mut().unwrap().next();
|
||||
}
|
||||
// move edit position to the right
|
||||
KeyCode::Right => {
|
||||
// safe unwrap because we are in `is_time_edit_mode`
|
||||
self.edit_time.as_mut().unwrap().prev();
|
||||
}
|
||||
// Value up
|
||||
KeyCode::Up => {
|
||||
// safe unwrap because of previous check in `is_time_edit_mode`
|
||||
self.edit_time.as_mut().unwrap().up();
|
||||
}
|
||||
// Value down
|
||||
KeyCode::Down => {
|
||||
// safe unwrap because of previous check in `is_time_edit_mode`
|
||||
self.edit_time.as_mut().unwrap().down();
|
||||
}
|
||||
_ => return Some(event),
|
||||
}
|
||||
}
|
||||
// default mode
|
||||
TuiEvent::Crossterm(CrosstermEvent::Key(key)) => match key.code {
|
||||
KeyCode::Char('r') => {
|
||||
// reset both clocks to use intial values
|
||||
self.clock.reset();
|
||||
@ -170,85 +287,29 @@ impl EventHandler for CountdownState {
|
||||
self.edit_time_done(edit_time);
|
||||
}
|
||||
}
|
||||
// STRG + e => toggle edit time
|
||||
// Enter edit by local time mode
|
||||
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();
|
||||
}
|
||||
// set `edit_time`
|
||||
self.edit_time = Some(EditTimeState::new(EditTimeStateArgs {
|
||||
time: self.time_to_edit(),
|
||||
min: self.min_time_to_edit(),
|
||||
max: self.max_time_to_edit(),
|
||||
}));
|
||||
|
||||
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`
|
||||
// pause `elapsed_clock`
|
||||
if self.elapsed_clock.is_running() {
|
||||
self.elapsed_clock.toggle_pause();
|
||||
}
|
||||
}
|
||||
// STRG + e => toggle edit clock
|
||||
// Enter edit clock mode
|
||||
KeyCode::Char('e') => {
|
||||
// toggle edit mode
|
||||
self.clock.toggle_edit();
|
||||
|
||||
// stop `elapsed_clock`
|
||||
// pause `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::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::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::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),
|
||||
},
|
||||
@ -260,6 +321,7 @@ impl EventHandler for CountdownState {
|
||||
|
||||
pub struct Countdown {
|
||||
pub style: Style,
|
||||
pub blink: bool,
|
||||
}
|
||||
|
||||
fn human_days_diff(a: &OffsetDateTime, b: &OffsetDateTime) -> String {
|
||||
@ -267,7 +329,7 @@ fn human_days_diff(a: &OffsetDateTime, b: &OffsetDateTime) -> String {
|
||||
match days_diff {
|
||||
0 => "today".to_owned(),
|
||||
1 => "tomorrow".to_owned(),
|
||||
n => format!("+{}days", n),
|
||||
n => format!("+{n}days"),
|
||||
}
|
||||
}
|
||||
|
||||
@ -319,11 +381,12 @@ impl StatefulWidget for Countdown {
|
||||
}
|
||||
.to_uppercase(),
|
||||
);
|
||||
let widget = ClockWidget::new(self.style);
|
||||
let widget = ClockWidget::new(self.style, self.blink);
|
||||
|
||||
let area = center(
|
||||
area,
|
||||
Constraint::Length(max(
|
||||
widget.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(widget.get_height() + 1 /* height of label */),
|
||||
|
||||
@ -9,7 +9,7 @@ use ratatui::{
|
||||
|
||||
use crate::{
|
||||
common::Style,
|
||||
widgets::clock_elements::{Colon, Digit, COLON_WIDTH, DIGIT_SPACE_WIDTH, DIGIT_WIDTH},
|
||||
widgets::clock_elements::{COLON_WIDTH, Colon, DIGIT_SPACE_WIDTH, DIGIT_WIDTH, Digit},
|
||||
};
|
||||
|
||||
use super::clock_elements::DIGIT_HEIGHT;
|
||||
|
||||
589
src/widgets/event.rs
Normal file
@ -0,0 +1,589 @@
|
||||
use color_eyre::{Report, eyre::eyre};
|
||||
use crossterm::event::{Event as CrosstermEvent, KeyCode, KeyModifiers};
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::{Constraint, Layout, Position, Rect},
|
||||
style::{Color, Modifier, Style},
|
||||
text::Line,
|
||||
widgets::{Paragraph, StatefulWidget, Widget},
|
||||
};
|
||||
use time::{OffsetDateTime, PrimitiveDateTime, macros::format_description};
|
||||
use tui_input::Input;
|
||||
use tui_input::backend::crossterm::EventHandler;
|
||||
|
||||
use crate::{
|
||||
common::{AppTime, ClockTypeId, Style as DigitStyle},
|
||||
duration::CalendarDuration,
|
||||
event::Event,
|
||||
events::{AppEvent, AppEventTx, TuiEvent, TuiEventHandler},
|
||||
utils::center,
|
||||
widgets::{clock, clock_elements::DIGIT_HEIGHT},
|
||||
};
|
||||
use std::{cmp::max, time::Duration};
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
enum Editable {
|
||||
#[default]
|
||||
DateTime,
|
||||
Title,
|
||||
}
|
||||
|
||||
impl Editable {
|
||||
pub fn next(&self) -> Self {
|
||||
match self {
|
||||
Editable::DateTime => Editable::Title,
|
||||
Editable::Title => Editable::DateTime,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prev(&self) -> Self {
|
||||
match self {
|
||||
Editable::DateTime => Editable::Title,
|
||||
Editable::Title => Editable::DateTime,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum EditMode {
|
||||
None,
|
||||
Editing(Editable),
|
||||
}
|
||||
|
||||
impl EditMode {
|
||||
fn is_editable(&self) -> bool {
|
||||
match self {
|
||||
EditMode::None => false,
|
||||
EditMode::Editing(_) => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// State for `EventWidget`
|
||||
pub struct EventState {
|
||||
title: Option<String>,
|
||||
event_time: OffsetDateTime,
|
||||
app_time: OffsetDateTime,
|
||||
start_time: OffsetDateTime,
|
||||
with_decis: bool,
|
||||
/// counter to simulate `DONE` state
|
||||
/// Default value: `None`
|
||||
done_count: Option<u64>,
|
||||
app_tx: AppEventTx,
|
||||
// inputs
|
||||
input_datetime: Input,
|
||||
input_datetime_error: Option<Report>,
|
||||
input_title: Input,
|
||||
input_title_error: Option<Report>,
|
||||
edit_mode: EditMode,
|
||||
last_editable: Editable,
|
||||
}
|
||||
|
||||
pub struct EventStateArgs {
|
||||
pub app_time: AppTime,
|
||||
pub event: Event,
|
||||
pub with_decis: bool,
|
||||
pub app_tx: AppEventTx,
|
||||
}
|
||||
|
||||
impl EventState {
|
||||
pub fn new(args: EventStateArgs) -> Self {
|
||||
let EventStateArgs {
|
||||
app_time,
|
||||
event,
|
||||
with_decis,
|
||||
app_tx,
|
||||
} = args;
|
||||
|
||||
let app_datetime = OffsetDateTime::from(app_time);
|
||||
// assume event has as same `offset` as `app_time`
|
||||
let event_offset = event.date_time.assume_offset(app_datetime.offset());
|
||||
let input_datetime_value = format_offsetdatetime(&event_offset);
|
||||
let input_title_value = event.title.clone().unwrap_or("".into());
|
||||
|
||||
Self {
|
||||
title: event.title.clone(),
|
||||
event_time: event_offset,
|
||||
app_time: app_datetime,
|
||||
start_time: app_datetime,
|
||||
with_decis,
|
||||
done_count: None,
|
||||
app_tx,
|
||||
input_datetime: Input::default().with_value(input_datetime_value),
|
||||
input_datetime_error: None,
|
||||
input_title: Input::default().with_value(input_title_value),
|
||||
input_title_error: None,
|
||||
edit_mode: EditMode::None,
|
||||
last_editable: Editable::default(),
|
||||
}
|
||||
}
|
||||
|
||||
// Sets `app_time`
|
||||
pub fn set_app_time(&mut self, app_time: AppTime) {
|
||||
let app_datetime = OffsetDateTime::from(app_time);
|
||||
self.app_time = app_datetime;
|
||||
|
||||
// Since updating `app_time` is like a `Tick`, we check `done` state here
|
||||
self.check_done();
|
||||
}
|
||||
|
||||
pub fn set_with_decis(&mut self, with_decis: bool) {
|
||||
self.with_decis = with_decis;
|
||||
}
|
||||
|
||||
pub fn get_event(&self) -> Event {
|
||||
Event {
|
||||
title: self.title.clone(),
|
||||
date_time: time::PrimitiveDateTime::new(self.event_time.date(), self.event_time.time()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_percentage_done(&self) -> u16 {
|
||||
get_percentage(self.start_time, self.event_time, self.app_time)
|
||||
}
|
||||
|
||||
pub fn get_duration(&mut self) -> CalendarDuration {
|
||||
CalendarDuration::from_start_end_times(self.event_time, self.app_time)
|
||||
}
|
||||
|
||||
fn check_done(&mut self) {
|
||||
let clock_duration = self.get_duration();
|
||||
if clock_duration.is_since() {
|
||||
let duration: Duration = clock_duration.into();
|
||||
// give some offset to make sure we are around `Duration::ZERO`
|
||||
// Without that we might miss it, because the app runs on its own FPS
|
||||
if duration < Duration::from_millis(100) {
|
||||
// reset `done_count`
|
||||
self.done_count = Some(clock::MAX_DONE_COUNT);
|
||||
// send notification
|
||||
_ = self.app_tx.send(AppEvent::ClockDone(
|
||||
ClockTypeId::Event,
|
||||
self.title.clone().unwrap_or("".into()),
|
||||
));
|
||||
}
|
||||
// count (possible) `done`
|
||||
self.done_count = clock::count_clock_done(self.done_count);
|
||||
}
|
||||
}
|
||||
|
||||
fn reset_cursor(&mut self) {
|
||||
_ = self.app_tx.send(AppEvent::SetCursor(None));
|
||||
}
|
||||
|
||||
pub fn is_edit_mode(&self) -> bool {
|
||||
self.edit_mode.is_editable()
|
||||
}
|
||||
|
||||
fn reset_edit_mode(&mut self) {
|
||||
self.edit_mode = EditMode::None;
|
||||
}
|
||||
|
||||
fn reset_input_datetime(&mut self) {
|
||||
self.input_datetime = Input::default().with_value(format_offsetdatetime(&self.event_time));
|
||||
self.input_datetime_error = None;
|
||||
}
|
||||
|
||||
fn reset_input_title(&mut self) {
|
||||
self.input_title = Input::default().with_value(self.title.clone().unwrap_or_default());
|
||||
self.input_title_error = None;
|
||||
}
|
||||
|
||||
fn save_event_time(&mut self, date_time: PrimitiveDateTime) {
|
||||
self.event_time =
|
||||
// apply offset to be in sync with `AppTime`
|
||||
date_time.assume_offset(self.app_time.offset());
|
||||
}
|
||||
|
||||
fn save_title(&mut self, value: &str) {
|
||||
self.title = if value.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(value.into())
|
||||
};
|
||||
}
|
||||
|
||||
fn prepare_switch_input(&mut self, editable: Editable) {
|
||||
// before switching store valid values or reset inputs in case of errors
|
||||
match editable {
|
||||
Editable::DateTime => {
|
||||
// accept valid values only
|
||||
match validate_datetime(self.input_datetime.value()) {
|
||||
Ok(dt) => self.save_event_time(dt),
|
||||
Err(_) => self.reset_input_datetime(),
|
||||
}
|
||||
}
|
||||
Editable::Title => match validate_title(self.input_title.clone().value()) {
|
||||
Ok(title) => self.save_title(title),
|
||||
Err(_) => self.reset_input_title(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn switch_input(&mut self, editable: Editable) {
|
||||
self.edit_mode = EditMode::Editing(editable);
|
||||
self.last_editable = editable;
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_datetime(value: &str) -> Result<time::PrimitiveDateTime, Report> {
|
||||
time::PrimitiveDateTime::parse(
|
||||
value,
|
||||
format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"),
|
||||
)
|
||||
.map_err(|_| eyre!("Expected format 'YYYY-MM-DD HH:MM:SS'"))
|
||||
}
|
||||
|
||||
const MAX_LABEL_WIDTH: usize = 60;
|
||||
|
||||
fn validate_title(value: &str) -> Result<&str, Report> {
|
||||
if value.len() > MAX_LABEL_WIDTH {
|
||||
return Err(eyre!("Max. {} chars", MAX_LABEL_WIDTH));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
impl TuiEventHandler for EventState {
|
||||
fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
|
||||
let editable = self.edit_mode.is_editable();
|
||||
match event {
|
||||
// EDIT mode
|
||||
TuiEvent::Crossterm(crossterm_event @ CrosstermEvent::Key(key)) if editable => {
|
||||
match key.code {
|
||||
// Skip changes
|
||||
KeyCode::Esc => {
|
||||
// reset inputs
|
||||
self.reset_input_datetime();
|
||||
self.reset_input_title();
|
||||
|
||||
self.reset_edit_mode();
|
||||
self.reset_cursor();
|
||||
}
|
||||
// switch to prev. input
|
||||
KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => {
|
||||
if let EditMode::Editing(editable) = self.edit_mode {
|
||||
self.prepare_switch_input(editable);
|
||||
self.switch_input(editable.prev());
|
||||
}
|
||||
}
|
||||
// switch to next input
|
||||
KeyCode::Tab => {
|
||||
if let EditMode::Editing(editable) = self.edit_mode {
|
||||
self.prepare_switch_input(editable);
|
||||
self.switch_input(editable.next());
|
||||
}
|
||||
}
|
||||
KeyCode::Enter => match self.edit_mode {
|
||||
EditMode::Editing(Editable::DateTime) => {
|
||||
// accept valid values only
|
||||
match validate_datetime(self.input_datetime.value()) {
|
||||
Ok(dt) => {
|
||||
self.save_event_time(dt);
|
||||
self.reset_edit_mode();
|
||||
self.reset_cursor();
|
||||
}
|
||||
Err(e) => self.input_datetime_error = Some(e),
|
||||
}
|
||||
}
|
||||
EditMode::Editing(Editable::Title) => {
|
||||
// accept valid values only
|
||||
match validate_title(self.input_title.clone().value()) {
|
||||
Ok(title) => {
|
||||
self.save_title(title);
|
||||
self.reset_edit_mode();
|
||||
self.reset_cursor();
|
||||
}
|
||||
Err(e) => self.input_title_error = Some(e),
|
||||
}
|
||||
}
|
||||
EditMode::None => {}
|
||||
},
|
||||
_ => match self.edit_mode {
|
||||
EditMode::Editing(Editable::DateTime) => {
|
||||
// push `CrosstermEvent` down to input
|
||||
self.input_datetime.handle_event(&crossterm_event);
|
||||
|
||||
let value = self.input_datetime.value();
|
||||
|
||||
match self.input_datetime_error {
|
||||
// To relax errors while typing:
|
||||
// (A) Do a "full" validation of `datetime` in case of a previous error only
|
||||
Some(_) => {
|
||||
if let Err(e) = validate_datetime(value) {
|
||||
self.input_datetime_error = Some(e);
|
||||
} else {
|
||||
self.input_datetime_error = None;
|
||||
}
|
||||
}
|
||||
// (B) do a "light" validation of `datetime` in case of no previous error
|
||||
None => {
|
||||
// check length of expected format
|
||||
if value.len() > 19 {
|
||||
self.input_datetime_error =
|
||||
Some(eyre!("Expected format 'YYYY-MM-DD HH:MM:SS'"))
|
||||
} else {
|
||||
self.input_datetime_error = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EditMode::Editing(Editable::Title) => {
|
||||
// push `CrosstermEvent` down to input
|
||||
self.input_title.handle_event(&crossterm_event);
|
||||
// do always a validation while typing
|
||||
if let Err(e) = validate_title(self.input_title.value()) {
|
||||
self.input_title_error = Some(e);
|
||||
} else {
|
||||
self.input_title_error = None;
|
||||
}
|
||||
}
|
||||
EditMode::None => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
// NORMAL mode
|
||||
TuiEvent::Crossterm(CrosstermEvent::Key(key)) => match key.code {
|
||||
// Enter edit mode
|
||||
KeyCode::Char('e') => {
|
||||
self.edit_mode = EditMode::Editing(self.last_editable);
|
||||
}
|
||||
_ => return Some(event),
|
||||
},
|
||||
_ => return Some(event),
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn get_percentage(start: OffsetDateTime, end: OffsetDateTime, current: OffsetDateTime) -> u16 {
|
||||
let total_millis = (end - start).whole_milliseconds();
|
||||
|
||||
if total_millis <= 0 {
|
||||
return 100;
|
||||
}
|
||||
|
||||
let elapsed_millis = (current - start).whole_milliseconds();
|
||||
|
||||
if elapsed_millis <= 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let percentage = (elapsed_millis * 100 / total_millis).min(100);
|
||||
percentage as u16
|
||||
}
|
||||
|
||||
fn format_offsetdatetime(dt: &OffsetDateTime) -> String {
|
||||
dt.format(&format_description!(
|
||||
"[year]-[month]-[day] [hour]:[minute]:[second]"
|
||||
))
|
||||
.unwrap_or_else(|e| format!("time format error: {}", e))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EventWidget {
|
||||
pub style: DigitStyle,
|
||||
pub blink: bool,
|
||||
}
|
||||
|
||||
impl StatefulWidget for EventWidget {
|
||||
type State = EventState;
|
||||
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
||||
let with_decis = state.with_decis;
|
||||
let clock_duration = state.get_duration();
|
||||
let clock_format = clock::format_by_duration(&clock_duration);
|
||||
let clock_widths = clock::clock_horizontal_lengths(&clock_format, with_decis);
|
||||
let clock_width = clock_widths.iter().sum();
|
||||
|
||||
let area = center(
|
||||
area,
|
||||
Constraint::Length(max(clock_width, MAX_LABEL_WIDTH as u16)),
|
||||
Constraint::Length(
|
||||
DIGIT_HEIGHT + 7, /* height of all labels + empty lines */
|
||||
),
|
||||
);
|
||||
let [_, v1, v2, v3, _, v4] = Layout::vertical(Constraint::from_lengths([
|
||||
3, // empty (offset) to keep everything centered vertically comparing to "clock" widgets with one label only
|
||||
DIGIT_HEIGHT,
|
||||
1, // label: event date
|
||||
1, // label: event title
|
||||
1, // empty
|
||||
1, // label: error
|
||||
]))
|
||||
.areas(area);
|
||||
|
||||
// To simulate a blink effect, just use an "empty" symbol (string)
|
||||
// It's "empty" all digits and creates an "empty" render area
|
||||
let symbol = if self.blink && clock::should_blink(state.done_count) {
|
||||
" "
|
||||
} else {
|
||||
self.style.get_digit_symbol()
|
||||
};
|
||||
|
||||
let render_clock_state = clock::RenderClockState {
|
||||
with_decis,
|
||||
duration: clock_duration.clone(),
|
||||
editable_time: None,
|
||||
format: clock_format,
|
||||
symbol,
|
||||
widths: clock_widths,
|
||||
};
|
||||
|
||||
clock::render_clock(v1, buf, render_clock_state);
|
||||
|
||||
// Helper to calculate centered area, cursor x position, and scroll
|
||||
let calc_editable_input_positions = |input: &Input, area: Rect| -> (Rect, u16, usize) {
|
||||
// Calculate scroll position to keep cursor visible
|
||||
let input_scroll = input.visual_scroll(area.width as usize);
|
||||
|
||||
// Get correct visual width (handles unicode properly)
|
||||
let text_width = Line::raw(input.value()).width() as u16;
|
||||
|
||||
// Calculate visible text width after scrolling
|
||||
let visible_text_width = text_width
|
||||
.saturating_sub(input_scroll as u16)
|
||||
.min(area.width);
|
||||
|
||||
// Center the visible portion
|
||||
let offset_x = (area.width.saturating_sub(visible_text_width)) / 2;
|
||||
|
||||
let centered_area = Rect {
|
||||
x: area.x + offset_x,
|
||||
y: area.y,
|
||||
width: visible_text_width,
|
||||
height: area.height,
|
||||
};
|
||||
|
||||
// Cursor position relative to the visible scrolled text
|
||||
let cursor_offset = input.visual_cursor().saturating_sub(input_scroll);
|
||||
let cursor_x = area.x + offset_x + cursor_offset as u16;
|
||||
|
||||
(centered_area, cursor_x, input_scroll)
|
||||
};
|
||||
|
||||
fn input_edit_style(with_error: bool) -> Style {
|
||||
if with_error {
|
||||
Style::default()
|
||||
.add_modifier(Modifier::UNDERLINED)
|
||||
.fg(Color::Red)
|
||||
} else {
|
||||
Style::default().add_modifier(Modifier::UNDERLINED)
|
||||
}
|
||||
}
|
||||
|
||||
// Render date time input
|
||||
match state.edit_mode {
|
||||
// EDIT
|
||||
EditMode::Editing(Editable::DateTime) => {
|
||||
let (datetime_area, datetime_cursor_x, datetime_scroll) =
|
||||
calc_editable_input_positions(&state.input_datetime, v2);
|
||||
|
||||
Paragraph::new(state.input_datetime.value())
|
||||
.style(input_edit_style(state.input_datetime_error.is_some()))
|
||||
.scroll((0, datetime_scroll as u16))
|
||||
.render(datetime_area, buf);
|
||||
|
||||
// Update cursor
|
||||
let cp = Position::new(datetime_cursor_x, v2.y);
|
||||
let _ = state.app_tx.send(AppEvent::SetCursor(Some(cp)));
|
||||
}
|
||||
// NORMAL
|
||||
_ => {
|
||||
let mut prefix = "Until";
|
||||
|
||||
if clock_duration.is_since() {
|
||||
let duration: Duration = clock_duration.clone().into();
|
||||
// Show `done` for a short of time (1 sec)
|
||||
prefix = if duration < Duration::from_secs(1) {
|
||||
"Done"
|
||||
} else {
|
||||
"Since"
|
||||
};
|
||||
};
|
||||
|
||||
Paragraph::new(format!(
|
||||
"{} {}",
|
||||
prefix.to_uppercase(),
|
||||
state.input_datetime.value()
|
||||
))
|
||||
.centered()
|
||||
.render(v2, buf);
|
||||
}
|
||||
};
|
||||
|
||||
// Render title input
|
||||
match state.edit_mode {
|
||||
// EDIT
|
||||
EditMode::Editing(Editable::Title) => {
|
||||
let (title_area, title_cursor_x, title_scroll) =
|
||||
calc_editable_input_positions(&state.input_title, v3);
|
||||
|
||||
Paragraph::new(state.input_title.value().to_uppercase())
|
||||
.style(input_edit_style(state.input_title_error.is_some()))
|
||||
.scroll((0, title_scroll as u16))
|
||||
.render(title_area, buf);
|
||||
// Update cursor
|
||||
let cp = Position::new(title_cursor_x, v3.y);
|
||||
let _ = state.app_tx.send(AppEvent::SetCursor(Some(cp)));
|
||||
}
|
||||
// NORMAL
|
||||
_ => {
|
||||
Paragraph::new(state.input_title.value().to_uppercase())
|
||||
.centered()
|
||||
.render(v3, buf);
|
||||
}
|
||||
};
|
||||
|
||||
// Render error
|
||||
let error_txt: String = match (&state.input_datetime_error, &state.input_title_error) {
|
||||
(Some(e), _) => e.to_string(),
|
||||
(_, Some(e)) => e.to_string(),
|
||||
_ => "".into(),
|
||||
};
|
||||
Paragraph::new(error_txt.to_lowercase())
|
||||
.style(Style::default().add_modifier(Modifier::ITALIC))
|
||||
.centered()
|
||||
.render(v4, buf);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use time::macros::datetime;
|
||||
|
||||
#[test]
|
||||
fn test_get_percentage() {
|
||||
let start = datetime!(2024-01-01 10:00:00 UTC);
|
||||
let end = datetime!(2024-01-01 20:00:00 UTC);
|
||||
|
||||
// current == start: 0%
|
||||
assert_eq!(get_percentage(start, end, start), 0);
|
||||
|
||||
// current == end: 100%
|
||||
assert_eq!(get_percentage(start, end, end), 100);
|
||||
|
||||
// current halfway: 50%
|
||||
let halfway = datetime!(2024-01-01 15:00:00 UTC);
|
||||
assert_eq!(get_percentage(start, end, halfway), 50);
|
||||
|
||||
// current 25%
|
||||
let quarter = datetime!(2024-01-01 12:30:00 UTC);
|
||||
assert_eq!(get_percentage(start, end, quarter), 25);
|
||||
|
||||
// current 75%
|
||||
let three_quarters = datetime!(2024-01-01 17:30:00 UTC);
|
||||
assert_eq!(get_percentage(start, end, three_quarters), 75);
|
||||
|
||||
// current > end: clamped to 100%
|
||||
let after = datetime!(2024-01-01 22:00:00 UTC);
|
||||
assert_eq!(get_percentage(start, end, after), 100);
|
||||
|
||||
// current < start: 0%
|
||||
let before = datetime!(2024-01-01 08:00:00 UTC);
|
||||
assert_eq!(get_percentage(start, end, before), 0);
|
||||
|
||||
// end <= start: 100%
|
||||
assert_eq!(get_percentage(end, start, halfway), 100);
|
||||
assert_eq!(get_percentage(start, start, start), 100);
|
||||
}
|
||||
}
|
||||
@ -13,11 +13,11 @@ use ratatui::{
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FooterState {
|
||||
show_menu: bool,
|
||||
app_time_format: AppTimeFormat,
|
||||
app_time_format: Option<AppTimeFormat>,
|
||||
}
|
||||
|
||||
impl FooterState {
|
||||
pub const fn new(show_menu: bool, app_time_format: AppTimeFormat) -> Self {
|
||||
pub const fn new(show_menu: bool, app_time_format: Option<AppTimeFormat>) -> Self {
|
||||
Self {
|
||||
show_menu,
|
||||
app_time_format,
|
||||
@ -32,12 +32,12 @@ impl FooterState {
|
||||
self.show_menu
|
||||
}
|
||||
|
||||
pub const fn app_time_format(&self) -> &AppTimeFormat {
|
||||
pub const fn app_time_format(&self) -> &Option<AppTimeFormat> {
|
||||
&self.app_time_format
|
||||
}
|
||||
|
||||
pub fn toggle_app_time_format(&mut self) {
|
||||
self.app_time_format = self.app_time_format.next();
|
||||
pub const fn set_app_time_format(&mut self, value: Option<AppTimeFormat>) {
|
||||
self.app_time_format = value;
|
||||
}
|
||||
}
|
||||
|
||||
@ -53,9 +53,11 @@ impl StatefulWidget for Footer {
|
||||
type State = FooterState;
|
||||
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
||||
let content_labels: BTreeMap<Content, &str> = BTreeMap::from([
|
||||
(Content::Countdown, "[c]ountdown"),
|
||||
(Content::Timer, "[t]imer"),
|
||||
(Content::Pomodoro, "[p]omodoro"),
|
||||
(Content::Countdown, "[1]countdown"),
|
||||
(Content::Timer, "[2]timer"),
|
||||
(Content::Pomodoro, "[3]pomodoro"),
|
||||
(Content::Event, "[4]event"),
|
||||
(Content::LocalTime, "[0]local time"),
|
||||
]);
|
||||
|
||||
let [_, area] =
|
||||
@ -71,25 +73,26 @@ impl StatefulWidget for Footer {
|
||||
)
|
||||
.title(
|
||||
Line::from(
|
||||
match state.app_time_format {
|
||||
// `Hidden` -> no (empty) title
|
||||
AppTimeFormat::Hidden => "".into(),
|
||||
// others -> add some space around
|
||||
_ => format!(" {} ", self.app_time.format(&state.app_time_format))
|
||||
match (state.app_time_format, self.selected_content) {
|
||||
// Show time
|
||||
(Some(v), content) if content != Content::LocalTime => format!(" {} " // add some space around
|
||||
, self.app_time.format(&v)),
|
||||
// Hide time -> empty
|
||||
_ => "".into(),
|
||||
}
|
||||
).right_aligned())
|
||||
.border_set(border::PLAIN)
|
||||
.render(border_area, buf);
|
||||
// show menu
|
||||
if state.show_menu {
|
||||
let content_labels: Vec<Span> = content_labels
|
||||
let mut content_labels: Vec<Span> = content_labels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, (content, label))| {
|
||||
let mut style = Style::default();
|
||||
// Add space for all except last
|
||||
let label = if index < content_labels.len() - 1 {
|
||||
format!("{} ", label)
|
||||
format!("{label} ")
|
||||
} else {
|
||||
label.to_string()
|
||||
};
|
||||
@ -100,39 +103,50 @@ impl StatefulWidget for Footer {
|
||||
})
|
||||
.collect();
|
||||
|
||||
content_labels.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
Span::from("[→]next"),
|
||||
Span::from(SPACE),
|
||||
Span::from("[←]prev."),
|
||||
]);
|
||||
|
||||
const SPACE: &str = " "; // 2 empty spaces
|
||||
let widths = [Constraint::Length(12), Constraint::Percentage(100)];
|
||||
let table = Table::new(
|
||||
[
|
||||
// content
|
||||
Row::new(vec![
|
||||
Cell::from(Span::styled(
|
||||
"screens",
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
let mut table_rows = vec![
|
||||
// screens
|
||||
Row::new(vec![
|
||||
Cell::from(Span::styled(
|
||||
"screens",
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Cell::from(Line::from(content_labels)),
|
||||
]),
|
||||
// appearance
|
||||
Row::new(vec![
|
||||
Cell::from(Span::styled(
|
||||
"appearance",
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Cell::from(Line::from(vec![
|
||||
Span::from("[,]change style"),
|
||||
Span::from(SPACE),
|
||||
Span::from("[.]toggle deciseconds"),
|
||||
Span::from(SPACE),
|
||||
Span::from(format!(
|
||||
"[:]toggle {} time",
|
||||
match self.app_time {
|
||||
AppTime::Local(_) => "local",
|
||||
AppTime::Utc(_) => "utc",
|
||||
}
|
||||
)),
|
||||
Cell::from(Line::from(content_labels)),
|
||||
]),
|
||||
// format
|
||||
Row::new(vec![
|
||||
Cell::from(Span::styled(
|
||||
"appearance",
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Cell::from(Line::from(vec![
|
||||
Span::from("[,]change style"),
|
||||
Span::from(SPACE),
|
||||
Span::from("[.]toggle deciseconds"),
|
||||
Span::from(SPACE),
|
||||
Span::from(format!(
|
||||
"[:]toggle {} time",
|
||||
match self.app_time {
|
||||
AppTime::Local(_) => "local",
|
||||
AppTime::Utc(_) => "utc",
|
||||
}
|
||||
)),
|
||||
])),
|
||||
]),
|
||||
// edit
|
||||
])),
|
||||
]),
|
||||
];
|
||||
|
||||
// Controls (except for `localtime`)
|
||||
if self.selected_content != Content::LocalTime {
|
||||
table_rows.extend_from_slice(&[
|
||||
// controls - 1. row
|
||||
Row::new(vec![
|
||||
Cell::from(Span::styled(
|
||||
"controls",
|
||||
@ -140,56 +154,126 @@ impl StatefulWidget for Footer {
|
||||
)),
|
||||
Cell::from(Line::from({
|
||||
match self.app_edit_mode {
|
||||
AppEditMode::None => {
|
||||
let mut spans = vec![
|
||||
Span::from(if self.running_clock {
|
||||
"[s]top"
|
||||
} else {
|
||||
"[s]tart"
|
||||
}),
|
||||
Span::from(SPACE),
|
||||
Span::from("[r]eset"),
|
||||
AppEditMode::None if self.selected_content != Content::Event => {
|
||||
let mut spans = vec![Span::from(if self.running_clock {
|
||||
"[s]top"
|
||||
} else {
|
||||
"[s]tart"
|
||||
})];
|
||||
spans.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
Span::from("[e]dit"),
|
||||
];
|
||||
]);
|
||||
if self.selected_content == Content::Countdown {
|
||||
spans.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
Span::from("[ctrl+e]dit by local time"),
|
||||
Span::from("[^e]dit by local time"),
|
||||
]);
|
||||
}
|
||||
spans.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
Span::from("[r]eset clock"),
|
||||
]);
|
||||
if self.selected_content == Content::Pomodoro {
|
||||
spans.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
Span::from("[← →]switch work/pause"),
|
||||
Span::from("[^r]eset clocks+rounds"),
|
||||
]);
|
||||
}
|
||||
spans
|
||||
}
|
||||
others => vec![
|
||||
Span::from(match others {
|
||||
AppEditMode::Clock => "[e]dit done",
|
||||
AppEditMode::Time => "[ctrl+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)), // ↓,
|
||||
],
|
||||
AppEditMode::None if self.selected_content == Content::Event => {
|
||||
vec![Span::from("[e]dit")]
|
||||
}
|
||||
AppEditMode::Clock | AppEditMode::Time | AppEditMode::Event => {
|
||||
let mut spans = vec![Span::from("[s]ave changes")];
|
||||
|
||||
if self.selected_content == Content::Event {
|
||||
spans[0] = Span::from("[enter]save changes")
|
||||
};
|
||||
|
||||
if self.selected_content == Content::Countdown
|
||||
|| self.selected_content == Content::Pomodoro
|
||||
{
|
||||
spans.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
Span::from("[^s]ave initial value"),
|
||||
]);
|
||||
}
|
||||
spans.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
Span::from("[esc]skip changes"),
|
||||
]);
|
||||
|
||||
if self.selected_content == Content::Event {
|
||||
spans.extend_from_slice(&[
|
||||
Span::from(SPACE),
|
||||
Span::from("[tab]switch input"),
|
||||
]);
|
||||
}
|
||||
spans
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
})),
|
||||
]),
|
||||
],
|
||||
widths,
|
||||
)
|
||||
.column_spacing(1);
|
||||
// controls - 2. row
|
||||
Row::new(if self.selected_content == Content::Event {
|
||||
vec![]
|
||||
} else {
|
||||
vec![
|
||||
Cell::from(Line::from("")),
|
||||
Cell::from(Line::from({
|
||||
match self.app_edit_mode {
|
||||
AppEditMode::None => {
|
||||
let mut spans = vec![];
|
||||
if self.selected_content == Content::Pomodoro {
|
||||
spans.extend_from_slice(&[Span::from(
|
||||
"[^←] or [^→] switch work/pause",
|
||||
)]);
|
||||
}
|
||||
spans
|
||||
}
|
||||
_ => vec![
|
||||
Span::from(format!(
|
||||
// ← →,
|
||||
"[{} {}]change selection",
|
||||
scrollbar::HORIZONTAL.begin,
|
||||
scrollbar::HORIZONTAL.end
|
||||
)),
|
||||
Span::from(SPACE),
|
||||
Span::from(format!(
|
||||
// ↑
|
||||
"[{}]edit up",
|
||||
scrollbar::VERTICAL.begin
|
||||
)),
|
||||
Span::from(SPACE),
|
||||
Span::from(format!(
|
||||
// ctrl + ↑
|
||||
"[^{}]edit up 10x",
|
||||
scrollbar::VERTICAL.begin
|
||||
)),
|
||||
Span::from(SPACE),
|
||||
Span::from(format!(
|
||||
// ↓
|
||||
"[{}]edit up",
|
||||
scrollbar::VERTICAL.end
|
||||
)),
|
||||
Span::from(SPACE),
|
||||
Span::from(format!(
|
||||
// ctrl + ↓
|
||||
"[^{}]edit up 10x",
|
||||
scrollbar::VERTICAL.end
|
||||
)),
|
||||
],
|
||||
}
|
||||
})),
|
||||
]
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
let table = Table::new(table_rows, widths).column_spacing(1);
|
||||
|
||||
Widget::render(table, menu_area, buf);
|
||||
}
|
||||
|
||||
195
src/widgets/local_time.rs
Normal file
@ -0,0 +1,195 @@
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::{Constraint, Layout, Rect},
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{StatefulWidget, Widget},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
common::{AppTime, AppTimeFormat, Style as DigitStyle},
|
||||
duration::{ClockDuration, DurationEx},
|
||||
events::{TuiEvent, TuiEventHandler},
|
||||
utils::center,
|
||||
widgets::clock_elements::{
|
||||
COLON_WIDTH, Colon, DIGIT_HEIGHT, DIGIT_SPACE_WIDTH, DIGIT_WIDTH, Digit,
|
||||
},
|
||||
};
|
||||
use std::cmp::max;
|
||||
|
||||
/// State for `LocalTimeWidget`
|
||||
pub struct LocalTimeState {
|
||||
time: AppTime,
|
||||
format: AppTimeFormat,
|
||||
}
|
||||
|
||||
pub struct LocalTimeStateArgs {
|
||||
pub app_time: AppTime,
|
||||
pub app_time_format: AppTimeFormat,
|
||||
}
|
||||
|
||||
impl LocalTimeState {
|
||||
pub fn new(args: LocalTimeStateArgs) -> Self {
|
||||
let LocalTimeStateArgs {
|
||||
app_time,
|
||||
app_time_format,
|
||||
} = args;
|
||||
|
||||
Self {
|
||||
time: app_time,
|
||||
format: app_time_format,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_app_time(&mut self, app_time: AppTime) {
|
||||
self.time = app_time;
|
||||
}
|
||||
|
||||
pub fn set_app_time_format(&mut self, format: AppTimeFormat) {
|
||||
self.format = format;
|
||||
}
|
||||
}
|
||||
|
||||
impl TuiEventHandler for LocalTimeState {
|
||||
fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
|
||||
Some(event)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LocalTimeWidget {
|
||||
pub style: DigitStyle,
|
||||
}
|
||||
|
||||
impl LocalTimeWidget {
|
||||
fn get_horizontal_lengths(&self, format: &AppTimeFormat) -> Vec<u16> {
|
||||
const PERIOD_WIDTH: u16 = 2; // PM or AM
|
||||
|
||||
match format {
|
||||
AppTimeFormat::HhMmSs => 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
|
||||
],
|
||||
AppTimeFormat::HhMm => vec![
|
||||
DIGIT_WIDTH, // H
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // h
|
||||
COLON_WIDTH, // :
|
||||
DIGIT_WIDTH, // M
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // m
|
||||
],
|
||||
AppTimeFormat::Hh12Mm => vec![
|
||||
DIGIT_SPACE_WIDTH + PERIOD_WIDTH, // (space) + (empty period) to center everything well horizontally
|
||||
DIGIT_WIDTH, // H
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // h
|
||||
COLON_WIDTH, // :
|
||||
DIGIT_WIDTH, // M
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
DIGIT_WIDTH, // m
|
||||
DIGIT_SPACE_WIDTH, // (space)
|
||||
PERIOD_WIDTH, // period
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StatefulWidget for LocalTimeWidget {
|
||||
type State = LocalTimeState;
|
||||
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
||||
let current_value: DurationEx = state.time.as_duration_of_today().into();
|
||||
let hours = current_value.hours_mod();
|
||||
let hours12 = current_value.hours_mod_12();
|
||||
let minutes = current_value.minutes_mod();
|
||||
let seconds = current_value.seconds_mod();
|
||||
let symbol = self.style.get_digit_symbol();
|
||||
|
||||
let label = Line::raw("Local Time".to_uppercase());
|
||||
let label_date = Line::raw(state.time.format_date().to_uppercase());
|
||||
let mut content_width = max(label.width(), label_date.width()) as u16;
|
||||
|
||||
let format = state.format;
|
||||
let widths = self.get_horizontal_lengths(&format);
|
||||
let mut widths = widths;
|
||||
// Special case for `Hh12Mm`
|
||||
// It might be `h:Mm` OR `Hh:Mm` depending on `hours12`
|
||||
if state.format == AppTimeFormat::Hh12Mm && hours12 < 10 {
|
||||
// single digit means, no (zero) width's for `H` and `space`
|
||||
widths[1] = 0; // `H`
|
||||
widths[2] = 0; // `space`
|
||||
}
|
||||
|
||||
content_width = max(widths.iter().sum(), content_width);
|
||||
let v_heights = [
|
||||
1, // empty (offset) to keep everything centered vertically comparing to "clock" widgets with one label only
|
||||
DIGIT_HEIGHT, // local time
|
||||
1, // label
|
||||
1, // date
|
||||
];
|
||||
|
||||
let area = center(
|
||||
area,
|
||||
Constraint::Length(content_width),
|
||||
Constraint::Length(v_heights.iter().sum()),
|
||||
);
|
||||
|
||||
let [_, v1, v2, v3] = Layout::vertical(Constraint::from_lengths(v_heights)).areas(area);
|
||||
|
||||
match state.format {
|
||||
AppTimeFormat::HhMmSs => {
|
||||
let [hh, _, h, c_hm, mm, _, m, c_ms, ss, _, s] =
|
||||
Layout::horizontal(Constraint::from_lengths(widths)).areas(v1);
|
||||
Digit::new(hours / 10, false, symbol).render(hh, buf);
|
||||
Digit::new(hours % 10, false, symbol).render(h, buf);
|
||||
Colon::new(symbol).render(c_hm, buf);
|
||||
Digit::new(minutes / 10, false, symbol).render(mm, buf);
|
||||
Digit::new(minutes % 10, false, symbol).render(m, buf);
|
||||
Colon::new(symbol).render(c_ms, buf);
|
||||
Digit::new(seconds / 10, false, symbol).render(ss, buf);
|
||||
Digit::new(seconds % 10, false, symbol).render(s, buf);
|
||||
}
|
||||
AppTimeFormat::HhMm => {
|
||||
let [hh, _, h, c_hm, mm, _, m] =
|
||||
Layout::horizontal(Constraint::from_lengths(widths)).areas(v1);
|
||||
Digit::new(hours / 10, false, symbol).render(hh, buf);
|
||||
Digit::new(hours % 10, false, symbol).render(h, buf);
|
||||
Colon::new(symbol).render(c_hm, buf);
|
||||
Digit::new(minutes / 10, false, symbol).render(mm, buf);
|
||||
Digit::new(minutes % 10, false, symbol).render(m, buf);
|
||||
}
|
||||
AppTimeFormat::Hh12Mm => {
|
||||
let [_, hh, _, h, c_hm, mm, _, m, _, p] =
|
||||
Layout::horizontal(Constraint::from_lengths(widths)).areas(v1);
|
||||
// Hh
|
||||
if hours12 >= 10 {
|
||||
Digit::new(hours12 / 10, false, symbol).render(hh, buf);
|
||||
Digit::new(hours12 % 10, false, symbol).render(h, buf);
|
||||
}
|
||||
// h
|
||||
else {
|
||||
Digit::new(hours12, false, symbol).render(h, buf);
|
||||
}
|
||||
Colon::new(symbol).render(c_hm, buf);
|
||||
Digit::new(minutes / 10, false, symbol).render(mm, buf);
|
||||
Digit::new(minutes % 10, false, symbol).render(m, buf);
|
||||
Span::styled(
|
||||
state.time.get_period().to_uppercase(),
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
)
|
||||
.render(p, buf);
|
||||
}
|
||||
}
|
||||
label.centered().render(v2, buf);
|
||||
label_date.centered().render(v3, buf);
|
||||
}
|
||||
}
|
||||
@ -1,24 +1,20 @@
|
||||
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 crossterm::event::{Event as CrosstermEvent, KeyCode, KeyModifiers};
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
crossterm::event::KeyCode,
|
||||
layout::{Constraint, Layout, Rect},
|
||||
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,10 +42,10 @@ impl ClockMap {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PomodoroState {
|
||||
mode: Mode,
|
||||
clock_map: ClockMap,
|
||||
round: u64,
|
||||
}
|
||||
|
||||
pub struct PomodoroStateArgs {
|
||||
@ -60,6 +55,8 @@ pub struct PomodoroStateArgs {
|
||||
pub initial_value_pause: Duration,
|
||||
pub current_value_pause: Duration,
|
||||
pub with_decis: bool,
|
||||
pub app_tx: AppEventTx,
|
||||
pub round: u64,
|
||||
}
|
||||
|
||||
impl PomodoroState {
|
||||
@ -71,6 +68,8 @@ impl PomodoroState {
|
||||
initial_value_pause,
|
||||
current_value_pause,
|
||||
with_decis,
|
||||
app_tx,
|
||||
round,
|
||||
} = args;
|
||||
Self {
|
||||
mode,
|
||||
@ -80,14 +79,19 @@ 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()),
|
||||
},
|
||||
round,
|
||||
}
|
||||
}
|
||||
|
||||
@ -103,14 +107,26 @@ impl PomodoroState {
|
||||
&self.clock_map.work
|
||||
}
|
||||
|
||||
pub fn get_clock_work_mut(&mut self) -> &mut ClockState<Countdown> {
|
||||
self.clock_map.get_mut(&Mode::Work)
|
||||
}
|
||||
|
||||
pub fn get_clock_pause(&self) -> &ClockState<Countdown> {
|
||||
&self.clock_map.pause
|
||||
}
|
||||
|
||||
pub fn get_clock_pause_mut(&mut self) -> &mut ClockState<Countdown> {
|
||||
self.clock_map.get_mut(&Mode::Pause)
|
||||
}
|
||||
|
||||
pub fn get_mode(&self) -> &Mode {
|
||||
&self.mode
|
||||
}
|
||||
|
||||
pub fn get_round(&self) -> u64 {
|
||||
self.round
|
||||
}
|
||||
|
||||
pub fn set_with_decis(&mut self, with_decis: bool) {
|
||||
self.clock_map.work.with_decis = with_decis;
|
||||
self.clock_map.pause.with_decis = with_decis;
|
||||
@ -124,40 +140,84 @@ 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 {
|
||||
// EDIT mode
|
||||
TuiEvent::Crossterm(CrosstermEvent::Key(key)) if edit_mode => match key.code {
|
||||
// Skip changes
|
||||
KeyCode::Esc => {
|
||||
let clock = self.get_clock_mut();
|
||||
// Important: set current value first
|
||||
clock.set_current_value(*clock.get_prev_value());
|
||||
// before toggling back to non-edit mode
|
||||
clock.toggle_edit();
|
||||
}
|
||||
// Apply changes and update initial value
|
||||
KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
self.get_clock_mut().toggle_edit();
|
||||
// update initial value
|
||||
let c = *self.get_clock().get_current_value();
|
||||
self.get_clock_mut().set_initial_value(c);
|
||||
}
|
||||
// Apply changes
|
||||
KeyCode::Char('s') => {
|
||||
self.get_clock_mut().toggle_edit();
|
||||
}
|
||||
// Value up
|
||||
KeyCode::Up => {
|
||||
self.get_clock_mut().edit_up();
|
||||
}
|
||||
// Value down
|
||||
KeyCode::Down => {
|
||||
self.get_clock_mut().edit_down();
|
||||
}
|
||||
// move edit position to the left
|
||||
KeyCode::Left => {
|
||||
self.get_clock_mut().edit_next();
|
||||
}
|
||||
// move edit position to the right
|
||||
KeyCode::Right => {
|
||||
self.get_clock_mut().edit_prev();
|
||||
}
|
||||
_ => return Some(event),
|
||||
},
|
||||
// default mode
|
||||
TuiEvent::Crossterm(CrosstermEvent::Key(key)) => match key.code {
|
||||
// Toggle run/pause
|
||||
KeyCode::Char('s') => {
|
||||
self.get_clock_mut().toggle_pause();
|
||||
}
|
||||
// Enter edit mode
|
||||
KeyCode::Char('e') => {
|
||||
self.get_clock_mut().toggle_edit();
|
||||
}
|
||||
KeyCode::Left if edit_mode => {
|
||||
self.get_clock_mut().edit_next();
|
||||
}
|
||||
KeyCode::Left => {
|
||||
// `next` is acting as same as a `prev` function, we don't have
|
||||
// toggle WORK/PAUSE
|
||||
KeyCode::Left if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
// `next` is acting as same as a "prev" function we don't have
|
||||
self.next();
|
||||
}
|
||||
KeyCode::Right if edit_mode => {
|
||||
self.get_clock_mut().edit_prev();
|
||||
}
|
||||
KeyCode::Right => {
|
||||
// toggle WORK/PAUSE
|
||||
KeyCode::Right if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
self.next();
|
||||
}
|
||||
KeyCode::Up if edit_mode => {
|
||||
self.get_clock_mut().edit_up();
|
||||
}
|
||||
KeyCode::Down if edit_mode => {
|
||||
self.get_clock_mut().edit_down();
|
||||
// reset rounds AND clocks
|
||||
KeyCode::Char('r') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
self.round = 1;
|
||||
self.get_clock_work_mut().reset();
|
||||
self.get_clock_pause_mut().reset();
|
||||
}
|
||||
// reset current clock
|
||||
KeyCode::Char('r') => {
|
||||
// increase round before (!!) resetting the clock
|
||||
if self.get_mode() == &Mode::Work && self.get_clock().is_done() {
|
||||
self.round += 1;
|
||||
}
|
||||
self.get_clock_mut().reset();
|
||||
}
|
||||
_ => return Some(event),
|
||||
@ -170,12 +230,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 {} {}",
|
||||
@ -184,23 +245,34 @@ impl StatefulWidget for PomodoroWidget {
|
||||
))
|
||||
.to_uppercase(),
|
||||
);
|
||||
let label_round = Line::raw((format!("round {}", state.get_round(),)).to_uppercase());
|
||||
|
||||
let area = center(
|
||||
area,
|
||||
Constraint::Length(max(
|
||||
clock_widget.get_width(
|
||||
&state.get_clock().get_format(),
|
||||
state.get_clock().with_decis,
|
||||
),
|
||||
clock_widget
|
||||
.get_width(state.get_clock().get_format(), state.get_clock().with_decis),
|
||||
label.width() as u16,
|
||||
)),
|
||||
Constraint::Length(clock_widget.get_height() + 1 /* height of mode_str */),
|
||||
Constraint::Length(
|
||||
// empty label + height of `label` + `label_round`
|
||||
clock_widget.get_height() + 3,
|
||||
),
|
||||
);
|
||||
|
||||
let [v1, v2] =
|
||||
Layout::vertical(Constraint::from_lengths([clock_widget.get_height(), 1])).areas(area);
|
||||
let [v1, v2, v3, v4] = Layout::vertical(Constraint::from_lengths([
|
||||
1,
|
||||
clock_widget.get_height(),
|
||||
1,
|
||||
1,
|
||||
]))
|
||||
.areas(area);
|
||||
|
||||
clock_widget.render(v1, buf, state.get_clock_mut());
|
||||
label.centered().render(v2, buf);
|
||||
// empty line keep everything in center vertically comparing to other
|
||||
// views (which have one label below the clock only)
|
||||
Line::raw("").centered().render(v1, buf);
|
||||
clock_widget.render(v2, buf, state.get_clock_mut());
|
||||
label.centered().render(v3, buf);
|
||||
label_round.centered().render(v4, buf);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
use crate::{
|
||||
common::Style,
|
||||
events::{Event, EventHandler},
|
||||
events::{TuiEvent, TuiEventHandler},
|
||||
utils::center,
|
||||
widgets::clock::{self, ClockState, ClockWidget},
|
||||
};
|
||||
use crossterm::event::{Event as CrosstermEvent, KeyModifiers};
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
crossterm::event::KeyCode,
|
||||
@ -13,7 +14,6 @@ use ratatui::{
|
||||
};
|
||||
use std::cmp::max;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TimerState {
|
||||
clock: ClockState<clock::Timer>,
|
||||
}
|
||||
@ -32,35 +32,65 @@ 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 {
|
||||
// EDIT mode
|
||||
TuiEvent::Crossterm(CrosstermEvent::Key(key)) if edit_mode => match key.code {
|
||||
// Skip changes
|
||||
KeyCode::Esc => {
|
||||
// Important: set current value first
|
||||
self.clock.set_current_value(*self.clock.get_prev_value());
|
||||
// before toggling back to non-edit mode
|
||||
self.clock.toggle_edit();
|
||||
}
|
||||
// Apply changes
|
||||
KeyCode::Char('s') => {
|
||||
self.clock.toggle_edit();
|
||||
}
|
||||
// move change position to the left
|
||||
KeyCode::Left => {
|
||||
self.clock.edit_next();
|
||||
}
|
||||
// move change position to the right
|
||||
KeyCode::Right => {
|
||||
self.clock.edit_prev();
|
||||
}
|
||||
KeyCode::Up if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
self.clock.edit_jump_up();
|
||||
}
|
||||
// change value up
|
||||
KeyCode::Up => {
|
||||
self.clock.edit_up();
|
||||
}
|
||||
// change value down
|
||||
KeyCode::Down if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
self.clock.edit_jump_down();
|
||||
}
|
||||
KeyCode::Down => {
|
||||
self.clock.edit_down();
|
||||
}
|
||||
_ => return Some(event),
|
||||
},
|
||||
// default mode
|
||||
TuiEvent::Crossterm(CrosstermEvent::Key(key)) => match key.code {
|
||||
// Toggle run/pause
|
||||
KeyCode::Char('s') => {
|
||||
self.clock.toggle_pause();
|
||||
}
|
||||
// reset clock
|
||||
KeyCode::Char('r') => {
|
||||
self.clock.reset();
|
||||
}
|
||||
// enter edit mode
|
||||
KeyCode::Char('e') => {
|
||||
self.clock.toggle_edit();
|
||||
}
|
||||
KeyCode::Left if edit_mode => {
|
||||
self.clock.edit_next();
|
||||
}
|
||||
KeyCode::Right if edit_mode => {
|
||||
self.clock.edit_prev();
|
||||
}
|
||||
KeyCode::Up if edit_mode => {
|
||||
self.clock.edit_up();
|
||||
}
|
||||
KeyCode::Down if edit_mode => {
|
||||
self.clock.edit_down();
|
||||
}
|
||||
_ => return Some(event),
|
||||
},
|
||||
_ => return Some(event),
|
||||
@ -71,19 +101,20 @@ 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(
|
||||
area,
|
||||
Constraint::Length(max(
|
||||
clock_widget.get_width(&clock.get_format(), clock.with_decis),
|
||||
clock_widget.get_width(clock.get_format(), clock.with_decis),
|
||||
label.width() as u16,
|
||||
)),
|
||||
Constraint::Length(clock_widget.get_height() + 1 /* height of label */),
|
||||
|
||||