Compare commits

..

44 Commits

Author SHA1 Message Date
Christoph J. Scherr a7ba7f9e34 docs: admit that this is a github project now 2024-10-16 21:21:19 +02:00
Christoph J. Scherr 74f1df69c2 chore: bump version to v0.3.1 2024-10-16 20:48:31 +02:00
Christoph J. Scherr bd801282f2 chore: add system deps to release cd for compilation 2024-10-16 20:42:37 +02:00
Christoph J. Scherr cf4e8b6011 Merge branch 'devel'
Rust CI / cargo CI (push) Has been cancelled Details
Release-plz / Release-plz release (push) Has been cancelled Details
Release-plz / Release-plz PR (push) Has been cancelled Details
2024-10-16 20:40:38 +02:00
Christoph J. Scherr b0c605452a chore: add system deps for ci
Rust CI / cargo CI (push) Waiting to run Details
Release-plz / Release-plz release (push) Waiting to run Details
Release-plz / Release-plz PR (push) Waiting to run Details
2024-10-16 20:36:29 +02:00
Christoph J. Scherr 18135c15d7 Merge branch 'master' into devel
Rust CI / cargo CI (push) Has been cancelled Details
2024-10-16 20:31:30 +02:00
Christoph J. Scherr 4a9eac6091 chore: change ci/cd to use github and deploy with cd from now
Rust CI / cargo CI (push) Waiting to run Details
Release-plz / Release-plz release (push) Waiting to run Details
Release-plz / Release-plz PR (push) Waiting to run Details
2024-10-16 20:29:26 +02:00
Christoph J. Scherr 757fe6b7b2 chore: bump to v0.3.1-alpha.0
cargo devel CI / cargo CI (push) Successful in 1m45s Details
2024-09-05 11:38:02 +02:00
Christoph J. Scherr 140123c124 fix: crashed when no timebar was requested because we unwrapped for the creation of Ui Data #26
cargo devel CI / cargo CI (push) Has been cancelled Details
2024-09-05 11:35:51 +02:00
Christoph J. Scherr 04c570243c fix(timebar): shortened format and refactored
cargo devel CI / cargo CI (push) Successful in 1m43s Details
2024-09-03 20:39:08 +02:00
Christoph J. Scherr 89a636589d chore: some more clippy findings
cargo devel CI / cargo CI (push) Successful in 1m47s Details
2024-09-03 19:16:25 +02:00
Christoph J. Scherr 2f306304b3 chore: clippy findings
cargo devel CI / cargo CI (push) Successful in 1m44s Details
2024-09-03 19:14:34 +02:00
Christoph J. Scherr 23a417a9f9 chore: bump version
cargo devel CI / cargo CI (push) Has been cancelled Details
2024-09-03 19:13:28 +02:00
Christoph J. Scherr 1b07e481f2 feat(timebar)!: add timer and add additional information to the ui #22
cargo devel CI / cargo CI (push) Has been cancelled Details
2024-09-03 19:13:13 +02:00
Christoph J. Scherr 12efcf45a8 Merge branch 'master' into devel
cargo devel CI / cargo CI (push) Successful in 1m43s Details
2024-07-26 10:57:03 +02:00
Christoph J. Scherr 80b466efdf chore: address clippy findings
cargo devel CI / cargo CI (push) Successful in 1m45s Details
2024-07-26 10:52:33 +02:00
Christoph J. Scherr 0853ee103b chore: bump to v0.2.1, v0.2.2 was too early oopsie
cargo devel CI / cargo CI (push) Successful in 1m47s Details
2024-07-26 10:46:17 +02:00
Christoph J. Scherr e940c4bfb4 docs: update screenshot
cargo devel CI / cargo CI (push) Has been cancelled Details
2024-07-26 10:44:41 +02:00
Christoph J. Scherr 77020571f8 docs: update screenshot
cargo devel CI / cargo CI (push) Successful in 1m57s Details
2024-07-26 10:44:32 +02:00
cscherrNT 3c9cf84f1a Merge pull request 'add mode show and fix some things' (#20) from devel into master
cargo devel CI / cargo CI (push) Has been cancelled Details
Reviewed-on: #20
2024-07-26 10:43:19 +02:00
Christoph J. Scherr 4d12f268d9 chore: bump version to v0.2.2
cargo devel CI / cargo CI (push) Has been cancelled Details
2024-07-26 10:42:57 +02:00
cscherrNT 28d149db42 automatic cargo CI changes 2024-07-26 08:40:32 +00:00
Christoph J. Scherr 4957c601ea fix(modeshow): display correct durations for hour,minute,day #19
cargo devel CI / cargo CI (push) Successful in 1m58s Details
2024-07-26 10:38:37 +02:00
Christoph J. Scherr 19c1939cfb fix(modeshow): fix #17 by conditionally setting the seconds to 0
cargo devel CI / cargo CI (push) Successful in 1m47s Details
2024-07-19 10:26:45 +02:00
Christoph J. Scherr 48f88ee17e feat(panic): add human_panic
cargo devel CI / cargo CI (push) Successful in 1m48s Details
2024-07-19 10:16:22 +02:00
cscherrNT 71f887c62e Merge pull request 'show mode of timebar with extra info' (#18) from feat/mode-show into devel
cargo devel CI / cargo CI (push) Successful in 1m44s Details
Reviewed-on: #18
2024-07-19 10:06:08 +02:00
Christoph J. Scherr b0d0651cc7 chore: bump alpha version
cargo devel CI / cargo CI (push) Successful in 1m45s Details
2024-07-19 10:03:33 +02:00
Christoph J. Scherr 01c3f44026 fix(modeshow): force all segments of the time to have 2 digits
cargo devel CI / cargo CI (push) Successful in 1m47s Details
2024-07-19 10:01:11 +02:00
Christoph J. Scherr 2526771026 refactor(uidata): change name of the struct and the idx 2024-07-19 10:01:11 +02:00
Christoph J. Scherr 4ec8be1e1b chore: add bug comment for #17 2024-07-19 10:01:11 +02:00
Christoph J. Scherr 3a4c3d7c00 feat(modeshow): add a timestamp that shows when the timer ends #14 2024-07-19 10:01:11 +02:00
Christoph J. Scherr 19cc0d5d1a chore: bump version to alpha
cargo devel CI / cargo CI (push) Successful in 1m46s Details
2024-07-17 17:52:35 +02:00
cscherrNT 290704de46 automatic cargo CI changes 2024-07-17 15:48:15 +00:00
Christoph J. Scherr 74e39a08dc feat(timebar): show mode and counter for timebar
cargo devel CI / cargo CI (push) Successful in 1m58s Details
2024-07-17 17:46:22 +02:00
Christoph J. Scherr 700f236649 refactor: partition to a HashMap instead of a Vec
cargo devel CI / cargo CI (push) Successful in 1m52s Details
2024-07-17 16:50:32 +02:00
Christoph J. Scherr d6102dffa2 refactor: move clock parts to submodules
cargo devel CI / cargo CI (push) Successful in 1m51s Details
2024-07-17 16:30:39 +02:00
Christoph J. Scherr 27d135b1c8 chore: remove an old todo comment
cargo devel CI / cargo CI (push) Successful in 1m47s Details
2024-07-12 19:25:16 +02:00
Christoph J. Scherr 6863448974 chore: address clippy findings 2024-07-12 19:25:08 +02:00
Christoph J. Scherr d62fd468ff refactor: hide the sound option behind the sound feature
cargo devel CI / cargo CI (push) Successful in 1m43s Details
2024-07-12 19:15:58 +02:00
Christoph J. Scherr daa764cb96 feat(notify): make sound be on by default #15 2024-07-12 19:15:14 +02:00
Christoph J. Scherr 3056e4fa36 chore: git merge shenanigans
cargo devel CI / cargo CI (push) Has been cancelled Details
2024-07-12 19:14:12 +02:00
Christoph J. Scherr de3954a1bb chore: update screenshot
cargo devel CI / cargo CI (push) Failing after 1m41s Details
2024-07-12 19:07:23 +02:00
Christoph J. Scherr 4de8e35f41 Merge branch 'devel'
cargo devel CI / cargo CI (push) Failing after 1m48s Details
2024-07-12 19:05:53 +02:00
Christoph J. Scherr 35e58ffea8 chore: bump version
cargo devel CI / cargo CI (push) Successful in 1m16s Details
2024-07-10 01:41:11 +02:00
10 changed files with 483 additions and 167 deletions

7
.github/dependabot.yaml vendored Normal file
View File

@ -0,0 +1,7 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
# Check for updates every Monday
schedule:
interval: "weekly"

View File

@ -1,12 +1,19 @@
name: cargo devel CI
name: Rust CI
on:
pull_request:
branches:
- '**'
push:
branches:
- '**'
# - '!master'
env:
CARGO_TERM_COLOR: always
jobs:
format:
CI:
runs-on: ubuntu-latest
name: cargo CI
permissions:
# Give the default GITHUB_TOKEN write permission to commit and push the
@ -16,15 +23,11 @@ jobs:
- name: get repo
uses: actions/checkout@v4
- name: install rust
uses: https://github.com/dtolnay/rust-toolchain@stable
uses: dtolnay/rust-toolchain@stable
- name: install additional rust things
run: |
rustup component add rustfmt
rustup component add clippy
- name: install additional system dependencies
run: |
apt update
apt install libdbus-1-dev libasound2-dev -y
- name: config custom registry
run: |
mkdir -p ~/.cargo/
@ -34,15 +37,19 @@ jobs:
echo '[registries.cscherr]' >> ~/.cargo/config.toml
echo 'index = "https://git.cscherr.de/PlexSheep/_cargo-index.git"' >> ~/.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
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: cargo test
run: cargo test --all-features --all-targets --workspace
- name: commit back to repository
uses: https://github.com/stefanzweifel/git-auto-commit-action@v5
uses: 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
commit_message: "ci: automatic Rust CI changes"

56
.github/workflows/release.yaml vendored Normal file
View File

@ -0,0 +1,56 @@
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 }}

