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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
use std::fmt;

/// `rgb({r},{g},{b})`
#[derive(Copy, Clone, PartialEq)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl Default for Color {
    fn default() -> Self {
        black()
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "rgb({},{},{})", self.r, self.g, self.b)
    }
}

pub fn rgb(r: u8, g: u8, b: u8) -> Color {
    Color { r, g, b }
}
pub fn black() -> Color {
    rgb(0, 0, 0)
}
pub fn white() -> Color {
    rgb(255, 255, 255)
}
pub fn red() -> Color {
    rgb(255, 0, 0)
}
pub fn green() -> Color {
    rgb(0, 255, 0)
}
pub fn blue() -> Color {
    rgb(0, 0, 255)
}

/// `fill:{self}`
#[derive(Copy, Clone, PartialEq)]
pub enum Fill {
    Color(Color),
    None,
}

impl Default for Fill {
    fn default() -> Self {
        Fill::None
    }
}

/// `stroke:{self}`
#[derive(Copy, Clone, PartialEq)]
pub enum Stroke {
    Color(Color, f32),
    None,
}

impl Default for Stroke {
    fn default() -> Self {
        Stroke::Color(black(), 1.0)
    }
}

/// `fill:{fill};stroke:{stroke};fill-opacity:{opacity};`
#[derive(Copy, Clone, PartialEq)]
pub struct Style {
    pub fill: Fill,
    pub stroke: Stroke,
    pub opacity: f32,
    pub stroke_opacity: f32,
}

impl fmt::Display for Style {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{};{};fill-opacity:{};stroke-opacity:{};",
            self.fill, self.stroke, self.opacity, self.stroke_opacity,
        )
    }
}

impl Default for Style {
    fn default() -> Self {
        Style {
            fill: Fill::Color(black()),
            stroke: Stroke::None,
            opacity: 1.0,
            stroke_opacity: 1.0,
        }
    }
}

impl From<Fill> for Style {
    fn from(fill: Fill) -> Style {
        Style {
            fill,
            stroke: Stroke::None,
            .. Default::default()
        }
    }
}

impl From<Stroke> for Style {
    fn from(stroke: Stroke) -> Style {
        Style {
            fill: Fill::None,
            stroke,
            .. Default::default()
        }
    }
}

impl fmt::Display for Fill {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Fill::Color(color) => write!(f, "fill:{}", color),
            Fill::None => write!(f, "fill:none"),
        }
    }
}

impl fmt::Display for Stroke {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Stroke::Color(color, radius) => write!(f, "stroke:{};stroke-width:{}", color, radius),
            Stroke::None => write!(f, "stroke:none"),
        }
    }
}

impl Into<Fill> for Color {
    fn into(self) -> Fill {
        Fill::Color(self)
    }
}

impl Into<Stroke> for Color {
    fn into(self) -> Stroke {
        Stroke::Color(self, 1.0)
    }
}

/// `<rect x="{x}" y="{y}" width="{w}" height="{h}" ... />`,
#[derive(Clone, PartialEq)]
pub struct Rectangle {
    pub x: f32,
    pub y: f32,
    pub w: f32,
    pub h: f32,
    pub style: Style,
    pub border_radius: f32,
    pub comment: Option<Comment>,
}

pub fn rectangle(x: f32, y: f32, w: f32, h: f32) -> Rectangle {
    Rectangle {
        x,
        y,
        w,
        h,
        style: Style::default(),
        border_radius: 0.0,
        comment: None,
    }
}

impl Rectangle {
    pub fn fill<F>(mut self, fill: F) -> Self
    where
        F: Into<Fill>,
    {
        self.style.fill = fill.into();
        self
    }

    pub fn stroke<S>(mut self, stroke: S) -> Self
    where
        S: Into<Stroke>,
    {
        self.style.stroke = stroke.into();
        self
    }

    pub fn opacity(mut self, opacity: f32) -> Self {
        self.style.opacity = opacity;
        self
    }

    pub fn stroke_opacity(mut self, opacity: f32) -> Self {
        self.style.stroke_opacity = opacity;
        self
    }

    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    pub fn border_radius(mut self, r: f32) -> Self {
        self.border_radius = r;
        self
    }

    pub fn offset(mut self, dx: f32, dy: f32) -> Self {
        self.x += dx;
        self.y += dy;
        self
    }

