Compare commits

..

No commits in common. "0c954962cc23418f17a652f1926ca95ea0db454e" and "853e735fcd9233c54bb3021edf2f80067d75afa0" have entirely different histories.

7 changed files with 61 additions and 1357 deletions

1118
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -8,8 +8,6 @@ edition = "2021"
[dependencies]
anyhow = "1.0.71"
clap = { version = "4.3.4", features = ["derive"] }
humantime = "2.1.0"
notify-rust = "4.8.0"
serde = { version = "1.0.164", features = ["derive"] }
serde_cbor = "0.11.2"
thiserror = "1.0.44"

View file

@ -1,9 +1,8 @@
use crate::daemon::{Answer, AnswerErr, Command as OtherCommand};
use crate::daemon::{Answer, Command as OtherCommand, AnswerErr};
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::net::Shutdown;
use std::os::unix::net::UnixStream;
use std::time::Duration;
#[derive(Debug, Parser)]
#[command(name = "timers")]
@ -19,35 +18,10 @@ pub struct Cli {
#[derive(Debug, Subcommand)]
pub enum Command {
Daemon {
#[arg(short, long)]
notify: bool,
},
Add {
name: String,
duration: humantime::Duration,
},
Daemon,
Add { name: String, duration_seconds: u64 },
List,
Remove {
name: String,
},
#[command(subcommand)]
Pomodoro(PomodoroCommand)
}
#[derive(Debug, Subcommand)]
pub enum PomodoroCommand {
Start {
#[clap(default_value_t = Duration::from_secs(25 * 60).into())]
work: humantime::Duration,
#[clap(default_value_t = Duration::from_secs(5 * 60).into())]
pause: humantime::Duration,
#[clap(default_value_t = Duration::from_secs(10 * 60).into())]
long_pause: humantime::Duration,
#[clap(default_value_t = 3)]
pauses_till_long: u64,
},
Stop,
Remove { name: String },
}
fn get_stream(socket_path: &String) -> Result<UnixStream> {
@ -61,8 +35,7 @@ pub fn send_command(socket_path: &String, command: OtherCommand) -> Result<()> {
stream
.shutdown(Shutdown::Write)
.context("Could not shutdown write!")?;
let answer: Result<Answer, AnswerErr> =
serde_cbor::from_reader(&stream).context("Could not read answer!")?;
let answer: Result<Answer, AnswerErr> = serde_cbor::from_reader(&stream).context("Could not read answer!")?;
match answer {
Ok(answer) => println!("{}", answer),
Err(err) => println!("Error: {}", err),

View file

@ -1,7 +1,5 @@
use crate::pomodoro::Pomodoro;
pub use crate::timer::Timer;
use anyhow::Context;
use notify_rust::Notification;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use std::{
@ -13,40 +11,28 @@ use std::{
#[derive(Debug, Serialize, Deserialize)]
pub enum Command {
Add(Box<str>, Duration),
Remove(Box<str>),
Add(String, Duration),
Remove(String),
List,
PomodoroStart {
work: Duration,
pause: Duration,
long_pause: Duration,
pauses_till_long: u64,
},
PomodoroStop
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Answer {
Ok,
Timers(Vec<Timer>, Option<Pomodoro>),
Timers(Vec<Timer>),
}
impl Display for Answer {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
Answer::Ok => write!(f, "Ok"),
Answer::Timers(timers, pomodoro) => {
Answer::Timers(timers) => {
if timers.is_empty() {
writeln!(f, "No timers running.")?;
write!(f, "No timers running.")
} else {
let strings: Vec<String> =
timers.iter().map(|timer| timer.to_string()).collect();
writeln!(f, "{}", strings.join("\n"))?;
};
match pomodoro {
Some(p) => write!(f, "{}", p),
None => write!(f, "No pomodoro running."),
write!(f, "{}", strings.join("\n"))
}
}
}
@ -56,20 +42,19 @@ impl Display for Answer {
#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
pub enum AnswerErr {
#[error("Timer with name '{}' already exists", .0)]
TimerAlreadyExist(Box<str>),
TimerAlreadyExist(String),
#[error("No timer with the name '{}' exists", .0)]
NoSuchTimer(Box<str>),
NoSuchTimer(String),
}
pub struct Daemon {
listener: UnixListener,
timers: Vec<Timer>,
pomodoro: Option<Pomodoro>,
notify: bool,
}
impl Daemon {
pub fn new(socket_path: String, notify: bool) -> anyhow::Result<Self> {
pub fn new(socket_path: String) -> anyhow::Result<Self> {
let path = std::path::Path::new(&socket_path);
if path.exists() {
std::fs::remove_file(path)
@ -80,42 +65,21 @@ impl Daemon {
Ok(Self {
listener,
timers: Vec::new(),
pomodoro: None,
notify,
})
}
fn has_timer(&mut self, name: &str) -> bool {
self.timers.iter().any(|other| other.name.as_ref() == name)
fn has_timer(&mut self, name: &String) -> bool {
self.timers.iter().any(|other| &other.name == name)
}
fn handle_command(&mut self, command: Command) -> Result<Answer, AnswerErr> {
println!("Received command {:?}", command);
match command {
Command::List => Ok(Answer::Timers(self.timers.clone(), self.pomodoro.clone())),
Command::List => Ok(Answer::Timers(self.timers.to_vec())),
Command::Add(name, duration) => {
if self.has_timer(&name) {
return Err(AnswerErr::TimerAlreadyExist(name));
}
if self.notify {
match Notification::new()
.summary("󰀠 Timers")
.body(
format!(
"Started timer {} for {}",
&name,
humantime::format_duration(duration)
)
.as_str(),
)
.show()
{
Ok(_) => println!("Sent notification sucessfully."),
Err(_) => println!("Failed to send notification."),
};
}
let timer = Timer::new(name, duration);
self.timers.push(timer);
Ok(Answer::Ok)
@ -124,31 +88,14 @@ impl Daemon {
if !self.has_timer(&name) {
return Err(AnswerErr::NoSuchTimer(name));
}
self.timers
.retain(|other| other.name.as_ref() != name.as_ref());
self.timers = self
.timers
.iter()
.cloned()
.filter(|other| other.name != name)
.collect();
Ok(Answer::Ok)
}
Command::PomodoroStart {
work,
pause,
long_pause,
pauses_till_long,
} => {
match Notification::new()
.summary("󰀠 Timers")
.body("Started pomodoro.")
.show()
{
Ok(_) => println!("Sent notification sucessfully."),
Err(_) => println!("Failed to send notification."),
};
self.pomodoro = Some(Pomodoro::new(work, pause, long_pause, pauses_till_long));
Ok(Answer::Ok)
}
Command::PomodoroStop => {
self.pomodoro = None;
Ok(Answer::Ok)
},
}
}
@ -161,19 +108,18 @@ impl Daemon {
}
fn check_timers(&mut self) {
self.timers.retain(|timer| {
if timer.is_expired() {
timer.handle_expiration(self.notify);
}
!timer.is_expired()
});
if let Some(pomodoro) = &mut self.pomodoro {
if pomodoro.is_expired() {
pomodoro.handle_expiration(self.notify);
}
}
self.timers = self
.timers
.iter()
.cloned()
.filter(|timer| {
let expired = timer.is_expired();
if expired {
println!("Timer {} is expired!", timer.name);
}
!expired
})
.collect();
}
pub fn run(&mut self) -> anyhow::Result<()> {

View file

@ -1,37 +1,24 @@
pub mod cli;
pub mod daemon;
pub mod pomodoro;
pub mod timer;
use std::time::Duration;
use crate::cli::{send_command, Cli, Command as CliCommand};
use crate::daemon::{Command as DaemonCommand, Daemon};
use anyhow::Result;
use clap::Parser;
use cli::PomodoroCommand;
fn main() -> Result<()> {
let args = Cli::parse();
let daemon_command = match args.command {
CliCommand::Daemon { notify } => return Daemon::new(args.socket, notify)?.run(),
CliCommand::Add { name, duration } => {
DaemonCommand::Add(name.into_boxed_str(), duration.into())
}
CliCommand::Daemon => return Daemon::new(args.socket)?.run(),
CliCommand::Add {
name,
duration_seconds,
} => DaemonCommand::Add(name, Duration::from_secs(duration_seconds)),
CliCommand::List => DaemonCommand::List,
CliCommand::Remove { name } => DaemonCommand::Remove(name.into_boxed_str()),
CliCommand::Pomodoro(pomodoro) => match pomodoro {
PomodoroCommand::Start {
work,
pause,
long_pause,
pauses_till_long,
} => DaemonCommand::PomodoroStart {
work: work.into(),
pause: pause.into(),
long_pause: long_pause.into(),
pauses_till_long,
},
PomodoroCommand::Stop => DaemonCommand::PomodoroStop,
},
CliCommand::Remove { name } => DaemonCommand::Remove(name),
};
send_command(&args.socket, daemon_command)
}

View file

@ -1,92 +0,0 @@
use std::{fmt::Display, time::Duration};
use serde::{Deserialize, Serialize};
use crate::daemon::Timer;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Pomodoro {
work: Duration,
pause: Duration,
long_pause: Duration,
pauses_till_long: u64,
pauses: u64,
status: Status,
pub timer: Timer,
}
impl Display for Pomodoro {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Pomodoro ({}, {}, {}) currently {} with {} remaining.",
humantime::format_duration(self.work),
humantime::format_duration(self.pause),
humantime::format_duration(self.long_pause),
self.status,
humantime::format_duration(self.timer.remaining())
)
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
enum Status {
Working,
Pausing,
LongPause,
}
impl Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Status::Working => write!(f, "pomodoro work"),
Status::Pausing => write!(f, "pomodoro pause"),
Status::LongPause => write!(f, "pomodoro long pause"),
}
}
}
impl Pomodoro {
pub fn new(
work: Duration,
pause: Duration,
long_pause: Duration,
pauses_till_long: u64,
) -> Self {
Pomodoro {
work,
pause,
long_pause,
pauses_till_long,
pauses: 0,
status: Status::Working,
timer: Timer::new(Status::Working.to_string().into_boxed_str(), work),
}
}
pub fn handle_expiration(&mut self, notify: bool) {
self.timer.handle_expiration(notify);
let duration = match self.status {
Status::Working => {
if self.pauses == self.pauses_till_long {
self.long_pause
} else {
self.pause
}
}
_ => self.work,
};
self.status = match self.status {
Status::Working => {
self.pauses += 1;
Status::Pausing
}
_ => Status::Working,
};
self.timer = Timer::new(self.status.to_string().into_boxed_str(), duration);
}
pub fn is_expired(&self) -> bool {
self.timer.is_expired()
}
}

View file

@ -1,4 +1,3 @@
use notify_rust::Notification;
use serde::{Deserialize, Serialize};
use std::{
fmt::{Display, Formatter},
@ -34,7 +33,7 @@ mod approx_instant {
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct Timer {
pub name: Box<str>,
pub name: String,
#[serde(with = "approx_instant")]
start: Instant,
duration: Duration,
@ -44,15 +43,15 @@ impl Display for Timer {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(
f,
"{} has {} remaining.",
"{} has {}s remaining.",
self.name,
humantime::format_duration(self.remaining())
self.remaining().as_secs()
)
}
}
impl Timer {
pub fn new(name: Box<str>, duration: Duration) -> Timer {
pub fn new(name: String, duration: Duration) -> Timer {
Timer {
name,
start: Instant::now(),
@ -64,20 +63,7 @@ impl Timer {
Instant::now() - self.start > self.duration
}
/// Returns the remaining duration rounded to seconds of this [`Timer`].
pub fn remaining(&self) -> Duration {
let exact = self.duration - (Instant::now() - self.start);
Duration::from_secs(exact.as_secs())
}
pub fn handle_expiration(&self, notify: bool) {
let msg = format!("Timer {} has expired!", self.name);
println!("{}", &msg);
if notify {
match Notification::new().summary("󰀠 Timers").body(&msg).show() {
Ok(_) => println!("Sent notification sucessfully."),
Err(_) => println!("Failed to send notification."),
}
}
self.duration - (Instant::now() - self.start)
}
}