forked from wathiede/i3xs
Allow time color to change based on time of day.
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
use chrono::NaiveTime;
|
||||
use chrono_tz::Tz;
|
||||
|
||||
use i3monkit::Block;
|
||||
use i3monkit::ColorRGB;
|
||||
use i3monkit::{Widget, WidgetUpdate};
|
||||
|
||||
/// The widget that shows local time
|
||||
@@ -11,21 +13,51 @@ pub struct DateTimeWidget {
|
||||
/// tz string, values from https://docs.rs/chrono-tz/*/chrono_tz/
|
||||
/// None will use local time.
|
||||
tz: Option<String>,
|
||||
colors: Option<Vec<TimeColor>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TimeColor {
|
||||
pub start: NaiveTime,
|
||||
pub color: ColorRGB,
|
||||
}
|
||||
|
||||
impl DateTimeWidget {
|
||||
// Create a new time widget
|
||||
pub fn new(fmt: String) -> Self {
|
||||
DateTimeWidget { fmt, tz: None }
|
||||
DateTimeWidget {
|
||||
fmt,
|
||||
tz: None,
|
||||
colors: None,
|
||||
}
|
||||
}
|
||||
pub fn tz(fmt: String, tz: String) -> Self {
|
||||
DateTimeWidget { fmt, tz: Some(tz) }
|
||||
DateTimeWidget {
|
||||
fmt,
|
||||
tz: Some(tz),
|
||||
colors: None,
|
||||
}
|
||||
}
|
||||
pub fn set_colors(&mut self, colors: &[TimeColor]) {
|
||||
let mut colors = colors.to_vec();
|
||||
colors.sort_by(|l, r| l.start.cmp(&r.start));
|
||||
self.colors = Some(colors);
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for DateTimeWidget {
|
||||
fn update(&mut self) -> Option<WidgetUpdate> {
|
||||
let now = chrono::Local::now();
|
||||
let color = if let Some(colors) = &self.colors {
|
||||
colors
|
||||
.iter()
|
||||
.filter(|tc| tc.start < now.time())
|
||||
.last()
|
||||
.map(|tc| tc.color.clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let time_string = match &self.tz {
|
||||
Some(tz) => {
|
||||
let tz: Tz = tz.parse().unwrap();
|
||||
@@ -36,9 +68,13 @@ impl Widget for DateTimeWidget {
|
||||
None => now.format(&self.fmt).to_string(),
|
||||
};
|
||||
|
||||
let mut data = Block::new().append_full_text(&time_string).clone();
|
||||
if let Some(color) = color {
|
||||
data.color(color);
|
||||
}
|
||||
Some(WidgetUpdate {
|
||||
refresh_interval: std::time::Duration::new(1, 0),
|
||||
data: Some(Block::new().append_full_text(&time_string).clone()),
|
||||
data: Some(data),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user