generated from PlexSheep/rs-base
Compare commits
No commits in common. "master" and "v0.1.5" have entirely different histories.
|
@ -0,0 +1,44 @@
|
||||||
|
name: cargo devel CI
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '**'
|
||||||
|
# - '!master'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
format:
|
||||||
|
name: cargo CI
|
||||||
|
permissions:
|
||||||
|
# Give the default GITHUB_TOKEN write permission to commit and push the
|
||||||
|
# added or changed files to the repository.
|
||||||
|
contents: write
|
||||||
|
steps:
|
||||||
|
- name: get repo
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: install rust
|
||||||
|
uses: https://github.com/dtolnay/rust-toolchain@stable
|
||||||
|
- name: install additional rust things
|
||||||
|
run: |
|
||||||
|
rustup component add rustfmt
|
||||||
|
rustup component add clippy
|
||||||
|
- name: config custom registry
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.cargo/
|
||||||
|
echo "" > ~/.cargo/config.toml
|
||||||
|
echo "[registry]" >> ~/.cargo/config.toml
|
||||||
|
echo 'cscherr = "cscherr"' >> ~/.cargo/config.toml
|
||||||
|
echo '[registries.cscherr]' >> ~/.cargo/config.toml
|
||||||
|
echo 'index = "https://git.cscherr.de/PlexSheep/_cargo-index.git"' >> ~/.cargo/config.toml
|
||||||
|
cat ~/.cargo/config.toml
|
||||||
|
- name: cargo clippy check
|
||||||
|
run: cargo clippy --all-features --all-targets --workspace
|
||||||
|
- name: cargo clippy fix
|
||||||
|
run: cargo clippy --fix --all-features --all-targets --workspace
|
||||||
|
- name: cargo fmt
|
||||||
|
run: cargo fmt --all
|
||||||
|
- name: commit back to repository
|
||||||
|
uses: https://github.com/stefanzweifel/git-auto-commit-action@v5
|
||||||
|
with:
|
||||||
|
# Optional. Commit message for the created commit.
|
||||||
|
# Defaults to "Apply automatic changes"
|
||||||
|
commit_message: automatic cargo CI changes
|
|
@ -1,7 +0,0 @@
|
||||||
version: 2
|
|
||||||
updates:
|
|
||||||
- package-ecosystem: "github-actions"
|
|
||||||
directory: "/"
|
|
||||||
# Check for updates every Monday
|
|
||||||
schedule:
|
|
||||||
interval: "weekly"
|
|
|
@ -1,16 +1,10 @@
|
||||||
name: Rust CI
|
name: cargo devel CI
|
||||||
on:
|
on:
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- '**'
|
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- '**'
|
- '**'
|
||||||
# - '!master'
|
# - '!master'
|
||||||
|
|
||||||
env:
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
CI:
|
CI:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
@ -37,19 +31,15 @@ jobs:
|
||||||
echo '[registries.cscherr]' >> ~/.cargo/config.toml
|
echo '[registries.cscherr]' >> ~/.cargo/config.toml
|
||||||
echo 'index = "https://git.cscherr.de/PlexSheep/_cargo-index.git"' >> ~/.cargo/config.toml
|
echo 'index = "https://git.cscherr.de/PlexSheep/_cargo-index.git"' >> ~/.cargo/config.toml
|
||||||
cat ~/.cargo/config.toml
|
cat ~/.cargo/config.toml
|
||||||
- name: install additional system dependencies
|
|
||||||
run: sudo apt-get install -y libasound2-dev libdbus-1-dev
|
|
||||||
- name: cargo clippy check
|
- name: cargo clippy check
|
||||||
run: cargo clippy --all-features --all-targets --workspace
|
run: cargo clippy --all-features --all-targets --workspace
|
||||||
- name: cargo clippy fix
|
- name: cargo clippy fix
|
||||||
run: cargo clippy --fix --all-features --all-targets --workspace
|
run: cargo clippy --fix --all-features --all-targets --workspace
|
||||||
- name: cargo fmt
|
- name: cargo fmt
|
||||||
run: cargo fmt --all
|
run: cargo fmt --all
|
||||||
- name: cargo test
|
|
||||||
run: cargo test --all-features --all-targets --workspace
|
|
||||||
- name: commit back to repository
|
- name: commit back to repository
|
||||||
uses: stefanzweifel/git-auto-commit-action@v5
|
uses: stefanzweifel/git-auto-commit-action@v5
|
||||||
with:
|
with:
|
||||||
# Optional. Commit message for the created commit.
|
# Optional. Commit message for the created commit.
|
||||||
# Defaults to "Apply automatic changes"
|
# Defaults to "Apply automatic changes"
|
||||||
commit_message: "ci: automatic Rust CI changes"
|
commit_message: automatic cargo CI changes
|
||||||
|
|
|
@ -1,56 +0,0 @@
|
||||||
name: Release-plz
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
pull-requests: write
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- main
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
|
|
||||||
# Release unpublished packages.
|
|
||||||
release-plz-release:
|
|
||||||
name: Release-plz release
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
- name: Install Rust toolchain
|
|
||||||
uses: dtolnay/rust-toolchain@stable
|
|
||||||
- name: install additional system dependencies
|
|
||||||
run: sudo apt-get install -y libasound2-dev libdbus-1-dev
|
|
||||||
- name: Run release-plz
|
|
||||||
uses: MarcoIeni/release-plz-action@v0.5
|
|
||||||
with:
|
|
||||||
command: release
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
|
||||||
|
|
||||||
# Create a PR with the new versions and changelog, preparing the next release.
|
|
||||||
release-plz-pr:
|
|
||||||
name: Release-plz PR
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
concurrency:
|
|
||||||
group: release-plz-${{ github.ref }}
|
|
||||||
cancel-in-progress: false
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
- name: Install Rust toolchain
|
|
||||||
uses: dtolnay/rust-toolchain@stable
|
|
||||||
- name: Run release-plz
|
|
||||||
uses: MarcoIeni/release-plz-action@v0.5
|
|
||||||
with:
|
|
||||||
command: release-pr
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
|
15
Cargo.toml
15
Cargo.toml
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "crock"
|
name = "crock"
|
||||||
version = "0.3.1"
|
version = "0.1.5"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
publish = true
|
publish = true
|
||||||
authors = ["Christoph J. Scherr <software@cscherr.de>"]
|
authors = ["Christoph J. Scherr <software@cscherr.de>"]
|
||||||
|
@ -12,23 +12,10 @@ repository = "https://git.cscherr.de/PlexSheep/crock"
|
||||||
keywords = ["time", "clock", "tui"]
|
keywords = ["time", "clock", "tui"]
|
||||||
categories = ["date-and-time"]
|
categories = ["date-and-time"]
|
||||||
|
|
||||||
[features]
|
|
||||||
default = ["desktop", "sound"]
|
|
||||||
desktop = ["dep:notify-rust"]
|
|
||||||
sound = ["dep:rodio"]
|
|
||||||
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.86"
|
anyhow = "1.0.86"
|
||||||
chrono = "0.4.38"
|
chrono = "0.4.38"
|
||||||
human-panic = "2.0.0"
|
|
||||||
humantime = "2.1.0"
|
|
||||||
libpt = { version = "0.6.0", features = ["cli"] }
|
libpt = { version = "0.6.0", features = ["cli"] }
|
||||||
notify-rust = { version = "4.11.0", default-features = false, features = [
|
|
||||||
"d",
|
|
||||||
], optional = true }
|
|
||||||
ratatui = "0.27.0"
|
ratatui = "0.27.0"
|
||||||
rodio = { version = "0.19.0", optional = true, default-features = false, features = [
|
|
||||||
"mp3",
|
|
||||||
] }
|
|
||||||
tui-big-text = "0.4.5"
|
tui-big-text = "0.4.5"
|
||||||
|
|
27
README.md
27
README.md
|
@ -2,31 +2,14 @@
|
||||||
|
|
||||||
![Project badge](https://img.shields.io/badge/language-Rust-blue.svg)
|
![Project badge](https://img.shields.io/badge/language-Rust-blue.svg)
|
||||||
![Crates.io License](https://img.shields.io/crates/l/crock)
|
![Crates.io License](https://img.shields.io/crates/l/crock)
|
||||||
![GitHub Release](https://img.shields.io/github/v/release/PlexSheep/crock)
|
![Gitea Release](https://img.shields.io/gitea/v/release/PlexSheep/crock?gitea_url=https%3A%2F%2Fgit.cscherr.de)
|
||||||
![GitHub language count](https://img.shields.io/github/languages/count/PlexSheep/crock)
|
![Gitea language count](https://img.shields.io/gitea/languages/count/PlexSheep/crock?gitea_url=https%3A%2F%2Fgit.cscherr.de)
|
||||||
|
[![cargo checks and tests](https://github.com/PlexSheep/crock/actions/workflows/cargo.yaml/badge.svg)](https://github.com/PlexSheep/crock/actions/workflows/cargo.yaml)
|
||||||
|
|
||||||
A little clock for your terminal, written in rust.
|
A little clock for your terminal, written in rust.
|
||||||
|
|
||||||
![screenshot](data/media/screenshot.png)
|
![screenshot](data/media/screenshot.png)
|
||||||
|
|
||||||
* [GitHub](https://github.com/PlexSheep/crock)
|
* [Original Repository](https://git.cscherr.de/PlexSheep/crock)
|
||||||
|
* [GitHub Mirror](https://github.com/PlexSheep/crock)
|
||||||
* [crates.io](https://crates.io/crates/crock)
|
* [crates.io](https://crates.io/crates/crock)
|
||||||
|
|
||||||
## Compilation
|
|
||||||
|
|
||||||
The `desktop` and `sound` features require additional system dependencies:
|
|
||||||
|
|
||||||
| Feature | Dependency | PKG Name on Debian based Distributions |
|
|
||||||
|-----------|------------|----------------------------------------|
|
|
||||||
| `desktop` | dbus | `libdbus-1-dev` |
|
|
||||||
| `sound` | alsa | `libasound2-dev` |
|
|
||||||
|
|
||||||
If you want to compile without these features, you will not have notifications
|
|
||||||
and sound alerts for countdown mode. (Use `cargo build -r --no-default-features`)
|
|
||||||
|
|
||||||
## Acknoledgements
|
|
||||||
|
|
||||||
The included alarm sound is from [freesound.org](https://freesound.org):
|
|
||||||
|
|
||||||
-> ["effect_notify.wav" by ricemaster (CC-0)](https://freesound.org/people/ricemaster/sounds/278142/)
|
|
||||||
|
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Before Width: | Height: | Size: 8.2 KiB After Width: | Height: | Size: 179 KiB |
447
src/clock.rs
447
src/clock.rs
|
@ -1,229 +1,31 @@
|
||||||
#![warn(clippy::pedantic, clippy::style, clippy::nursery)]
|
#![warn(clippy::pedantic, clippy::style, clippy::nursery)]
|
||||||
// That's useful and sometimes I don't need extra stuff
|
|
||||||
#![allow(clippy::question_mark_used)]
|
#![allow(clippy::question_mark_used)]
|
||||||
// allows us to cast u64 to i64, if the number is too high
|
|
||||||
// enough time has passed that I don't care
|
|
||||||
#![allow(clippy::cast_possible_wrap)]
|
|
||||||
#![allow(clippy::cast_sign_loss)] // it should only be positive anyway
|
|
||||||
|
|
||||||
use chrono::{DateTime, Local, SubsecRound, Timelike};
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use libpt::cli::args::HELP_TEMPLATE;
|
use libpt::cli::{args::VerbosityLevel, args::HELP_TEMPLATE, clap};
|
||||||
use libpt::cli::clap::ArgGroup;
|
|
||||||
use libpt::cli::{args::VerbosityLevel, clap};
|
use chrono::SubsecRound;
|
||||||
use libpt::log::{debug, error, trace};
|
|
||||||
use ratatui::backend::CrosstermBackend;
|
use ratatui::backend::CrosstermBackend;
|
||||||
use ratatui::crossterm::event::{self, poll, Event, KeyCode, KeyModifiers};
|
use ratatui::crossterm::event::{self, poll, Event, KeyCode, KeyModifiers};
|
||||||
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
|
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
|
||||||
use ratatui::style::{Style, Stylize};
|
use ratatui::style::{Style, Stylize};
|
||||||
use ratatui::widgets::{Block, Padding, Paragraph};
|
use ratatui::widgets::{Block, Padding, Paragraph};
|
||||||
use ratatui::Terminal;
|
use ratatui::Terminal;
|
||||||
use std::collections::HashMap;
|
use std::io::Stdout;
|
||||||
use std::io::{Cursor, Stdout, Write};
|
use std::time::Duration;
|
||||||
use std::time::Instant;
|
|
||||||
|
|
||||||
pub mod timebar;
|
|
||||||
pub mod ui;
|
|
||||||
use timebar::TimeBarLength;
|
|
||||||
use ui::Data;
|
|
||||||
|
|
||||||
/// Make your terminal into a big clock
|
/// Make your terminal into a big clock
|
||||||
#[derive(Parser, Debug, Clone)]
|
#[derive(Parser, Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
#[command(help_template = HELP_TEMPLATE, author, version)]
|
#[command(help_template = HELP_TEMPLATE, author, version)]
|
||||||
#[clap(group( ArgGroup::new("timebarlen") .args(&["minute","day", "hour", "custom", "countdown", "timer"]),))]
|
|
||||||
#[allow(clippy::struct_excessive_bools)] // the struct is for cli parsing and we already use an
|
|
||||||
// ArgGroup
|
|
||||||
pub struct Clock {
|
pub struct Clock {
|
||||||
#[command(flatten)]
|
#[command(flatten)]
|
||||||
pub verbose: VerbosityLevel,
|
pub verbose: VerbosityLevel,
|
||||||
/// Show time since start
|
|
||||||
#[clap(short, long)]
|
|
||||||
pub timer: bool,
|
|
||||||
|
|
||||||
// timebar options
|
|
||||||
/// show a time bar that tracks progress of the minute
|
|
||||||
#[clap(short, long)]
|
|
||||||
pub minute: bool,
|
|
||||||
/// show a time bar that tracks progress of the day
|
|
||||||
#[clap(short, long)]
|
|
||||||
pub day: bool,
|
|
||||||
/// show a time bar that tracks progress of the hour
|
|
||||||
#[clap(short = 'o', long)]
|
|
||||||
pub hour: bool,
|
|
||||||
/// show a time bar that tracks progress of a custom duration
|
|
||||||
///
|
|
||||||
/// Precision: only to seconds
|
|
||||||
#[clap(short, long, value_parser = humantime::parse_duration)]
|
|
||||||
pub custom: Option<std::time::Duration>,
|
|
||||||
/// show a time bar that tracks progress of a custom duration without resetting
|
|
||||||
///
|
|
||||||
/// Precision: only to seconds
|
|
||||||
#[clap(short = 'u', long, value_parser = humantime::parse_duration)]
|
|
||||||
pub countdown: Option<std::time::Duration>,
|
|
||||||
/// Play a notification sound when the countdown is up
|
|
||||||
#[cfg(feature = "sound")]
|
|
||||||
#[clap(short, long, default_value_t = true)]
|
|
||||||
pub sound: bool,
|
|
||||||
|
|
||||||
// internal variables
|
|
||||||
#[clap(skip)]
|
|
||||||
pub(crate) last_reset: Option<DateTime<Local>>,
|
|
||||||
#[clap(skip)]
|
|
||||||
pub(crate) did_notify: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Clock {
|
impl Clock {
|
||||||
#[must_use]
|
|
||||||
#[allow(clippy::missing_const_for_fn)]
|
|
||||||
fn timebar_len(&self) -> Option<TimeBarLength> {
|
|
||||||
if self.minute {
|
|
||||||
Some(TimeBarLength::Minute)
|
|
||||||
} else if self.day {
|
|
||||||
Some(TimeBarLength::Day)
|
|
||||||
} else if self.hour {
|
|
||||||
Some(TimeBarLength::Hour)
|
|
||||||
} else if self.timer {
|
|
||||||
Some(TimeBarLength::Timer)
|
|
||||||
} else if self.countdown.is_some() {
|
|
||||||
Some(TimeBarLength::Countup(
|
|
||||||
self.countdown.unwrap().as_secs() as i64
|
|
||||||
))
|
|
||||||
} else if self.custom.is_some() {
|
|
||||||
Some(TimeBarLength::Custom(self.custom.unwrap().as_secs() as i64))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::cast_precision_loss)] // okay, good to know, but I accept the loss. It
|
|
||||||
// shouldn't come to more than 2^52 seconds anyway
|
|
||||||
pub(crate) fn timebar_ratio(&self, current_time: DateTime<Local>) -> Option<f64> {
|
|
||||||
let len = self.timebar_len()?;
|
|
||||||
let since = current_time
|
|
||||||
.signed_duration_since(self.last_reset.unwrap())
|
|
||||||
.num_seconds() as f64;
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
if since < 1.0 {
|
|
||||||
trace!("ratio calculation since is now <1: {:#?}", since);
|
|
||||||
}
|
|
||||||
Some((since / len.as_secs() as f64).clamp(0.0, 1.0))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn maybe_reset_since_zero(&mut self) {
|
|
||||||
if let Some(len) = self.timebar_len() {
|
|
||||||
let since_last_reset = Local::now().signed_duration_since(self.last_reset.unwrap());
|
|
||||||
match len {
|
|
||||||
TimeBarLength::Countup(_) | TimeBarLength::Timer => {
|
|
||||||
// the count up should not reset. If the time is over, just keep it at 100%
|
|
||||||
}
|
|
||||||
TimeBarLength::Custom(_) => {
|
|
||||||
// BUG: this is not consistent, sometimes leads to wrong seconds
|
|
||||||
if since_last_reset.num_milliseconds() >= 100
|
|
||||||
&& since_last_reset.num_seconds() >= len.as_secs()
|
|
||||||
{
|
|
||||||
self.last_reset = Some(Local::now().round_subsecs(0));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
TimeBarLength::Minute => {
|
|
||||||
if since_last_reset.num_seconds() >= 1 && Local::now().second() == 0 {
|
|
||||||
self.last_reset = Some(
|
|
||||||
Local::now()
|
|
||||||
.round_subsecs(0)
|
|
||||||
.with_second(1)
|
|
||||||
.expect("tried to use a time that does not exist"),
|
|
||||||
);
|
|
||||||
debug!("reset the time of the time bar (minute)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
TimeBarLength::Hour => {
|
|
||||||
if since_last_reset.num_minutes() >= 1 && Local::now().minute() == 0 {
|
|
||||||
self.last_reset = Some(
|
|
||||||
Local::now()
|
|
||||||
.round_subsecs(0)
|
|
||||||
.with_second(1)
|
|
||||||
.expect("tried to use a time that does not exist"),
|
|
||||||
);
|
|
||||||
debug!("reset the time of the time bar (hour)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
TimeBarLength::Day => {
|
|
||||||
if since_last_reset.num_hours() >= 1 && Local::now().hour() == 0 {
|
|
||||||
self.last_reset = Some(
|
|
||||||
Local::now()
|
|
||||||
.round_subsecs(0)
|
|
||||||
.with_second(1)
|
|
||||||
.expect("tried to use a time that does not exist"),
|
|
||||||
);
|
|
||||||
debug!("reset the time of the time bar (day)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn setup_last_reset(&mut self) {
|
|
||||||
if let Some(len) = self.timebar_len() {
|
|
||||||
trace!("Local Time: {}", Local::now());
|
|
||||||
match len {
|
|
||||||
TimeBarLength::Custom(_) | TimeBarLength::Countup(_) | TimeBarLength::Timer => {
|
|
||||||
self.last_reset = Some(Local::now());
|
|
||||||
}
|
|
||||||
TimeBarLength::Minute => {
|
|
||||||
self.last_reset = Some(
|
|
||||||
Local::now()
|
|
||||||
.round_subsecs(0)
|
|
||||||
.with_second(1)
|
|
||||||
.expect("tried to use a time that does not exist"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
TimeBarLength::Hour => {
|
|
||||||
self.last_reset = Some(
|
|
||||||
Local::now()
|
|
||||||
.round_subsecs(0)
|
|
||||||
.with_second(1)
|
|
||||||
.expect("tried to use a time that does not exist")
|
|
||||||
.with_minute(0)
|
|
||||||
.expect("tried to use a time that does not exist"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
TimeBarLength::Day => {
|
|
||||||
self.last_reset = Some(
|
|
||||||
Local::now()
|
|
||||||
.round_subsecs(0)
|
|
||||||
.with_second(1)
|
|
||||||
.expect("tried to use a time that does not exist")
|
|
||||||
.with_minute(0)
|
|
||||||
.expect("tried to use a time that does not exist")
|
|
||||||
.with_hour(0)
|
|
||||||
.expect("tried to use a time that does not exist"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
debug!("set up initial last reset as {:#?}", self.last_reset);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::unnecessary_wraps)] // we have that to be future proof
|
|
||||||
pub(crate) fn setup(&mut self) -> anyhow::Result<()> {
|
|
||||||
self.setup_last_reset();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run the clock TUI
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
///
|
|
||||||
/// * The [setup](Self::setup) fails
|
|
||||||
/// * Drawing the [ui](Self::ui) fails
|
|
||||||
/// * Polling or reading an event fails
|
|
||||||
pub(crate) fn run(
|
pub(crate) fn run(
|
||||||
mut self,
|
self,
|
||||||
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
|
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let tick_rate = std::time::Duration::from_millis(100);
|
|
||||||
let mut last_tick = Instant::now();
|
|
||||||
let mut uidata: Data = Data::new(self.timebar_len());
|
|
||||||
self.setup()?;
|
|
||||||
loop {
|
loop {
|
||||||
let raw_time = chrono::Local::now().round_subsecs(0);
|
let raw_time = chrono::Local::now().round_subsecs(0);
|
||||||
let splits: Vec<String> = raw_time
|
let splits: Vec<String> = raw_time
|
||||||
|
@ -232,215 +34,62 @@ impl Clock {
|
||||||
.split_whitespace()
|
.split_whitespace()
|
||||||
.map(str::to_string)
|
.map(str::to_string)
|
||||||
.collect();
|
.collect();
|
||||||
|
let fdate: String = splits[0].clone();
|
||||||
// We somehow fill timebar_ratio with a bad value here if we don't add 1 second. It's
|
let ftime: String = splits[1].clone();
|
||||||
// always the value that would be right for now-1s. The start of the minute is
|
terminal.draw(|frame| {
|
||||||
// special, with this strategy it is 100%. #10
|
let root = frame.size();
|
||||||
//
|
let space = Block::bordered()
|
||||||
// If we manually add a second, it works as expected, but it feels weird. We use the
|
.padding(Padding::new(
|
||||||
// same time for all of the datapoints here, so it can't be because of time diff in
|
root.width / 8,
|
||||||
// calculation. I noticed that we don't start at 0% this way (with len=minute)
|
root.width / 8,
|
||||||
// . Normally, chrono does not include 60 seconds, only letting it range between 0 and
|
root.height / 8,
|
||||||
// 59. This makes sense but feels weird to the human understanding, of course there are
|
root.height / 8,
|
||||||
// seconds in a minute! If we do it this way, we don't quite start at 0%, but 100%,
|
))
|
||||||
// which feels correct.
|
.title(env!("CARGO_PKG_NAME"))
|
||||||
//
|
.title_bottom(env!("CARGO_PKG_VERSION"))
|
||||||
// In short: if we add a second here, we get the correct percentages. 01:00 is 100%,
|
.title_alignment(Alignment::Center)
|
||||||
// 01:30 is 50%, 01:59 is 98%, 01:60 does not exist because that's how counting from
|
.title_style(Style::new().bold());
|
||||||
// 0 works.
|
let a = space.inner(root);
|
||||||
|
let parts = Self::partition(a);
|
||||||
let now = raw_time + chrono::Duration::seconds(1);
|
let timew = tui_big_text::BigText::builder()
|
||||||
uidata.update(
|
.style(Style::new().red())
|
||||||
now,
|
.lines(vec![ftime.into()])
|
||||||
splits[0].clone(),
|
.alignment(Alignment::Center)
|
||||||
splits[1].clone(),
|
.build()
|
||||||
self.timebar_ratio(now),
|
.expect("could not render time widget");
|
||||||
);
|
let datew = Paragraph::new(fdate)
|
||||||
if uidata.changed() {
|
.blue()
|
||||||
self.ui(terminal, &uidata)?;
|
.alignment(Alignment::Left)
|
||||||
}
|
.block(Block::new().padding(Padding::new(
|
||||||
let timeout = tick_rate.saturating_sub(last_tick.elapsed());
|
parts.0.left(),
|
||||||
if poll(timeout)? {
|
parts.0.right() / 3,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
)));
|
||||||
|
frame.render_widget(space, root);
|
||||||
|
frame.render_widget(timew, parts.1);
|
||||||
|
frame.render_widget(datew, parts.0);
|
||||||
|
})?;
|
||||||
|
if poll(Duration::from_millis(100))? {
|
||||||
if let Event::Key(key) = event::read()? {
|
if let Event::Key(key) = event::read()? {
|
||||||
if key.code == KeyCode::Char('q')
|
if key.code == KeyCode::Char('q')
|
||||||
|| key.code == KeyCode::Esc
|
|| key.code == KeyCode::Esc
|
||||||
|| (key.modifiers.contains(KeyModifiers::CONTROL)
|
|| (key.modifiers.contains(KeyModifiers::CONTROL)
|
||||||
&& key.code == KeyCode::Char('c'))
|
&& key.code == KeyCode::Char('c'))
|
||||||
{
|
{
|
||||||
return Ok(());
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if last_tick.elapsed() >= tick_rate {
|
|
||||||
self.on_tick();
|
|
||||||
last_tick = Instant::now();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn on_tick(&mut self) {
|
|
||||||
self.maybe_reset_since_zero();
|
|
||||||
}
|
|
||||||
#[allow(clippy::cast_possible_truncation)] // if we have that much padding, please truncate
|
|
||||||
fn ui(
|
|
||||||
&mut self,
|
|
||||||
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
|
|
||||||
data: &Data,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
terminal.draw(|frame| {
|
|
||||||
debug!("rendering the ui");
|
|
||||||
let root = frame.size();
|
|
||||||
let space = Block::bordered()
|
|
||||||
.padding(Padding::new(
|
|
||||||
root.width / 16,
|
|
||||||
root.width / 16,
|
|
||||||
root.height / 16,
|
|
||||||
root.height / 16,
|
|
||||||
))
|
|
||||||
.title(env!("CARGO_PKG_NAME"))
|
|
||||||
.title_bottom(env!("CARGO_PKG_VERSION"))
|
|
||||||
.title_alignment(Alignment::Center)
|
|
||||||
.title_style(Style::new().bold());
|
|
||||||
let inner_rect = space.inner(root);
|
|
||||||
frame.render_widget(space, root);
|
|
||||||
let parts = Self::partition(inner_rect);
|
|
||||||
|
|
||||||
let mut clockw = tui_big_text::BigText::builder();
|
|
||||||
if inner_rect.width > 80 {
|
|
||||||
clockw.pixel_size(tui_big_text::PixelSize::Full);
|
|
||||||
} else {
|
|
||||||
clockw.pixel_size(tui_big_text::PixelSize::Quadrant);
|
|
||||||
}
|
|
||||||
|
|
||||||
let clockw = clockw
|
|
||||||
.style(Style::new().red())
|
|
||||||
.lines(vec![data.ftime().into()])
|
|
||||||
.alignment(Alignment::Center)
|
|
||||||
.build()
|
|
||||||
.expect("could not render time widget");
|
|
||||||
|
|
||||||
// render the timebar which counts up to the full minute and so on
|
|
||||||
//
|
|
||||||
// Will not be rendered if it is None
|
|
||||||
let timebarw_padding = [
|
|
||||||
(f32::from(parts["timebarw"].width) * 0.43) as u16,
|
|
||||||
(f32::from(parts["timebarw"].width) * 0.25) as u16,
|
|
||||||
];
|
|
||||||
let timebarw = ui::timebarw(self, data, &timebarw_padding, inner_rect);
|
|
||||||
let timebarw_label: Option<Paragraph> =
|
|
||||||
ui::timebarw_label(self, data, &timebarw_padding, inner_rect);
|
|
||||||
|
|
||||||
// render the small date
|
|
||||||
let datew = Paragraph::new(data.fdate())
|
|
||||||
.blue()
|
|
||||||
.block(Block::default().padding(Padding::right(2)))
|
|
||||||
.alignment(Alignment::Right);
|
|
||||||
frame.render_widget(&timebarw, parts["timebarw"]);
|
|
||||||
frame.render_widget(&timebarw_label, parts["timebarw_label"]);
|
|
||||||
frame.render_widget(datew, parts["datew"]);
|
|
||||||
// render the clock
|
|
||||||
frame.render_widget(clockw, parts["clockw"]);
|
|
||||||
})?;
|
|
||||||
debug!("done rendering the ui");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
fn notify(&mut self) -> anyhow::Result<()> {
|
|
||||||
Self::beep()?;
|
|
||||||
#[cfg(feature = "sound")]
|
|
||||||
if self.sound {
|
|
||||||
std::thread::spawn(|| {
|
|
||||||
use rodio::{Decoder, OutputStream, Sink};
|
|
||||||
// only 30 KiB, so let's just include it in the binary and not worry about reading it
|
|
||||||
// from the fs and somehow making the file be there
|
|
||||||
const SOUND_RAW: &[u8] = include_bytes!("../data/media/alarm.mp3");
|
|
||||||
|
|
||||||
trace!("playing bundled sound");
|
|
||||||
|
|
||||||
let sound_data: Cursor<_> = std::io::Cursor::new(SOUND_RAW);
|
|
||||||
|
|
||||||
let (_stream, stream_handle) = OutputStream::try_default().unwrap();
|
|
||||||
let sink = Sink::try_new(&stream_handle).unwrap();
|
|
||||||
sink.append(
|
|
||||||
Decoder::new(sound_data).expect("could not decode the bundled alarm sound"),
|
|
||||||
);
|
|
||||||
sink.sleep_until_end();
|
|
||||||
|
|
||||||
debug!("played bundled sound");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
#[cfg(feature = "desktop")]
|
|
||||||
{
|
|
||||||
let mut notify = notify_rust::Notification::new();
|
|
||||||
|
|
||||||
notify.appname(env!("CARGO_BIN_NAME"));
|
|
||||||
|
|
||||||
// see [FreeDesktop Sound Naming Specification](http://0pointer.de/public/sound-naming-spec.html)
|
|
||||||
// a sound exists for our use-case
|
|
||||||
//
|
|
||||||
// NOTE: sadly, notify_rust does not (yet) support KDE plasma, because
|
|
||||||
// they have a weird way of making sounds and notifications in general
|
|
||||||
// work. At least we get a little notification.
|
|
||||||
|
|
||||||
// only play this when we don't use built in sound, this
|
|
||||||
// isn't as consistent
|
|
||||||
#[cfg(not(feature = "sound"))]
|
|
||||||
notify.sound_name("alarm-clock-elapsed");
|
|
||||||
|
|
||||||
// The user sets the time with the expectation to be notified, but it's
|
|
||||||
// not like the moon is crashing into the earth
|
|
||||||
notify.urgency(notify_rust::Urgency::Normal);
|
|
||||||
|
|
||||||
// We don't need to have it be displayed for ever, the TUI shows that the time is up
|
|
||||||
// (100%) already.
|
|
||||||
notify.timeout(notify_rust::Timeout::Default);
|
|
||||||
|
|
||||||
notify.summary(&format!(
|
|
||||||
"Your countdown of {} is up.",
|
|
||||||
humantime::Duration::from(self.countdown.unwrap())
|
|
||||||
));
|
|
||||||
// NOTE: this will only work on machines with a proper desktop, not
|
|
||||||
// with things like WSL2 or a docker container. Therefore, it is behind
|
|
||||||
// the desktop feature.
|
|
||||||
let _ = notify.show().inspect_err(|e| {
|
|
||||||
error!("could not notify of finished countup: {e}");
|
|
||||||
debug!(": {e:#?}");
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
fn beep() -> anyhow::Result<()> {
|
fn partition(r: Rect) -> (Rect, Rect) {
|
||||||
print!("\x07");
|
|
||||||
std::io::stdout().flush()?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
fn partition(r: Rect) -> HashMap<&'static str, Rect> {
|
|
||||||
let part = Layout::default()
|
let part = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints([
|
.constraints([Constraint::Percentage(13), Constraint::Min(0)])
|
||||||
Constraint::Length(3),
|
|
||||||
Constraint::Length(if r.width > 80 { 8 } else { 5 }),
|
|
||||||
])
|
|
||||||
.split(r);
|
.split(r);
|
||||||
#[allow(clippy::cast_sign_loss)]
|
|
||||||
#[allow(clippy::cast_possible_truncation)]
|
|
||||||
let hlen_date: u16 = (f32::from(part[1].width) * 0.32) as u16;
|
|
||||||
let subparts = Layout::default()
|
|
||||||
.direction(Direction::Horizontal)
|
|
||||||
.constraints([
|
|
||||||
Constraint::Length(hlen_date),
|
|
||||||
Constraint::Length(part[0].width - hlen_date),
|
|
||||||
])
|
|
||||||
.split(part[0]);
|
|
||||||
|
|
||||||
let timebarw_spaces = Layout::default()
|
(part[0], part[1])
|
||||||
.direction(Direction::Vertical)
|
|
||||||
.constraints([Constraint::Length(1), Constraint::Length(1)])
|
|
||||||
.split(subparts[1]);
|
|
||||||
|
|
||||||
HashMap::from([
|
|
||||||
("clockw", part[1]),
|
|
||||||
("timebarw", timebarw_spaces[0]),
|
|
||||||
("timebarw_label", timebarw_spaces[1]),
|
|
||||||
("datew", subparts[0]),
|
|
||||||
])
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,71 +0,0 @@
|
||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
use chrono::Duration;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum TimeBarLength {
|
|
||||||
Timer,
|
|
||||||
Minute,
|
|
||||||
Hour,
|
|
||||||
Custom(i64),
|
|
||||||
/// implementing a bar that would grow smaller would be weird, so it's a count up instead of
|
|
||||||
/// a countdown
|
|
||||||
Countup(i64),
|
|
||||||
Day,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TimeBarLength {
|
|
||||||
pub(crate) const fn as_secs(self) -> i64 {
|
|
||||||
match self {
|
|
||||||
Self::Minute => 60,
|
|
||||||
Self::Day => 24 * 60 * 60,
|
|
||||||
Self::Hour => 60 * 60,
|
|
||||||
Self::Timer => 1,
|
|
||||||
Self::Custom(secs) | Self::Countup(secs) => secs,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<TimeBarLength> for chrono::Duration {
|
|
||||||
fn from(value: TimeBarLength) -> Self {
|
|
||||||
Self::new(value.as_secs(), 0).expect("seconds out of bounds, cannot create duration")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for TimeBarLength {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::Minute
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for TimeBarLength {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
if *self == Self::Timer {
|
|
||||||
return write!(f, "");
|
|
||||||
}
|
|
||||||
let buf = match self {
|
|
||||||
Self::Minute => humantime::Duration::from(
|
|
||||||
Duration::minutes(1)
|
|
||||||
.to_std()
|
|
||||||
.expect("could not convert chrono time to std time"),
|
|
||||||
),
|
|
||||||
Self::Hour => humantime::Duration::from(
|
|
||||||
Duration::hours(1)
|
|
||||||
.to_std()
|
|
||||||
.expect("could not convert chrono time to std time"),
|
|
||||||
),
|
|
||||||
Self::Day => humantime::Duration::from(
|
|
||||||
Duration::days(1)
|
|
||||||
.to_std()
|
|
||||||
.expect("could not convert chrono time to std time"),
|
|
||||||
),
|
|
||||||
Self::Custom(secs) | Self::Countup(secs) => humantime::Duration::from(
|
|
||||||
Duration::seconds(*secs)
|
|
||||||
.to_std()
|
|
||||||
.expect("could not convert chrono time to std time"),
|
|
||||||
),
|
|
||||||
Self::Timer => unreachable!(),
|
|
||||||
};
|
|
||||||
write!(f, "{buf}")
|
|
||||||
}
|
|
||||||
}
|
|
221
src/clock/ui.rs
221
src/clock/ui.rs
|
@ -1,221 +0,0 @@
|
||||||
use chrono::{DateTime, Local, SubsecRound, Timelike};
|
|
||||||
use libpt::log::{debug, error, trace};
|
|
||||||
use ratatui::layout::{Alignment, Rect};
|
|
||||||
use ratatui::style::{Style, Stylize};
|
|
||||||
use ratatui::widgets::{Block, LineGauge, Padding, Paragraph};
|
|
||||||
|
|
||||||
use crate::clock::timebar::TimeBarLength;
|
|
||||||
|
|
||||||
use super::Clock;
|
|
||||||
|
|
||||||
pub const TIME_FORMAT: &str = "%H:%M:%S";
|
|
||||||
pub const TIME_FORMAT_SHORT: &str = "%H:%M";
|
|
||||||
|
|
||||||
// TODO: make this a ringbuffer with a custom struct inside?
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct Data {
|
|
||||||
now: [DateTime<Local>; 2],
|
|
||||||
fdate: [String; 2],
|
|
||||||
ftime: [String; 2],
|
|
||||||
timebar_ratio: [Option<f64>; 2],
|
|
||||||
|
|
||||||
timebar_type: Option<TimeBarLength>,
|
|
||||||
started_at: DateTime<Local>,
|
|
||||||
|
|
||||||
idx: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Data {
|
|
||||||
pub fn new(timebar_type: Option<TimeBarLength>) -> Self {
|
|
||||||
let mut this = Self {
|
|
||||||
now: [DateTime::default(); 2],
|
|
||||||
fdate: [String::new(), String::new()],
|
|
||||||
ftime: [String::new(), String::new()],
|
|
||||||
timebar_ratio: [Option::default(); 2],
|
|
||||||
started_at: Local::now(),
|
|
||||||
idx: usize::default(),
|
|
||||||
|
|
||||||
timebar_type,
|
|
||||||
};
|
|
||||||
this.started_at = this.started_at.round_subsecs(0);
|
|
||||||
this
|
|
||||||
}
|
|
||||||
pub fn update(
|
|
||||||
&mut self,
|
|
||||||
now: DateTime<Local>,
|
|
||||||
fdate: String,
|
|
||||||
ftime: String,
|
|
||||||
timebar_ratio: Option<f64>,
|
|
||||||
) {
|
|
||||||
self.idx ^= 1;
|
|
||||||
self.now[self.idx] = now;
|
|
||||||
self.fdate[self.idx] = fdate;
|
|
||||||
self.ftime[self.idx] = ftime;
|
|
||||||
self.timebar_ratio[self.idx] = timebar_ratio;
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
if self.changed() {
|
|
||||||
trace!("update with change: {:#?}", self);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// did the data change with the last update?
|
|
||||||
#[must_use]
|
|
||||||
#[inline]
|
|
||||||
pub fn changed(&self) -> bool {
|
|
||||||
// the timebar ratio is discarded, so that we only render the ui when the time
|
|
||||||
// (second) changes
|
|
||||||
self.fdate[0] != self.fdate[1] || self.ftime[0] != self.ftime[1]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
#[inline]
|
|
||||||
pub fn fdate(&self) -> &str {
|
|
||||||
&self.fdate[self.idx]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
#[inline]
|
|
||||||
pub fn ftime(&self) -> &str {
|
|
||||||
&self.ftime[self.idx]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
#[inline]
|
|
||||||
#[allow(clippy::missing_const_for_fn)] // why should it be okay to make this const? This is
|
|
||||||
// a custom ringbuffer!
|
|
||||||
pub fn now(&self) -> &DateTime<Local> {
|
|
||||||
&self.now[self.idx]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
#[inline]
|
|
||||||
#[allow(clippy::missing_const_for_fn)] // no it's not const
|
|
||||||
pub fn timebar_ratio(&self) -> Option<f64> {
|
|
||||||
if self.timebar_type.is_some() && self.timebar_type.unwrap() == TimeBarLength::Timer {
|
|
||||||
return Some(0.0);
|
|
||||||
}
|
|
||||||
self.timebar_ratio[self.idx]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn timebarw<'a>(
|
|
||||||
clock: &mut Clock,
|
|
||||||
data: &Data,
|
|
||||||
timebarw_padding: &[u16],
|
|
||||||
inner_rect: Rect,
|
|
||||||
) -> Option<LineGauge<'a>> {
|
|
||||||
if clock.timebar_len().is_some() {
|
|
||||||
debug!("time bar ration: {:?}", data.timebar_ratio());
|
|
||||||
let ratio = data.timebar_ratio().unwrap();
|
|
||||||
|
|
||||||
if !clock.did_notify && (ratio - 1.0).abs() < 0.000_001 {
|
|
||||||
if let Some(TimeBarLength::Countup(_)) = clock.timebar_len() {
|
|
||||||
let _ = clock.notify().inspect_err(|e| {
|
|
||||||
error!("could not notify: {e}");
|
|
||||||
debug!("complete error: {e:#?}");
|
|
||||||
});
|
|
||||||
clock.did_notify = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::cast_sign_loss)]
|
|
||||||
#[allow(clippy::cast_possible_truncation)]
|
|
||||||
let timebarw = LineGauge::default()
|
|
||||||
.filled_style(if clock.did_notify {
|
|
||||||
Style::default()
|
|
||||||
.slow_blink()
|
|
||||||
.bold()
|
|
||||||
.underlined()
|
|
||||||
.yellow()
|
|
||||||
.crossed_out()
|
|
||||||
} else {
|
|
||||||
Style::default().blue()
|
|
||||||
})
|
|
||||||
.unfilled_style(Style::default())
|
|
||||||
.block(
|
|
||||||
Block::default().padding(Padding::right(if inner_rect.width > 80 {
|
|
||||||
timebarw_padding[0]
|
|
||||||
} else {
|
|
||||||
timebarw_padding[1]
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.ratio(ratio);
|
|
||||||
Some(timebarw)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn timebarw_label<'a>(
|
|
||||||
clock: &Clock,
|
|
||||||
data: &Data,
|
|
||||||
timebarw_padding: &[u16],
|
|
||||||
inner_rect: Rect,
|
|
||||||
) -> Option<Paragraph<'a>> {
|
|
||||||
clock.timebar_len().map(|len| {
|
|
||||||
let last_reset = clock.last_reset.unwrap().round_subsecs(0);
|
|
||||||
let time_now = match clock.timebar_len().unwrap() {
|
|
||||||
TimeBarLength::Countup(secs) => {
|
|
||||||
if clock.did_notify {
|
|
||||||
humantime::Duration::from(chrono::Duration::seconds(secs).to_std().unwrap())
|
|
||||||
} else {
|
|
||||||
humantime::Duration::from(
|
|
||||||
data.now()
|
|
||||||
.round_subsecs(0)
|
|
||||||
.signed_duration_since(last_reset)
|
|
||||||
.to_std()
|
|
||||||
.unwrap(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
TimeBarLength::Hour => humantime::Duration::from(
|
|
||||||
data.now()
|
|
||||||
.signed_duration_since(last_reset)
|
|
||||||
.to_std()
|
|
||||||
.unwrap(),
|
|
||||||
),
|
|
||||||
_ => humantime::Duration::from(
|
|
||||||
data.now()
|
|
||||||
.round_subsecs(0)
|
|
||||||
.signed_duration_since(last_reset)
|
|
||||||
.to_std()
|
|
||||||
.unwrap(),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
let until = {
|
|
||||||
// we need to cut off the seconds if we're not in custom and countup mode, otherwise,
|
|
||||||
// the timestamp will not be correct. This fixes #17
|
|
||||||
match len {
|
|
||||||
TimeBarLength::Custom(_) | TimeBarLength::Countup(_) => last_reset,
|
|
||||||
_ => last_reset.with_second(0).unwrap(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// BUG: seconds are sometimes a little too much, for
|
|
||||||
// example with `-o` #17
|
|
||||||
.checked_add_signed(len.into())
|
|
||||||
.expect("could not calculate when the countdown finishes")
|
|
||||||
.format(TIME_FORMAT_SHORT);
|
|
||||||
|
|
||||||
let text: String = match clock.timebar_len().unwrap() {
|
|
||||||
TimeBarLength::Timer => format!("{} + {time_now}", data.started_at.format(TIME_FORMAT)),
|
|
||||||
TimeBarLength::Countup(_) | TimeBarLength::Custom(_) => format!(
|
|
||||||
"{time_now} / {len} | {} -> {until}",
|
|
||||||
last_reset.format(TIME_FORMAT_SHORT)
|
|
||||||
),
|
|
||||||
_ => format!(
|
|
||||||
"{time_now} / {len} | {} -> {until}",
|
|
||||||
last_reset.with_second(0).unwrap().format(TIME_FORMAT_SHORT)
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
Paragraph::new(text)
|
|
||||||
.alignment(Alignment::Center)
|
|
||||||
.block(
|
|
||||||
Block::default().padding(Padding::right(if inner_rect.width > 80 {
|
|
||||||
timebarw_padding[0]
|
|
||||||
} else {
|
|
||||||
timebarw_padding[1]
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
64
src/main.rs
64
src/main.rs
|
@ -1,9 +1,6 @@
|
||||||
#![allow(missing_docs)] // this is not a library crate
|
|
||||||
|
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
use libpt::cli::clap::Parser;
|
use libpt::cli::clap::Parser;
|
||||||
use libpt::log::{debug, Level, Logger};
|
|
||||||
use ratatui::backend::CrosstermBackend;
|
use ratatui::backend::CrosstermBackend;
|
||||||
use ratatui::crossterm::event::{DisableMouseCapture, EnableMouseCapture};
|
use ratatui::crossterm::event::{DisableMouseCapture, EnableMouseCapture};
|
||||||
use ratatui::crossterm::execute;
|
use ratatui::crossterm::execute;
|
||||||
|
@ -17,31 +14,9 @@ use self::clock::Clock;
|
||||||
mod clock;
|
mod clock;
|
||||||
|
|
||||||
fn main() -> anyhow::Result<()> {
|
fn main() -> anyhow::Result<()> {
|
||||||
human_panic::setup_panic!(human_panic::Metadata::new(
|
|
||||||
env!("CARGO_BIN_NAME"),
|
|
||||||
env!("CARGO_PKG_VERSION")
|
|
||||||
)
|
|
||||||
.authors(env!("CARGO_PKG_AUTHORS"))
|
|
||||||
.homepage(env!("CARGO_PKG_HOMEPAGE")));
|
|
||||||
|
|
||||||
// setup the cli
|
// setup the cli
|
||||||
let clock = Clock::parse();
|
let clock = Clock::parse();
|
||||||
if clock.verbose.level() >= Level::DEBUG {
|
|
||||||
let _logger = Logger::builder()
|
|
||||||
.log_to_file(true)
|
|
||||||
.log_dir("/tmp/crock/".into())
|
|
||||||
.set_level(clock.verbose.level())
|
|
||||||
.display_time(true)
|
|
||||||
.build()?;
|
|
||||||
} else {
|
|
||||||
// no logger
|
|
||||||
}
|
|
||||||
debug!("set up logger");
|
|
||||||
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
mock_tests();
|
|
||||||
|
|
||||||
debug!("taking over terminal");
|
|
||||||
// setup terminal
|
// setup terminal
|
||||||
enable_raw_mode()?;
|
enable_raw_mode()?;
|
||||||
let mut stdout = io::stdout();
|
let mut stdout = io::stdout();
|
||||||
|
@ -49,10 +24,8 @@ fn main() -> anyhow::Result<()> {
|
||||||
let backend = CrosstermBackend::new(stdout);
|
let backend = CrosstermBackend::new(stdout);
|
||||||
let mut terminal = Terminal::new(backend)?;
|
let mut terminal = Terminal::new(backend)?;
|
||||||
|
|
||||||
debug!("entering clock");
|
|
||||||
let result = clock.run(&mut terminal);
|
let result = clock.run(&mut terminal);
|
||||||
|
|
||||||
debug!("restoring terminal");
|
|
||||||
// restore terminal
|
// restore terminal
|
||||||
disable_raw_mode()?;
|
disable_raw_mode()?;
|
||||||
execute!(
|
execute!(
|
||||||
|
@ -62,42 +35,5 @@ fn main() -> anyhow::Result<()> {
|
||||||
)?;
|
)?;
|
||||||
terminal.show_cursor()?;
|
terminal.show_cursor()?;
|
||||||
|
|
||||||
debug!("done");
|
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
#[allow(clippy::cast_precision_loss)]
|
|
||||||
fn mock_tests() {
|
|
||||||
use chrono::{Local, Timelike};
|
|
||||||
use libpt::log::info;
|
|
||||||
|
|
||||||
use crate::clock::ui::Data;
|
|
||||||
info!("doing the mock tests");
|
|
||||||
{
|
|
||||||
let mut c = Clock::parse_from(["some exec", "-mvvv"]);
|
|
||||||
let now = Local::now();
|
|
||||||
c.last_reset = Some(now.with_second(0).unwrap());
|
|
||||||
|
|
||||||
assert_eq!(c.timebar_ratio(now.with_second(30).unwrap()), Some(0.5));
|
|
||||||
info!("30s=0.5");
|
|
||||||
assert_eq!(
|
|
||||||
c.timebar_ratio(now.with_second(59).unwrap()),
|
|
||||||
Some(0.9833333333333333)
|
|
||||||
);
|
|
||||||
info!("60s=1.0");
|
|
||||||
assert_eq!(c.timebar_ratio(now.with_second(0).unwrap()), Some(0.0));
|
|
||||||
info!("0s=0.0");
|
|
||||||
}
|
|
||||||
{
|
|
||||||
let mut data = Data::new(None);
|
|
||||||
let now = Local::now();
|
|
||||||
data.update(now, "date".to_owned(), "time".to_owned(), Some(0.1));
|
|
||||||
assert_eq!(data.timebar_ratio(), Some(0.1));
|
|
||||||
data.update(now, "date".to_owned(), "time".to_owned(), Some(0.2));
|
|
||||||
assert_eq!(data.timebar_ratio(), Some(0.2));
|
|
||||||
data.update(now, "date".to_owned(), "time".to_owned(), Some(0.3));
|
|
||||||
assert_eq!(data.timebar_ratio(), Some(0.3));
|
|
||||||
}
|
|
||||||
info!("finished the mock tests");
|
|
||||||
}
|
|
||||||
|
|
Reference in New Issue