Skip to main content

qr_code_styling/figures/
traits.rs

1//! Traits for figure drawing.
2
3use std::f64::consts::PI;
4
5/// Trait for drawing QR code figures.
6pub trait FigureDrawer {
7    /// Draw the figure and return SVG element string.
8    fn draw<F>(&self, x: f64, y: f64, size: f64, get_neighbor: Option<F>) -> String
9    where
10        F: Fn(i32, i32) -> bool;
11}
12
13/// Legacy type alias for compatibility.
14pub type NeighborFn = dyn Fn(i32, i32) -> bool;
15
16/// Helper to apply rotation transform to SVG element.
17pub fn rotate_transform(x: f64, y: f64, size: f64, rotation: f64) -> Option<String> {
18    if rotation.abs() < 0.0001 {
19        return None;
20    }
21    let cx = x + size / 2.0;
22    let cy = y + size / 2.0;
23    let degrees = (180.0 * rotation) / PI;
24    Some(format!("rotate({},{},{})", degrees, cx, cy))
25}
26
27/// Helper to create SVG circle element.
28pub fn svg_circle(cx: f64, cy: f64, r: f64, transform: Option<&str>) -> String {
29    match transform {
30        Some(t) => format!(
31            r#"<circle cx="{}" cy="{}" r="{}" transform="{}"/>"#,
32            cx, cy, r, t
33        ),
34        None => format!(r#"<circle cx="{}" cy="{}" r="{}"/>"#, cx, cy, r),
35    }
36}
37
38/// Helper to create SVG rect element.
39pub fn svg_rect(x: f64, y: f64, width: f64, height: f64, transform: Option<&str>) -> String {
40    match transform {
41        Some(t) => format!(
42            r#"<rect x="{}" y="{}" width="{}" height="{}" transform="{}"/>"#,
43            x, y, width, height, t
44        ),
45        None => format!(
46            r#"<rect x="{}" y="{}" width="{}" height="{}"/>"#,
47            x, y, width, height
48        ),
49    }
50}
51
52/// Helper to create SVG path element.
53pub fn svg_path(d: &str, clip_rule: Option<&str>, transform: Option<&str>) -> String {
54    let mut attrs = format!(r#"d="{}""#, d);
55    if let Some(rule) = clip_rule {
56        attrs.push_str(&format!(r#" clip-rule="{}""#, rule));
57    }
58    if let Some(t) = transform {
59        attrs.push_str(&format!(r#" transform="{}""#, t));
60    }
61    format!(r#"<path {}/>"#, attrs)
62}