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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use crate::prelude::*;
use std::fmt;
use std::io::{self, Write};

pub struct Path {
    pub stroke_width: f64,
    pub stroke_color: Color,
    pub fill_color: Color,
    pub data: Data,
}

pub struct Data(pub Vec<Pos>);

pub struct Document {
    pub frame: Frame,
    pub items: Vec<Path>,
}

impl Data {
    pub fn new(pos: Pos) -> Self {
        Self(vec![pos])
    }

    pub fn line_to(&mut self, pos: Pos) {
        self.0.push(pos);
    }

    pub fn with_line_to(mut self, pos: Pos) -> Self {
        self.0.push(pos);
        self
    }
}

impl Path {
    pub fn new(d: Data) -> Self {
        Self {
            stroke_width: 0.0,
            stroke_color: Color(0, 0, 0),
            fill_color: Color(255, 255, 255),
            data: d,
        }
    }

    pub fn with_fill_color(mut self, c: Color) -> Self {
        self.fill_color = c;
        self
    }

    pub fn with_stroke_color(mut self, c: Color) -> Self {
        self.stroke_color = c;
        self
    }

    pub fn with_stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = w;
        self
    }
}

impl Document {
    pub fn new(frame: Frame) -> Self {
        Self {
            frame,
            items: Vec::new(),
        }
    }

    pub fn add(&mut self, path: Path) {
        self.items.push(path);
    }

    pub fn save(&self, dest: &str) -> io::Result<()> {
        if dest.ends_with(".svg") || dest.ends_with(".svg.tmp") {
            let mut buffer = std::fs::File::create(dest)?;
            buffer.write_all(&format!("{}", &self).into_bytes())
        } else if dest.ends_with(".png") || dest.ends_with(".png.tmp") {
            #[cfg(feature = "make-png")]
            {
                // The following code uses functionality from two crates licensed under MPL 2.0
                //   usvg: https://crates.io/crates/usvg
                //   resvg: https://crates.io/crates/resvg
                let svg_data = format!("{}", &self);
                let tree = match usvg::Tree::from_str(&svg_data, &usvg::Options::default()) {
                    Ok(tree) => tree,
                    Err(_) => {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidData,
                            "Failed to parse svg",
                        ))
                    }
                };
                let fit_to = usvg::FitTo::Original;
                let bg = None;
                let converted = match resvg::render(&tree, fit_to, bg) {
                    Some(img) => img,
                    None => {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidData,
                            "Failed to convert to png",
                        ))
                    }
                };
                match converted.save_png(dest) {
                    Ok(_) => Ok(()),
                    Err(_) => {
                        return Err(io::Error::new(
                            io::ErrorKind::AddrNotAvailable,
                            "Could not save image",
                        ))
                    }
                }
            }
            #[cfg(not(feature = "make-png"))]
            {
                Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "PNG is not supported with the current feature flags --  Make sure to include the feature 'make-png' to access this option -- See 'https://doc.rust-lang.org/cargo/reference/features.html' to learn how to do it",
                ))
            }
        } else {
            Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Can only support .svg and .png extensions",
            ))
        }
    }
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "<path d=\"{}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"{}\" />",
            self.data, self.fill_color, self.stroke_color, self.stroke_width
        )
    }
}

impl fmt::Display for Data {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if !self.0.is_empty() {
            let Pos(x, y) = self.0[0];
            write!(f, "M{},{} ", x, y)?;
        }
        for Pos(x, y) in self.0.iter().skip(1) {
            write!(f, "L{},{} ", x, y)?;
        }
        write!(f, "z")
    }
}

impl fmt::Display for Document {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let (x1, y1, x2, y2) = self.frame.into_tuple();
        let src = String::from("http://www.w3.org/2000/svg");
        writeln!(
            f,
            "<svg viewBox=\"{} {} {} {}\" xmlns=\"{}\">",
            x1, y1, x2, y2, src
        )?;
        for p in self.items.iter() {
            writeln!(f, "{}", p)?;
        }
        write!(f, "</svg>")
    }
}