app.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. use crate::dmc;
  2. use anyhow::{anyhow, bail, Result};
  3. pub struct Data {
  4. pub symbol: char,
  5. pub dmc: Option<dmc::DMC>,
  6. }
  7. impl Data {
  8. pub fn draw_to_file<P: AsRef<std::path::Path>>(&self, path: P) -> Result<()> {
  9. let f = std::fs::File::create(path)?;
  10. let surf = cairo::SvgSurface::for_stream(100.0, 100.0, f)?;
  11. self.render(&cairo::Context::new(&surf), 100.0, 100.0)?;
  12. if let Err(err) = surf.finish_output_stream() {
  13. bail!(err.error);
  14. };
  15. Ok(())
  16. }
  17. pub fn render(&self, ctx: &cairo::Context, w: f64, h: f64) -> Result<()> {
  18. let off_x = (w - 100.) / 2.0;
  19. let off_y = (h - 100.) / 2.0;
  20. let color = self.color();
  21. ctx.set_source_rgb(color.0, color.1, color.2);
  22. ctx.paint();
  23. ctx.set_source_rgb(0., 0., 0.);
  24. ctx.rectangle(off_x, off_y, 100., 100.);
  25. ctx.stroke();
  26. ctx.move_to(off_x, off_y - 23.0);
  27. let layout = pangocairo::functions::create_layout(&ctx)
  28. .ok_or_else(|| anyhow!("Could not create layout"))?;
  29. layout.set_width(100 * 1024);
  30. layout.set_alignment(pango::Alignment::Center);
  31. let font = pango::FontDescription::from_string("Fira Sans 92");
  32. layout.set_font_description(Some(&font));
  33. layout.set_text(&self.symbol.to_string());
  34. pangocairo::functions::show_layout(&ctx, &layout);
  35. Ok(())
  36. }
  37. fn color(&self) -> (f64, f64, f64) {
  38. self.dmc
  39. .map(|dmc| dmc.color)
  40. .unwrap_or_else(|| (0.5, 0.5, 0.5))
  41. }
  42. }