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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use crate::core::color::Color;
use crate::core::format::{ClipHandle, RenderBackend};
use crate::core::geometry::Point;
use crate::core::style::StyleAttr;
use std::collections::HashMap;
static SVG_HEADER: &str =
    r#"<?xml version="1.0" encoding="UTF-8" standalone="no"?>"#;
static SVG_DEFS: &str = r#"<defs>
<marker id="startarrow" markerWidth="10" markerHeight="7"
refX="0" refY="3.5" orient="auto">
<polygon points="10 0, 10 7, 0 3.5" />
</marker>
<marker id="endarrow" markerWidth="10" markerHeight="7"
refX="10" refY="3.5" orient="auto">
<polygon points="0 0, 10 3.5, 0 7" />
</marker>
</defs>"#;
static SVG_FOOTER: &str = "</svg>";
fn escape_string(x: &str) -> String {
    let mut res = String::new();
    for c in x.chars() {
        match c {
            '&' => {
                res.push_str("&");
            }
            '<' => {
                res.push_str("<");
            }
            '>' => {
                res.push_str(">");
            }
            '"' => {
                res.push_str(""");
            }
            '\'' => {
                res.push_str("'");
            }
            _ => {
                res.push(c);
            }
        }
    }
    res
}
pub struct SVGWriter {
    content: String,
    view_size: Point,
    counter: usize,
    font_style_map: HashMap<usize, (String, String)>,
    clip_regions: Vec<String>,
}
impl SVGWriter {
    pub fn new() -> SVGWriter {
        SVGWriter {
            content: String::new(),
            view_size: Point::zero(),
            counter: 0,
            font_style_map: HashMap::new(),
            clip_regions: Vec::new(),
        }
    }
}
impl Default for SVGWriter {
    fn default() -> Self {
        Self::new()
    }
}
impl Drop for SVGWriter {
    fn drop(&mut self) {}
}
impl SVGWriter {
    fn grow_window(&mut self, point: Point, size: Point) {
        self.view_size.x = self.view_size.x.max(point.x + size.x + 5.);
        self.view_size.y = self.view_size.y.max(point.y + size.y + 5.);
    }
    fn get_or_create_font_style(&mut self, font_size: usize) -> String {
        if let Option::Some(x) = self.font_style_map.get(&font_size) {
            return x.0.clone();
        }
        let class_name = format!("a{}", font_size);
        let class_impl = format!(
            ".a{} {{ font-size: {}px; font-family: Times, serif; }}",
            font_size, font_size
        );
        let impl_ = (class_name.clone(), class_impl);
        self.font_style_map.insert(font_size, impl_);
        class_name
    }
    fn emit_svg_font_styles(&self) -> String {
        let mut content = String::new();
        content.push_str("<style>\n");
        for p in self.font_style_map.iter() {
            content.push_str(&p.1 .1);
            content.push('\n');
        }
        content.push_str("</style>\n");
        for p in self.clip_regions.iter() {
            content.push_str(p);
            content.push('\n');
        }
        content
    }
    pub fn finalize(&self) -> String {
        let mut result = String::new();
        result.push_str(SVG_HEADER);
        let svg_line = format!(
            "<svg width=\"{}\" height=\"{}\" viewBox=\"0 0 {} {}\
            \" xmlns=\"http://www.w3.org/2000/svg\">\n",
            self.view_size.x,
            self.view_size.y,
            self.view_size.x,
            self.view_size.y
        );
        result.push_str(&svg_line);
        result.push_str(SVG_DEFS);
        result.push_str(&self.emit_svg_font_styles());
        result.push_str(&self.content);
        result.push_str(SVG_FOOTER);
        result
    }
}
impl RenderBackend for SVGWriter {
    fn draw_rect(
        &mut self,
        xy: Point,
        size: Point,
        look: &StyleAttr,
        clip: Option<ClipHandle>,
    ) {
        self.grow_window(xy, size);
        let mut clip_option = String::new();
        if let Option::Some(clip_id) = clip {
            clip_option = format!("clip-path=\"url(#C{})\"", clip_id);
        }
        let fill_color = look.fill_color.unwrap_or_else(Color::transparent);
        let stroke_width = look.line_width;
        let stroke_color = look.line_color;
        let rounded_px = look.rounded;
        let line1 = format!(
            "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"{}\" 
            stroke-width=\"{}\" stroke=\"{}\" rx=\"{}\" {} />\n",
            xy.x,
            xy.y,
            size.x,
            size.y,
            fill_color.to_web_color(),
            stroke_width,
            stroke_color.to_web_color(),
            rounded_px,
            clip_option
        );
        self.content.push_str(&line1);
    }
    fn draw_circle(&mut self, xy: Point, size: Point, look: &StyleAttr) {
        self.grow_window(xy, size);
        let fill_color = look.fill_color.unwrap_or_else(Color::transparent);
        let stroke_width = look.line_width;
        let stroke_color = look.line_color;
        let line1 = format!(
            "<ellipse cx=\"{}\" cy=\"{}\" rx=\"{}\" ry=\"{}\" fill=\"{}\" 
            stroke-width=\"{}\" stroke=\"{}\"/>\n",
            xy.x,
            xy.y,
            size.x / 2.,
            size.y / 2.,
            fill_color.to_web_color(),
            stroke_width,
            stroke_color.to_web_color()
        );
        self.content.push_str(&line1);
    }
    fn draw_text(&mut self, xy: Point, text: &str, look: &StyleAttr) {
        let len = text.len();
        let font_class = self.get_or_create_font_style(look.font_size);
        let mut content = String::new();
        let cnt = 1 + text.lines().count();
        let size_y = (cnt * look.font_size) as f64;
        for line in text.lines() {
            content.push_str(&format!("<tspan x = \"{}\" dy=\"1.0em\">", xy.x));
            content.push_str(&escape_string(line));
            content.push_str("</tspan>");
        }
        self.grow_window(xy, Point::new(10., len as f64 * 10.));
        let line = format!(
            "<text dominant-baseline=\"middle\" text-anchor=\"middle\" 
            x=\"{}\" y=\"{}\" class=\"{}\">{}</text>",
            xy.x,
            xy.y - size_y / 2.,
            font_class,
            &content
        );
        self.content.push_str(&line);
    }
    fn draw_arrow(
        &mut self,
        path: &[(Point, Point)],
        dashed: bool,
        head: (bool, bool),
        look: &StyleAttr,
        text: &str,
    ) {
        for point in path {
            self.grow_window(point.0, Point::zero());
            self.grow_window(point.1, Point::zero());
        }
        let dash = if dashed {
            &"stroke-dasharray=\"5,5\""
        } else {
            &""
        };
        let start = if head.0 {
            "marker-start=\"url(#startarrow)\""
        } else {
            ""
        };
        let end = if head.1 {
            "marker-end=\"url(#endarrow)\""
        } else {
            ""
        };
        let mut path_builder = String::new();
        path_builder.push_str(&format!(
            "M {} {} C {} {}, {} {}, {} {} ",
            path[0].0.x,
            path[0].0.y,
            path[0].1.x,
            path[0].1.y,
            path[1].0.x,
            path[1].0.y,
            path[1].1.x,
            path[1].1.y
        ));
        for point in path.iter().skip(2) {
            path_builder.push_str(&format!(
                "S {} {}, {} {} ",
                point.0.x, point.0.y, point.1.x, point.1.y
            ));
        }
        let stroke_width = look.line_width;
        let stroke_color = look.line_color;
        let line = format!(
            "<path id=\"arrow{}\" d=\"{}\" \
            stroke=\"{}\" stroke-width=\"{}\" {} {} {} 
            fill=\"transparent\" />\n",
            self.counter,
            path_builder.as_str(),
            stroke_color.to_web_color(),
            stroke_width,
            dash,
            start,
            end
        );
        self.content.push_str(&line);
        let font_class = self.get_or_create_font_style(look.font_size);
        let line = format!(
            "<text><textPath href=\"#arrow{}\" startOffset=\"50%\" \
            text-anchor=\"middle\" class=\"{}\">{}</textPath></text>",
            self.counter,
            font_class,
            escape_string(text)
        );
        self.content.push_str(&line);
        self.counter += 1;
    }
    fn draw_line(&mut self, start: Point, stop: Point, look: &StyleAttr) {
        let stroke_width = look.line_width;
        let stroke_color = look.line_color;
        let line1 = format!(
            "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke-width=\"{}\"
             stroke=\"{}\" />\n",
            start.x,
            start.y,
            stop.x,
            stop.y,
            stroke_width,
            stroke_color.to_web_color()
        );
        self.content.push_str(&line1);
    }
    fn create_clip(
        &mut self,
        xy: Point,
        size: Point,
        rounded_px: usize,
    ) -> ClipHandle {
        let handle = self.clip_regions.len();
        let clip_code = format!(
            "<clipPath id=\"C{}\"><rect x=\"{}\" y=\"{}\" \
            width=\"{}\" height=\"{}\" rx=\"{}\" /> \
            </clipPath>",
            handle, xy.x, xy.y, size.x, size.y, rounded_px
        );
        self.clip_regions.push(clip_code);
        handle
    }
}