    pub fn inflate(mut self, dx: f32, dy: f32) -> Self {
        self.x -= dx;
        self.y -= dy;
        self.w += 2.0 * dx;
        self.h += 2.0 * dy;
        self
    }

    pub fn comment(mut self, text: &str) -> Self {
        self.comment = Some(comment(text));
        self
    }
}

impl fmt::Display for Rectangle {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            r#"<rect x="{}" y="{}" width="{}" height="{}" ry="{}" style="{}""#,
            self.x, self.y, self.w, self.h, self.border_radius, self.style,
        )?;
        if let Some(comment) = &self.comment {
            write!(f, r#">{}</rect>"#, comment)?;
        } else {
            write!(f, r#" />"#)?;
        }
        Ok(())
    }
}

/// `<circle cx="{x}" cy="{y}" r="{radius}" .../>`
#[derive(Clone, PartialEq)]
pub struct Circle {
    pub x: f32,
    pub y: f32,
    pub radius: f32,
    pub style: Style,
    pub comment: Option<Comment>,
}

impl Circle {
    pub fn fill<F>(mut self, fill: F) -> Self
    where
        F: Into<Fill>,
    {
        self.style.fill = fill.into();
        self
    }

    pub fn stroke<S>(mut self, stroke: S) -> Self
    where
        S: Into<Stroke>,
    {
        self.style.stroke = stroke.into();
        self
    }

    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    pub fn opacity(mut self, opacity: f32) -> Self {
        self.style.opacity = opacity;
        self
    }

    pub fn stroke_opacity(mut self, opacity: f32) -> Self {
        self.style.stroke_opacity = opacity;
        self
    }

    pub fn offset(mut self, dx: f32, dy: f32) -> Self {
        self.x += dx;
        self.y += dy;
        self
    }

    pub fn inflate(mut self, by: f32) -> Self {
        self.radius += by;
        self
    }

    pub fn comment(mut self, text: &str) -> Self {
        self.comment = Some(comment(text));
        self
    }
}

impl fmt::Display for Circle {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            r#"<circle cx="{}" cy="{}" r="{}" style="{}""#,
            self.x, self.y, self.radius, self.style,
        )?;
        if let Some(comment) = &self.comment {
            write!(f, r#">{}</circle>"#, comment)?;
        } else {
            write!(f, r#" />"#)?;
        }
        Ok(())
    }
}

/// `<path d="..." style="..."/>`
#[derive(Clone, PartialEq)]
pub struct Polygon {
    pub points: Vec<[f32; 2]>,
    pub closed: bool,
    pub style: Style,
    pub comment: Option<Comment>,
}

