use cairo::{Context, Error}; use std::f64::consts::PI; use wmap_parser::Shape; /// Draws a vertex shape at the given position pub fn draw_vertex( context: &Context, shape: &Shape, x: f64, y: f64, width: f64, height: f64, ) -> Result<(), Error> { match shape { Shape::Circle => draw_circle(context, x, y, width, height), Shape::Square => draw_square(context, x, y, width, height), Shape::Triangle => draw_triangle(context, x, y, width, height), Shape::X => draw_x(context, x, y, width, height), } } fn draw_circle(context: &Context, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> { context.save()?; context.translate(x + width / 2.0, y + height / 2.0); context.scale(width / 2.0, height / 2.0); context.arc(0.0, 0.0, 1.0, 0.0, 2.0 * PI); context.restore()?; context.fill()?; Ok(()) } fn draw_square(context: &Context, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> { context.rectangle(x, y, width, height); context.fill()?; Ok(()) } fn draw_triangle(context: &Context, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> { context.move_to(x + width / 2.0, y); context.line_to(x + width, y + height); context.line_to(x, y + height); context.close_path(); context.fill()?; Ok(()) } fn draw_x(context: &Context, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> { let line_width = 2.0; context.set_line_width(line_width); context.move_to(x, y); context.line_to(x + width, y + height); context.move_to(x + width, y); context.line_to(x, y + height); context.stroke()?; Ok(()) } #[cfg(test)] mod tests { use super::*; use cairo::{Context, Format, ImageSurface}; #[test] fn test_draw_shapes() { // Just verify the functions don't panic let surface = ImageSurface::create(Format::Rgb24, 100, 100).unwrap(); let context = Context::new(&surface).unwrap(); assert!(draw_vertex(&context, &Shape::Circle, 0.0, 0.0, 25.0, 25.0).is_ok()); assert!(draw_vertex(&context, &Shape::Square, 0.0, 0.0, 25.0, 25.0).is_ok()); assert!(draw_vertex(&context, &Shape::Triangle, 0.0, 0.0, 25.0, 25.0).is_ok()); assert!(draw_vertex(&context, &Shape::X, 0.0, 0.0, 25.0, 25.0).is_ok()); } }