| 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 | pub underline: bool, |
| 24 | } |
| 25 | |
| 26 | pub enum BlockCommand { |
| 27 | Shell(&'static str), |
| 28 | DateTime(&'static str), |
| 29 | Battery { |
| 30 | format_charging: &'static str, |
| 31 | format_discharging: &'static str, |
| 32 | format_full: &'static str, |
| 33 | }, |
| 34 | Static(&'static str), |
| 35 | } |
| 36 | |
| 37 | impl BlockConfig { |
| 38 | pub fn to_block(&self) -> Box<dyn Block> { |
| 39 | match self.command { |
| 40 | BlockCommand::Shell(cmd) => Box::new(ShellBlock::new( |
| 41 | self.format, |
| 42 | cmd, |
| 43 | self.interval_secs, |
| 44 | self.color, |
| 45 | )), |
| 46 | BlockCommand::DateTime(fmt) => Box::new(DateTime::new( |
| 47 | self.format, |
| 48 | fmt, |
| 49 | self.interval_secs, |
| 50 | self.color, |
| 51 | )), |
| 52 | BlockCommand::Battery { |
| 53 | format_charging, |
| 54 | format_discharging, |
| 55 | format_full, |
| 56 | } => Box::new(Battery::new( |
| 57 | format_charging, |
| 58 | format_discharging, |
| 59 | format_full, |
| 60 | self.interval_secs, |
| 61 | self.color, |
| 62 | )), |
| 63 | BlockCommand::Static(text) => Box::new(StaticBlock::new( |
| 64 | &format!("{}{}", self.format, text), |
| 65 | self.color, |
| 66 | )), |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | struct StaticBlock { |
| 72 | text: String, |
| 73 | color: u32, |
| 74 | } |
| 75 | |
| 76 | impl StaticBlock { |
| 77 | fn new(text: &str, color: u32) -> Self { |
| 78 | Self { |
| 79 | text: text.to_string(), |
| 80 | color, |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | impl Block for StaticBlock { |
| 86 | fn content(&mut self) -> Result<String> { |
| 87 | Ok(self.text.clone()) |
| 88 | } |
| 89 | |
| 90 | fn interval(&self) -> Duration { |
| 91 | Duration::from_secs(u64::MAX) |
| 92 | } |
| 93 | |
| 94 | fn color(&self) -> u32 { |
| 95 | self.color |
| 96 | } |
| 97 | } |