rs_blocks/blocks/
time.rs

1// Copyright ⓒ 2019-2021 Lewis Belcher
2// Licensed under the MIT license (see LICENSE or <http://opensource.org/licenses/MIT>).
3// All files in the project carrying such notice may not be copied, modified, or
4// distributed except according to those terms
5
6//! # Time block
7//!
8//! Use this block to get time monitoring in the status bar.
9//!
10//! Typical configuration:
11//!
12//! ```toml
13//! [time]
14//! ```
15//!
16//! ## Configuration options
17//!
18//! - `name`: Name of the block (must be unique)
19//! - `period`: Default update period in seconds (extra updates may occur on
20//!    event changes etc)
21//! - `format`: Strftime format string for specifying the time format
22
23use crate::blocks::{Block, Configure, Message, Sender};
24use chrono::prelude::*;
25use serde::Deserialize;
26use std::thread;
27use std::time::Duration;
28
29#[derive(Configure, Deserialize)]
30pub struct Time {
31	#[serde(default = "default_name")]
32	name: String,
33	#[serde(default = "default_period")]
34	period: f32,
35	#[serde(default = "default_format")]
36	format: String,
37}
38
39fn default_name() -> String {
40	"time".to_string()
41}
42
43fn default_period() -> f32 {
44	1.0
45}
46
47fn default_format() -> String {
48	"%a %d %b <b>%H:%M:%S</b>".to_string()
49}
50
51impl Sender for Time {
52	fn add_sender(&self, channel: crossbeam_channel::Sender<Message>) -> anyhow::Result<()> {
53		let name = self.get_name();
54		let format = self.format.clone();
55		let period = self.period;
56		let mut block = Block::new(name.clone(), true);
57
58		thread::spawn(move || loop {
59			block.full_text = Some(Local::now().format(&format).to_string());
60			channel.send((name.clone(), block.to_string())).unwrap();
61			thread::sleep(Duration::from_secs_f32(period));
62		});
63
64		Ok(())
65	}
66}