| 1 | use anyhow::Result; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | mod battery; |
| 5 | mod datetime; |
| 6 | mod shell; |
| 7 | |
| 8 | use battery::Battery; |
| 9 | use datetime::DateTime; |
| 10 | use shell::ShellBlock; |
| 11 | |
| 12 | pub trait Block { |
| 13 | fn content(&mut self) -> Result<String>; |
| 14 | fn interval(&self) -> Duration; |
| 15 | fn color(&self) -> u32; |
| 16 | } |
| 17 | |
| 18 | pub struct BlockConfig { |
| 19 | pub format: &'static str, |
| 20 | pub command: BlockCommand, |
| 21 | pub interval_secs: u64, |
| 22 | pub color: u32, |
| 23 | } |
| 24 | |
| 25 | pub enum BlockCommand { |
| 26 | Shell(&'static str), |
| 27 | DateTime(&'static str), |
| 28 | Battery { |
| 29 | format_charging: &'static str, |
| 30 | format_discharging: &'static str, |
| 31 | format_full: &'static str, |
| 32 | }, |
| 33 | Static(&'static str), |
| 34 | } |
| 35 | |
| 36 | impl BlockConfig { |
| 37 | pub fn to_block(&self) -> Box<dyn Block> { |
| 38 | match self.command { |
| 39 | BlockCommand::Shell(cmd) => Box::new(ShellBlock::new( |
| 40 | self.format, |
| 41 | cmd, |
| 42 | self.interval_secs, |
| 43 | self.color, |
| 44 | )), |
| 45 | BlockCommand::DateTime(fmt) => Box::new(DateTime::new( |
| 46 | self.format, |
| 47 | fmt, |
| 48 | self.interval_secs, |
| 49 | self.color, |
| 50 | )), |
| 51 | BlockCommand::Battery { |
| 52 | format_charging, |
| 53 | format_discharging, |
| 54 | format_full, |
| 55 | } => Box::new(Battery::new( |
| 56 | format_charging, |
| 57 | format_discharging, |
| 58 | format_full, |
| 59 | self.interval_secs, |
| 60 | self.color, |
| 61 | )), |
| 62 | BlockCommand::Static(text) => Box::new(StaticBlock::new( |
| 63 | &format!("{}{}", self.format, text), |
| 64 | self.color, |
| 65 | )), |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | struct StaticBlock { |
| 71 | text: String, |
| 72 | color: u32, |
| 73 | } |
| 74 | |
| 75 | impl StaticBlock { |
| 76 | fn new(text: &str, color: u32) -> Self { |
| 77 | Self { |
| 78 | text: text.to_string(), |
| 79 | color, |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | impl Block for StaticBlock { |
| 85 | fn content(&mut self) -> Result<String> { |
| 86 | Ok(self.text.clone()) |
| 87 | } |
| 88 | |
| 89 | fn interval(&self) -> Duration { |
| 90 | Duration::from_secs(u64::MAX) |
| 91 | } |
| 92 | |
| 93 | fn color(&self) -> u32 { |
| 94 | self.color |
| 95 | } |
| 96 | } |