View File

@ -1,6 +1,6 @@
[package]
name = "crock"
version = "0.2.0"
version = "0.3.1"
edition = "2021"
publish = true
authors = ["Christoph J. Scherr <software@cscherr.de>"]
@ -21,6 +21,7 @@ sound = ["dep:rodio"]
[dependencies]
anyhow = "1.0.86"
chrono = "0.4.38"
human-panic = "2.0.0"
humantime = "2.1.0"
libpt = { version = "0.6.0", features = ["cli"] }
notify-rust = { version = "4.11.0", default-features = false, features = [

View File

@ -2,15 +2,15 @@
![Project badge](https://img.shields.io/badge/language-Rust-blue.svg)
![Crates.io License](https://img.shields.io/crates/l/crock)
![Gitea Release](https://img.shields.io/gitea/v/release/PlexSheep/crock?gitea_url=https%3A%2F%2Fgit.cscherr.de)
![Gitea language count](https://img.shields.io/gitea/languages/count/PlexSheep/crock?gitea_url=https%3A%2F%2Fgit.cscherr.de)
![GitHub Release](https://img.shields.io/github/v/release/PlexSheep/crock)
![GitHub language count](https://img.shields.io/github/languages/count/PlexSheep/crock)
A little clock for your terminal, written in rust.
![screenshot](data/media/screenshot.png)
* [Original Repository](https://git.cscherr.de/PlexSheep/crock)
* [GitHub Mirror](https://github.com/PlexSheep/crock)
* [GitHub](https://github.com/PlexSheep/crock)
* [crates.io](https://crates.io/crates/crock)
## Compilation

Binary file not shown.

Before

Width:  |  Height:  |  Size: 179 KiB

After

Width:  |  Height:  |  Size: 8.2 KiB

View File

@ -1,5 +1,10 @@
#![warn(clippy::pedantic, clippy::style, clippy::nursery)]
// That's useful and sometimes I don't need extra stuff
#![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;
@ -11,43 +16,21 @@ use ratatui::backend::CrosstermBackend;
use ratatui::crossterm::event::{self, poll, Event, KeyCode, KeyModifiers};
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Style, Stylize};
use ratatui::widgets::{Block, LineGauge, Padding, Paragraph};
use ratatui::widgets::{Block, Padding, Paragraph};
use ratatui::Terminal;
use std::collections::HashMap;
use std::io::{Cursor, Stdout, Write};
use std::time::{Duration, Instant};
use std::time::Instant;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeBarLength {
Minute,
Hour,
Custom(i128),
/// implementing a bar that would grow smaller would be weird, so it's a count up instead of
/// a countdown
Countup(i128),
Day,
}
impl TimeBarLength {
pub(crate) const fn as_secs(self) -> i128 {
match self {
Self::Minute => 60,
Self::Day => 24 * 60 * 60,
Self::Hour => 60 * 60,
Self::Custom(secs) | Self::Countup(secs) => secs,
}
}
}
impl Default for TimeBarLength {
fn default() -> Self {
Self::Minute
}
}
pub mod timebar;
pub mod ui;
use timebar::TimeBarLength;
use ui::Data;
/// Make your terminal into a big clock
#[derive(Parser, Debug, Clone)]
#[command(help_template = HELP_TEMPLATE, author, version)]
#[clap(group( ArgGroup::new("timebarlen") .args(&["minute","day", "hour", "custom", "countdown"]),))]
#[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 {
@ -78,7 +61,8 @@ pub struct Clock {
#[clap(short = 'u', long, value_parser = humantime::parse_duration)]
pub countdown: Option<std::time::Duration>,
/// Play a notification sound when the countdown is up
#[clap(short, long)]
#[cfg(feature = "sound")]
#[clap(short, long, default_value_t = true)]
pub sound: bool,
// internal variables
@ -88,56 +72,6 @@ pub struct Clock {
pub(crate) did_notify: bool,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct UiData {
fdate: [String; 2],
ftime: [String; 2],
timebar_ratio: [Option<f64>; 2],
data_idx: usize,
}
impl UiData {
pub fn update(&mut self, fdate: String, ftime: String, timebar_ratio: Option<f64>) {
self.data_idx ^= 1;
self.fdate[self.data_idx] = fdate;
self.ftime[self.data_idx] = ftime;
self.timebar_ratio[self.data_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.data_idx]
}
#[must_use]
#[inline]
pub fn ftime(&self) -> &str {
&self.ftime[self.data_idx]
}
#[must_use]
#[inline]
#[allow(clippy::missing_const_for_fn)] // no it's not const
pub fn timebar_ratio(&self) -> Option<f64> {
self.timebar_ratio[self.data_idx]
}
}
impl Clock {
#[must_use]
#[allow(clippy::missing_const_for_fn)]
@ -148,14 +82,14 @@ impl Clock {
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(i128::from(
self.countdown.unwrap().as_secs(),
)))
Some(TimeBarLength::Countup(
self.countdown.unwrap().as_secs() as i64
))
} else if self.custom.is_some() {
Some(TimeBarLength::Custom(i128::from(
self.custom.unwrap().as_secs(),
)))
Some(TimeBarLength::Custom(self.custom.unwrap().as_secs() as i64))
} else {
None
}
@ -179,31 +113,47 @@ impl Clock {
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::Countup(_) | TimeBarLength::Timer => {
// the count up should not reset. If the time is over, just keep it at 100%
}
TimeBarLength::Custom(_) => {
if since_last_reset.num_seconds() >= 1
&& i128::from(since_last_reset.num_seconds()) >= len.as_secs()
// 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());
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());
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());
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());
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)");
}
}
@ -215,19 +165,23 @@ impl Clock {
if let Some(len) = self.timebar_len() {
trace!("Local Time: {}", Local::now());
match len {
TimeBarLength::Custom(_) | TimeBarLength::Countup(_) => {
TimeBarLength::Custom(_) | TimeBarLength::Countup(_) | TimeBarLength::Timer => {
self.last_reset = Some(Local::now());
}
TimeBarLength::Minute => {
self.last_reset = Some(
Local::now()
.with_second(0)
.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"),
);
@ -235,6 +189,11 @@ impl Clock {
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"),
);
@ -261,9 +220,9 @@ impl Clock {
mut self,
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
) -> anyhow::Result<()> {
let tick_rate = Duration::from_millis(100);
let tick_rate = std::time::Duration::from_millis(100);
let mut last_tick = Instant::now();
let mut uidata: UiData = UiData::default();
let mut uidata: Data = Data::new(self.timebar_len());
self.setup()?;
loop {
let raw_time = chrono::Local::now().round_subsecs(0);
@ -290,10 +249,12 @@ impl Clock {
// 01:30 is 50%, 01:59 is 98%, 01:60 does not exist because that's how counting from
// 0 works.
let now = raw_time + chrono::Duration::seconds(1);
uidata.update(
now,
splits[0].clone(),
splits[1].clone(),
self.timebar_ratio(raw_time + chrono::Duration::seconds(1)),
self.timebar_ratio(now),
);
if uidata.changed() {
self.ui(terminal, &uidata)?;
@ -319,10 +280,11 @@ impl Clock {
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: &UiData,
data: &Data,
) -> anyhow::Result<()> {
terminal.draw(|frame| {
debug!("rendering the ui");
@ -338,12 +300,12 @@ impl Clock {
.title_bottom(env!("CARGO_PKG_VERSION"))
.title_alignment(Alignment::Center)
.title_style(Style::new().bold());
let a = space.inner(root);
let inner_rect = space.inner(root);
frame.render_widget(space, root);
let parts = Self::partition(a);
let parts = Self::partition(inner_rect);
let mut clockw = tui_big_text::BigText::builder();
if a.width > 80 {
if inner_rect.width > 80 {
clockw.pixel_size(tui_big_text::PixelSize::Full);
} else {
clockw.pixel_size(tui_big_text::PixelSize::Quadrant);
@ -359,52 +321,24 @@ impl Clock {
// render the timebar which counts up to the full minute and so on
//
// Will not be rendered if it is None
let timebarw: Option<LineGauge> = if self.timebar_len().is_some() {
debug!("time bar ration: {:?}", data.timebar_ratio());
let ratio = data.timebar_ratio().unwrap();
if !self.did_notify && (ratio - 1.0).abs() < 0.000_001 {
if let Some(TimeBarLength::Countup(_)) = self.timebar_len() {
let _ = self.notify().inspect_err(|e| {
error!("could not notify: {e}");
debug!("complete error: {e:#?}");
});
self.did_notify = true;
}
}
let timebarw = LineGauge::default()
.filled_style(if self.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 a.width > 80 {
(f32::from(parts[2].width) * 0.43) as u16
} else {
(f32::from(parts[2].width) * 0.25) as u16
})))
.ratio(ratio);
Some(timebarw)
} else {
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[2]);
frame.render_widget(datew, parts[1]);
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[0]);
frame.render_widget(clockw, parts["clockw"]);
})?;
debug!("done rendering the ui");
Ok(())
@ -445,9 +379,6 @@ impl Clock {
// 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.
//
// TODO: add something to make a sound without the notification system,
// as that is not reliable but the user might depend on it.
// only play this when we don't use built in sound, this
// isn't as consistent
@ -481,7 +412,7 @@ impl Clock {
std::io::stdout().flush()?;
Ok(())
}
fn partition(r: Rect) -> Vec<Rect> {
fn partition(r: Rect) -> HashMap<&'static str, Rect> {
let part = Layout::default()
.direction(Direction::Vertical)
.constraints([
@ -489,7 +420,9 @@ impl Clock {
Constraint::Length(if r.width > 80 { 8 } else { 5 }),
])
.split(r);
let hlen_date: u16 = (f32::from(part[1].width) * 0.35) as u16;
#[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([
@ -498,6 +431,16 @@ impl Clock {
])
.split(part[0]);
vec![part[1], subparts[0], subparts[1]]
let timebarw_spaces = Layout::default()
.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]),
])
}
}

71
src/clock/timebar.rs Normal file
View File

@ -0,0 +1,71 @@
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 Normal file
View File

@ -0,0 +1,221 @@
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]
})),
)
})
}

View File

@ -1,3 +1,5 @@
#![allow(missing_docs)] // this is not a library crate
use std::io;
use libpt::cli::clap::Parser;
@ -15,6 +17,13 @@ use self::clock::Clock;
mod clock;
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
let clock = Clock::parse();
if clock.verbose.level() >= Level::DEBUG {
@ -63,7 +72,7 @@ fn mock_tests() {
use chrono::{Local, Timelike};
use libpt::log::info;
use self::clock::UiData;
use crate::clock::ui::Data;
info!("doing the mock tests");
{
let mut c = Clock::parse_from(["some exec", "-mvvv"]);
@ -81,12 +90,13 @@ fn mock_tests() {
info!("0s=0.0");
}
{
let mut data = UiData::default();
data.update("date".to_owned(), "time".to_owned(), Some(0.1));
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("date".to_owned(), "time".to_owned(), Some(0.2));
data.update(now, "date".to_owned(), "time".to_owned(), Some(0.2));
assert_eq!(data.timebar_ratio(), Some(0.2));
data.update("date".to_owned(), "time".to_owned(), Some(0.3));
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");