aboutsummaryrefslogtreecommitdiff
path: root/src/shapes.rs
blob: 2b8db2c0417808d87be70b6153be2f811cdab41b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use wmap_parser::Shape;

/// Draws a vertex shape at the given position
pub fn draw_vertex(
    ctx: &cairo::Context,
    shape: &Shape,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
) -> Result<(), cairo::Error> {
    match shape {
        Shape::Circle => draw_circle(ctx, x, y, width, height),
        Shape::Square => draw_square(ctx, x, y, width, height),
        Shape::Triangle => draw_triangle(ctx, x, y, width, height),
        Shape::X => draw_x(ctx, x, y, width, height),
    }
}

fn draw_circle(
    ctx: &cairo::Context,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
) -> Result<(), cairo::Error> {
    ctx.save()?;
    ctx.translate(x + width / 2.0, y + height / 2.0);
    ctx.scale(width / 2.0, height / 2.0);
    ctx.arc(0.0, 0.0, 1.0, 0.0, 2.0 * std::f64::consts::PI);
    ctx.restore()?;
    ctx.fill()?;
    Ok(())
}

fn draw_square(
    ctx: &cairo::Context,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
) -> Result<(), cairo::Error> {
    ctx.rectangle(x, y, width, height);
    ctx.fill()?;
    Ok(())
}

fn draw_triangle(
    ctx: &cairo::Context,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
) -> Result<(), cairo::Error> {
    ctx.move_to(x + width / 2.0, y);
    ctx.line_to(x + width, y + height);
    ctx.line_to(x, y + height);
    ctx.close_path();
    ctx.fill()?;
    Ok(())
}

fn draw_x(
    ctx: &cairo::Context,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
) -> Result<(), cairo::Error> {
    let line_width = 2.0;
    ctx.set_line_width(line_width);
    ctx.move_to(x, y);
    ctx.line_to(x + width, y + height);
    ctx.move_to(x + width, y);
    ctx.line_to(x, y + height);
    ctx.stroke()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_draw_shapes() {
        // Just verify the functions don't panic
        let surface = cairo::ImageSurface::create(cairo::Format::Rgb24, 100, 100).unwrap();
        let ctx = cairo::Context::new(&surface).unwrap();

        assert!(draw_vertex(&ctx, &Shape::Circle, 0.0, 0.0, 25.0, 25.0).is_ok());
        assert!(draw_vertex(&ctx, &Shape::Square, 0.0, 0.0, 25.0, 25.0).is_ok());
        assert!(draw_vertex(&ctx, &Shape::Triangle, 0.0, 0.0, 25.0, 25.0).is_ok());
        assert!(draw_vertex(&ctx, &Shape::X, 0.0, 0.0, 25.0, 25.0).is_ok());
    }
}