config.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use crate::widgets as w;
  2. pub struct Config {
  3. left: Vec<Box<w::Widget>>,
  4. right: Vec<Box<w::Widget>>,
  5. }
  6. impl Config {
  7. pub fn from_toml(input: toml::Value) -> Result<Config, failure::Error> {
  8. let mut conf = Config { left: Vec::new(), right: Vec::new() };
  9. let widgets = &input.as_table().ok_or(format_err!("invalid config"))?["widgets"];
  10. let mut target = &mut conf.left;
  11. for section in widgets.as_array().ok_or(format_err!("invalid config"))? {
  12. let section = section.as_table().ok_or(format_err!("invalid config"))?;
  13. match section["name"].as_str().ok_or(format_err!(""))? {
  14. "box" => target.push(Box::new(w::SmallBox)),
  15. "battery" => target.push(Box::new(w::Battery::new()?)),
  16. "sep" => target = &mut conf.right,
  17. "stdin" => target.push(Box::new(w::Stdin::new())),
  18. "time" => target.push(Box::new(w::Time::new())),
  19. _ => (),
  20. }
  21. }
  22. Ok(conf)
  23. }
  24. pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Config, failure::Error> {
  25. let body = std::fs::read_to_string(path)?;
  26. let val = body.parse::<toml::Value>()?;
  27. Config::from_toml(val)
  28. }
  29. pub fn draw(&self, ctx: &cairo::Context, layout: &pango::Layout, stdin: &str, size: w::Size) -> Result<(), failure::Error>{
  30. // the background is... gray-ish? this'll be configurable eventually
  31. ctx.set_source_rgb(0.1, 0.1, 0.1);
  32. ctx.paint();
  33. // and the text is white
  34. ctx.set_source_rgb(1.0, 1.0, 1.0);
  35. // set up a struct with everything that widgets need to draw
  36. let d = w::Drawing {
  37. ctx: ctx,
  38. lyt: &layout,
  39. size,
  40. stdin,
  41. };
  42. let mut offset = 10;
  43. for w in self.left.iter() {
  44. offset += 10 + w.draw(&d, w::Located::FromLeft(offset));
  45. }
  46. offset = 10;
  47. for w in self.right.iter() {
  48. offset += 10 + w.draw(&d, w::Located::FromRight(offset));
  49. }
  50. Ok(())
  51. }
  52. }