impl fmt::Display for Polygon {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, r#"<path d="#)?;
        if self.points.len() > 0 {
            write!(f, "M {} {} ", self.points[0][0], self.points[0][1])?;
            for &p in &self.points[1..] {
                write!(f, "L {} {} ", p[0], p[1])?;
            }
            if self.closed {
                write!(f, "Z")?;
            }
        }
        write!(f, r#"" style="{}"#, self.style)?;
        if let Some(comment) = &self.comment {
            write!(f, r#">{}</path>"#, comment)?;
        } else {
            write!(f, r#" />"#)?;
        }
        Ok(())
    }
}

pub fn polygon<T: Copy + Into<[f32; 2]>>(pts: &[T]) -> Polygon {
    let mut points = Vec::with_capacity(pts.len());
    for p in pts {
        points.push((*p).into());
    }
    Polygon {
        points,
        closed: true,
        style: Style::default(),
        comment: None,
    }
}

pub fn triangle(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) -> Polygon {
    polygon(&[[x1, y1], [x2, y2], [x3, y3]])
}

impl Polygon {
    pub fn open(mut self) -> Self {
        self.closed = false;
        self
    }

    pub fn fill<F>(mut self, fill: F) -> Self
    where
        F: Into<Fill>,
    {
        self.style.fill = fill.into();
        self
    }

    pub fn stroke<S>(mut self, stroke: S) -> Self
    where
        S: Into<Stroke>,
    {
        self.style.stroke = stroke.into();
        self
    }

    pub fn opacity(mut self, opacity: f32) -> Self {
        self.style.opacity = opacity;
        self
    }

    pub fn stroke_opacity(mut self, opacity: f32) -> Self {
        self.style.stroke_opacity = opacity;
        self
    }

    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    pub fn comment(mut self, text: &str) -> Self {
        self.comment = Some(comment(text));
        self
    }
}

/// `<path d="M {x1} {y1} L {x2} {y2}" ... />`
#[derive(Clone, PartialEq)]
pub struct LineSegment {
    pub x1: f32,
    pub x2: f32,
    pub y1: f32,
    pub y2: f32,
    pub color: Color,
    pub width: f32,
    pub comment: Option<Comment>,
}

impl fmt::Display for LineSegment {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            r#"<path d="M {} {} L {} {}" style="stroke:{};stroke-width:{}""#,
            self.x1, self.y1, self.x2, self.y2, self.color, self.width
        )?;
        if let Some(comment) = &self.comment {
            write!(f, r#">{}</path>"#, comment)?;
        } else {
            write!(f, r#" />"#)?;
        }
        Ok(())
    }
}

pub fn line_segment(x1: f32, y1: f32, x2: f32, y2: f32) -> LineSegment {
    LineSegment {
        x1,
        y1,
        x2,
        y2,
        color: black(),
        width: 1.0,
        comment: None,
    }
}

impl LineSegment {
    pub fn color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub fn width(mut self, width: f32) -> Self {
        self.width = width;
        self
    }

    pub fn offset(mut self, dx: f32, dy: f32) -> Self {
        self.x1 += dx;
        self.y1 += dy;
        self.x2 += dx;
        self.y2 += dy;
        self
    }

    pub fn comment(mut self, text: &str) -> Self {
        self.comment = Some(comment(text));
        self
    }
}

/// `<path d="..." />`
#[derive(Clone, PartialEq)]
pub struct Path {
    pub ops: Vec<PathOp>,
    pub style: Style,
    pub comment: Option<Comment>,
}

/// `M {} {} L {} {} ...`
#[derive(Copy, Clone, PartialEq)]
pub enum PathOp {
    MoveTo {
        x: f32,
        y: f32,
    },
    LineTo {
        x: f32,
        y: f32,
    },
    QuadraticTo {
        ctrl_x: f32,
        ctrl_y: f32,
        x: f32,
        y: f32,
    },
    CubicTo {
        ctrl1_x: f32,
        ctrl1_y: f32,
        ctrl2_x: f32,
        ctrl2_y: f32,
        x: f32,
        y: f32,
    },
    Close,
}
impl fmt::Display for PathOp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            PathOp::MoveTo { x, y } => write!(f, "M {} {} ", x, y),
            PathOp::LineTo { x, y } => write!(f, "L {} {} ", x, y),
            PathOp::QuadraticTo {
                ctrl_x,
                ctrl_y,
                x,
                y,
            } => write!(f, "Q {} {} {} {} ", ctrl_x, ctrl_y, x, y),
            PathOp::CubicTo {
                ctrl1_x,
                ctrl1_y,
                ctrl2_x,
                ctrl2_y,
                x,
                y,
            } => write!(
                f,
                "C {} {} {} {} {} {} ",
                ctrl1_x, ctrl1_y, ctrl2_x, ctrl2_y, x, y
            ),
            PathOp::Close => write!(f, "Z "),
        }
    }
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, r#"<path d=""#)?;
        for op in &self.ops {
            op.fmt(f)?;
        }
        write!(f, r#"" style="{}""#, self.style)?;
        if let Some(comment) = &self.comment {
            write!(f, r#">{}</path>"#, comment)?;
        } else {
            write!(f, r#"/>"#)?;
        }
        Ok(())
    }
}

impl Path {
    pub fn move_to(mut self, x: f32, y: f32) -> Self {
        self.ops.push(PathOp::MoveTo { x, y });
        self
    }

    pub fn line_to(mut self, x: f32, y: f32) -> Self {
        self.ops.push(PathOp::LineTo { x, y });
        self
    }

    pub fn quadratic_bezier_to(mut self, ctrl_x: f32, ctrl_y: f32, x: f32, y: f32) -> Self {
        self.ops.push(PathOp::QuadraticTo {
            ctrl_x,
            ctrl_y,
            x,
            y,
        });
        self
    }

    pub fn cubic_bezier_to(
        mut self,
        ctrl1_x: f32,
        ctrl1_y: f32,
        ctrl2_x: f32,
        ctrl2_y: f32,
        x: f32,
        y: f32,
    ) -> Self {
        self.ops.push(PathOp::CubicTo {
            ctrl1_x,
            ctrl1_y,
            ctrl2_x,
            ctrl2_y,
            x,
            y,
        });
        self
    }

    pub fn close(mut self) -> Self {
        self.ops.push(PathOp::Close);
        self
    }

    pub fn fill<F>(mut self, fill: F) -> Self
    where
        F: Into<Fill>,
    {
        self.style.fill = fill.into();
        self
    }

    pub fn stroke<S>(mut self, stroke: S) -> Self
    where
        S: Into<Stroke>,
    {
        self.style.stroke = stroke.into();
        self
    }

    pub fn opacity(mut self, opacity: f32) -> Self {
        self.style.opacity = opacity;
        self
    }

    pub fn stroke_opacity(mut self, opacity: f32) -> Self {
        self.style.stroke_opacity = opacity;
        self
    }

    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }
}

