1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright ⓒ 2019-2020 Lewis Belcher
// Licensed under the MIT license (see LICENSE or <http://opensource.org/licenses/MIT>).
// All files in the project carrying such notice may not be copied, modified, or
// distributed except according to those terms

use crate::blocks::{Block, Configure, Message, Sender};
use chrono::prelude::*;
use serde::Deserialize;
use std::thread;
use std::time::Duration;

#[derive(Configure, Deserialize)]
pub struct Time {
	#[serde(default = "default_name")]
	name: String,
	#[serde(default = "default_format")]
	format: String,
	#[serde(default = "default_period")]
	period: f32,
}

fn default_name() -> String {
	"time".to_string()
}

fn default_format() -> String {
	"%a %d %b <b>%H:%M:%S</b>".to_string()
}

fn default_period() -> f32 {
	1.0
}

impl Sender for Time {
	fn add_sender(&self, channel: crossbeam_channel::Sender<Message>) {
		let name = self.get_name();
		let format = self.format.clone();
		let period = self.period;
		let mut block = Block::new(name.clone(), true);

		thread::spawn(move || loop {
			block.full_text = Some(Local::now().format(&format).to_string());
			channel.send((name.clone(), block.to_string())).unwrap();
			thread::sleep(Duration::from_secs_f32(period));
		});
	}
}