config.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. conf.right.reverse();
  23. Ok(conf)
  24. }
  25. pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Config, failure::Error> {
  26. let body = std::fs::read_to_string(path)?;
  27. let val = body.parse::<toml::Value>()?;
  28. Config::from_toml(val)
  29. }
  30. pub fn find_config() -> Result<Config, failure::Error> {
  31. if let Some(p) = xdg::BaseDirectories::new()?.find_config_file("knurling/knurling.toml") {
  32. return Config::from_file(p);
  33. }
  34. Err(format_err!("Unable to find `knurling.toml`"))
  35. }
  36. pub fn draw(&self, ctx: &cairo::Context, layout: &pango::Layout, stdin: &str, size: w::Size) -> Result<(), failure::Error>{
  37. // the background is... gray-ish? this'll be configurable eventually
  38. ctx.set_source_rgb(0.1, 0.1, 0.1);
  39. ctx.paint();
  40. // and the text is white
  41. ctx.set_source_rgb(1.0, 1.0, 1.0);
  42. // set up a struct with everything that widgets need to draw
  43. let d = w::Drawing {
  44. ctx: ctx,
  45. lyt: &layout,
  46. size,
  47. stdin,
  48. };
  49. let mut offset = 10;
  50. for w in self.left.iter() {
  51. offset += 10 + w.draw(&d, w::Located::FromLeft(offset));
  52. }
  53. offset = 10;
  54. for w in self.right.iter() {
  55. offset += 10 + w.draw(&d, w::Located::FromRight(offset));
  56. }
  57. Ok(())
  58. }
  59. }