pub fn path() -> Path {
    Path {
        ops: Vec::new(),
        style: Style::default(),
        comment: None,
    }
}

/// `<text x="{x}" y="{y}" ... > {text} </text>`
#[derive(Clone, PartialEq)]
pub struct Text {
    pub x: f32,
    pub y: f32,
    pub text: String,
    pub color: Color,
    pub align: Align,
    pub size: f32,
    pub comment: Option<Comment>,
}

impl fmt::Display for Text {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            r#"<text x="{}" y="{}" style="font-size:{}px;fill:{};{}">"#,
            self.x, self.y, self.size, self.color, self.align,
        )?;
        if let Some(comment) = &self.comment {
            write!(f, r#" {}"#, comment)?;
        }
        write!(f, r#" {} </text>"#, self.text)
    }
}

pub fn text<T: Into<String>>(x: f32, y: f32, txt: T) -> Text {
    Text {
        x,
        y,
        text: txt.into(),
        color: black(),
        align: Align::Left,
        size: 10.0,
        comment: None,
    }
}

impl Text {
    pub fn color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub fn size(mut self, size: f32) -> Self {
        self.size = size;
        self
    }

    pub fn align(mut self, align: Align) -> Self {
        self.align = align;
        self
    }

    pub fn offset(mut self, dx: f32, dy: f32) -> Self {
        self.x += dx;
        self.y += dy;
        self
    }

    pub fn comment(mut self, text: &str) -> Self {
        self.comment = Some(comment(text));
        self
    }
}

#[derive(Clone, PartialEq)]
pub struct Comment {
    pub text: String,
}

pub fn comment<T: Into<String>>(text: T) -> Comment {
    Comment { text: text.into() }
}

impl fmt::Display for Comment {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "<!-- {} -->", self.text)
    }
}

/// `text-align:{self}`
#[derive(Copy, Clone, PartialEq)]
pub enum Align {
    Left,
    Right,
    Center,
}

impl fmt::Display for Align {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Align::Left => write!(f, "text-anchor:start;text-align:left;"),
            Align::Right => write!(f, "text-anchor:end;text-align:right;"),
            Align::Center => write!(f, "text-anchor:middle;text-align:center;"),
        }
    }
}

/// `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {y}">`
#[derive(Copy, Clone, PartialEq)]
pub struct BeginSvg {
    pub w: f32,
    pub h: f32,
}

impl fmt::Display for BeginSvg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {} {}">"#,
            self.w, self.h,
        )
    }
}

/// `</svg>`
#[derive(Copy, Clone, PartialEq)]
pub struct EndSvg;

impl fmt::Display for EndSvg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "</svg>")
    }
}

/// `"    "`
pub struct Indentation {
    pub n: u32,
}

pub fn indent(n: u32) -> Indentation {
    Indentation { n }
}

impl Indentation {
    pub fn push(&mut self) {
        self.n += 1;
    }

    pub fn pop(&mut self) {
        self.n -= 1;
    }
}

impl fmt::Display for Indentation {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for _ in 0..self.n {
            write!(f, "    ")?;
        }
        Ok(())
    }
}

#[test]
fn foo() {
    println!("{}", BeginSvg { w: 800.0, h: 600.0 });
    println!(
        "    {}",
        rectangle(20.0, 50.0, 200.0, 100.0)
            .fill(red())
            .stroke(Stroke::Color(black(), 3.0))
            .border_radius(5.0)
    );
    println!(
        "    {}",
        text(25.0, 100.0, "Foo!").size(42.0).color(white())
    );
    println!("{}", EndSvg);
}