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
use treexml::Element;

trait InsertAttribute {
    fn insert_attribute<S1, S2>(&mut self, attr: S1, val: S2)
        where S1: Into<String>, S2: Into<String>;
}

impl InsertAttribute for Element {
    fn insert_attribute<S1, S2>(&mut self, attr: S1, val: S2)
        where S1: Into<String>, S2: Into<String>
    {
        self.attributes.insert(attr.into(), val.into());
    }
}

//@ A silly numeric representation.
//@ For `Dec(a,b)`, `a` is the integral part and `b` is the fractional part,
//@ in the sense that the printed string form of the number is `a.b`.
//@
//@ (Basically this makes reading and writing literal forms very easy
//@ but makes every other aspect of arithmetic hard.)
//@
//@ Why is it silly? Well, beyond things like making arithmetic hard,
//@ it also conflates values; e.g. a fractional part of `1` is the same
//@ as one of `10`, and `100`, et cetera.
//@
//@ Even worse, one cannot represent `1.01` with this data type as
//@ currently defined. (That might be the killer issue for me, in
//@ fact, because I am worried about such intermediate values arising
//@ in practice.  I probably will switch to a different representation
//@ and try to just add `Dec(a,b)` as a constructor function.

#[derive(Copy, Clone, PartialEq, Eq)]
struct Dec(u32, u32);

pub fn correct(frac: u32, new_frac: u32) -> (u32, u32) {
    let denom = denom(frac);
    let carry = new_frac / denom;
    let rem = new_frac - (carry * denom);
    (carry, rem)
}

fn denom(frac: u32) -> u32 {
    match frac {
        0       ...9        => 10,
        10      ...99       => 100,
        100     ...999      => 1000,
        1000    ...9999     => 10000,
        10000   ...99999    => 100000,
        100000  ...999999   => 1000000,
        1000000 ...9999999  => 10000000,
        10000000...99999999 => 100000000,
        _ => unimplemented!(),
    }
}

impl Dec {
    fn scale(&self, scale: u32) -> Dec {
        let Dec(nat, frac) = *self;
        // if frac == 0 { return (nat * scale, 0); }
        let (carry, rem) = correct(frac, frac * scale);
        Dec(nat * scale + carry, rem)
    }

    #[allow(dead_code)]
    fn add_half(&self) -> Dec {
        let Dec(nat, frac) = *self;
        let denom = denom(frac) / 10;
        let (carry, rem) = correct(frac, frac + 5 * denom);
        Dec(nat + carry, rem)
    }

    fn sub_half(&self) -> Dec {
        let Dec(nat, frac) = *self;
        let denom = denom(frac) / 10;
        if frac >= 5 * denom {
            Dec(nat, frac - 5 * denom)
        } else {
            assert!(nat >= 1, "Dec {}.{} sub_half() failed", nat, frac);
            Dec(nat - 1, 5 * denom + frac)
        }
    }
}

/// `Dim` is a measure of dimension. They are meant to carry units,
/// though it can be omitted via the `U` variant.
#[derive(Copy, Clone, PartialEq, Debug)] // if we ever impl PartialOrd, do it explicitly.
pub enum Dim {
    /// Unit-less; e.g. U(50,1) is "50.1"
    U(u32, u32),
    /// Pixel count; e.g. Px(50) is "50px"
    Px(u32),
    /// Pct stands for "Percent". e.g. Pc(50) is "50%"
    Pc(u32, u32),

    // Unit-less computed floating-point value. Results from internal usage
    // of things like sqrt.
    FU(f64)
}

impl Default for Dim {
    fn default() -> Self { Dim::U(0, 0) }
}

impl Dim {
    pub fn to_string(&self) -> String {
        match *self {
            Dim::U(s, 0) => format!("{}", s),
            Dim::U(n, d) => format!("{}.{}", n, d),
            Dim::Px(s) => format!("{}px", s),
            Dim::Pc(s, 0) => format!("{}%", s),
            Dim::Pc(n, d) => format!("{}.{}%", n, d),
            Dim::FU(x) => format!("{}", x),
        }
    }

    fn to_dec(&self) -> Dec {
        match *self {
            Dim::U(s, f) => Dec(s, f),
            Dim::Px(_) => panic!("should never convert pixel dim to Dec"),
            Dim::Pc(s, f) => Dec(s, f),
            Dim::FU(_) => panic!("should never convert computed float to Dec"),
        }
    }

    #[allow(dead_code)]
    pub(crate) fn add_half(&self) -> Dim {
        match *self {
            Dim::U(..) => self.to_dec().add_half().to_u(),
            Dim::Px(_) => panic!("should never add half to pixel dim"),
            Dim::Pc(..) => self.to_dec().add_half().to_pc(),
            Dim::FU(..) => panic!("should never add half to computed float"),
        }
    }

    pub(crate) fn sub_half(&self) -> Dim {
        match *self {
            Dim::U(..) => self.to_dec().sub_half().to_u(),
            Dim::Px(_) => panic!("should never sub half from pixel dim"),
            Dim::Pc(..) => self.to_dec().sub_half().to_pc(),
            Dim::FU(_) => panic!("should never sub half from computed float"),
        }
    }

    #[allow(dead_code)]
    pub(crate) fn sub_one(&self) -> Dim {
        self.sub_half().sub_half()
    }

    #[allow(dead_code)]
    pub(crate) fn div_2(&self) -> Dim {
        match *self {
            Dim::U(n,0) if n % 2 == 0 => Dim::U(n/2,0),
            Dim::U(n,0) if n % 2 == 1 => Dim::U(n/2,5),
            Dim::Pc(n,0) if n % 2 == 0 => Dim::Pc(n/2,0),
            Dim::Pc(n,0) if n % 2 == 1 => Dim::Pc(n/2,5),
            _ => unimplemented!(),
        }
    }

    pub(crate) fn addf(&self, x: f64) -> Dim {
        match *self {
            Dim::FU(y) => Dim::FU(y + x),
            Dim::U(s, 0) => Dim::FU(s as f64 + x),
            Dim::U(n, d) => Dim::FU(format!("{}.{}", n, d).parse::<f64>().unwrap() + x),
            _ => unimplemented!(),
        }
    }

    pub(crate) fn subf(&self, x: f64) -> Dim { self.addf(-x) }
}

trait ToDimU { fn to_u(&self) -> Dim; }
trait ToDimPx {  fn to_px(&self) -> Dim; }
trait ToDimPc { fn to_pc(&self) -> Dim; }

impl ToDimU  for (u32, u32) { fn to_u(&self) -> Dim { Dim::U(self.0, self.1) } }
impl ToDimU  for Dec { fn to_u(&self) -> Dim { Dim::U(self.0, self.1) } }
impl ToDimU  for u32        { fn to_u(&self) -> Dim { Dim::U(*self, 0) } }
impl ToDimPx for u32        { fn to_px(&self) -> Dim { Dim::Px(*self) } }
impl ToDimPc for (u32, u32) { fn to_pc(&self) -> Dim { Dim::Pc(self.0, self.1) } }
impl ToDimPc for Dec { fn to_pc(&self) -> Dim { Dim::Pc(self.0, self.1) } }

use std::ops::Mul;
impl Mul<u32> for Dim {
    type Output = Dim;
    fn mul(self, rhs: u32) -> Dim {
        match self {
            Dim::U(..)  => self.to_dec().scale(rhs).to_u(),
            Dim::Px(n)   => (n*rhs).to_px(),
            Dim::Pc(..) => self.to_dec().scale(rhs).to_pc(),
            Dim::FU(x) => Dim::FU(x * (rhs as f64)),
        }
    }
}

mod color;
pub use self::color::Color;

#[derive(Clone, PartialEq, Eq)]
pub enum Fill {
    Color(Color),
    Pattern { def_id: String },
    None,
}

impl Fill {
    fn into_string(self) -> String {
        match self {
            Fill::Color(c) => c.into_string(),
            Fill::Pattern { def_id } => format!("url(#{})", def_id),
            Fill::None => "none".to_string()
        }
    }
}

pub struct Rect {
    pub x: Dim,
    pub y: Dim,
    pub width: Dim,
    pub height: Dim,
    pub fill: Fill,
    pub stroke: Option<(Fill, Dim)>,
    pub rounded: Option<(Dim, Dim)>,
    pub id: Option<String>,
    pub attrs: Vec<(String, String)>,
}

pub trait ToElement {
    fn to_element(&self) -> Element;
}

pub trait IntoElement {
    fn into_element(self) -> Element;
}

impl IntoElement for Rect {
    fn into_element(self) -> Element {
        let mut e = Element::new("rect");
        let Rect { x, y, width, height, fill, stroke, rounded, id, attrs } = self;
        e.insert_attribute("x", x.to_string());
        e.insert_attribute("y", y.to_string());
        e.insert_attribute("width", width.to_string());
        e.insert_attribute("height", height.to_string());
        e.insert_attribute("fill", fill.into_string());
        if let Some((stroke, stroke_width)) = stroke {
            e.insert_attribute("stroke", stroke.into_string());
            e.insert_attribute("stroke-width", stroke_width.to_string());
        }
        if let Some((rx, ry)) = rounded {
            e.insert_attribute("rx", rx.to_string());
            e.insert_attribute("ry", ry.to_string());
        }
        if let Some(id) = id {
            e.insert_attribute("id", id);
        }
        for (k,v) in attrs {
            e.insert_attribute(k, v);
        }
        e
    }
}

pub struct Circle { pub cx: Dim, pub cy: Dim, pub r: Dim, pub fill: Color }

impl IntoElement for Circle {
    fn into_element(self) -> Element {
        let mut e = Element::new("circle");
        e.insert_attribute("cx", self.cx.to_string());
        e.insert_attribute("cy", self.cy.to_string());
        e.insert_attribute("r", self.r.to_string());
        e.insert_attribute("fill", self.fill.into_string());
        e
    }
}

pub use self::text::Text;

impl IntoElement for Text {
    fn into_element(self) -> Element {
        // FIXME adhering to the grid layout is paramount for some
        // text objects. I should add way for such objects to indicate
        // that via an attached attribute.

        let mut e = Element::new("text");
        e.insert_attribute("x", self.x.to_string());
        e.insert_attribute("y", self.y.to_string());
        e.insert_attribute("font-family", self.font_family);
        e.insert_attribute("font-size", self.font_size.to_string());
        e.insert_attribute("text-anchor", self.text_anchor.to_string());
        e.insert_attribute("fill", self.fill.into_string());
        e.insert_attribute("dominant-baseline", "middle".to_string());
        e.insert_attribute("xml:space", "preserve".to_string());
        if let Some(id) = self.id {
            e.insert_attribute("id", id);
        }
        for (k, v) in self.attrs {
            e.insert_attribute(k, v);
        }
        e.text = Some(self.content);
        e
    }
}

pub struct Path { pub d: String, pub attrs: Vec<(String, String)> }

impl IntoElement for Path {
    fn into_element(self) -> Element {
        let mut e = Element::new("path");
        e.insert_attribute("d", self.d);
        for (k, v) in self.attrs {
            e.insert_attribute(k, v);
        }
        e
    }
}

pub mod text {
    use super::{Color, Dim};

    #[derive(Debug)]
    pub enum TextAnchor {
        Start,
        Middle,
        End,
    }

    impl TextAnchor {
        pub fn to_string(&self) -> String {
            match *self {
                TextAnchor::Middle => "middle".to_string(),
                TextAnchor::Start => "start".to_string(),
                TextAnchor::End => "end".to_string(),
            }
        }
    }

    #[derive(Debug)]
    pub struct Text {
        pub x: Dim,
        pub y: Dim,
        pub font_family: String,
        pub font_size: Dim,
        pub text_anchor: TextAnchor,
        pub fill: Color,
        pub content: String,
        pub id: Option<String>,
        pub attrs: Vec<(String, String)>,
    }
}

pub enum Shape {
    Rect(Rect),
    Circle(Circle),
    Text(Text),
    Path(Path),
}

impl IntoElement for Shape {
    fn into_element(self) -> Element {
        match self {
            Shape::Rect(r) => r.into_element(),
            Shape::Circle(c) => c.into_element(),
            Shape::Text(t) => t.into_element(),
            Shape::Path(p) => p.into_element(),
        }
    }
}

pub trait IntoShape { fn into_shape(self) -> Shape; }

impl IntoShape for Rect { fn into_shape(self) -> Shape { Shape::Rect(self) } }
impl IntoShape for Circle { fn into_shape(self) -> Shape { Shape::Circle(self) } }
impl IntoShape for Text { fn into_shape(self) -> Shape { Shape::Text(self) } }
impl IntoShape for Path { fn into_shape(self) -> Shape { Shape::Path(self) } }

pub struct Svg {
    doc: Element,
}

impl IntoElement for Svg {
    fn into_element(self) -> Element { self.doc }
}

use std::fmt;

impl fmt::Display for Svg {
    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
        self.doc.fmt(w)
    }
}

impl Svg {
    /// Create an SVG doc of given `width` and `height`.
    pub fn new(width: u32, height: u32) -> Svg {
        let mut doc = Element::new("svg");
        doc.insert_attribute("version", "1.1");
        doc.insert_attribute("baseProfile", "full");
        doc.insert_attribute("xmlns", "http://www.w3.org/2000/svg");
        doc.insert_attribute("width", width.to_string());
        doc.insert_attribute("height", height.to_string());

//@ Using a `viewBox` ensures that the content will be rendered according to
//@ the width and height of the columns and rows in the original picture, even
//@ if it is being forcibly shrunk or zoomed by the width and height that we
//@ want the rendered SVG to fill.

        doc.insert_attribute("viewBox",
                             format!("0 0 {} {}",
                                     width.to_string(), height.to_string()));
        Svg { doc: doc }
    }

    /// Add (or overwrite) an attribute on the SVG document.
    pub fn insert_attribute<S1, S2>(&mut self, attr: S1, val: S2)
        where S1: Into<String>, S2: Into<String>
    {
        self.doc.attributes.insert(attr.into(), val.into());
    }

    /// Returns the version of the SVG document. Documents start by default at version 1.1.
    pub fn version(&self) -> &str { &self.doc.attributes["version"] }

    /// Returns the element children of the SVG document.
    pub fn children(&self) -> &[Element] { &self.doc.children }

    /// Returns the width of the SVG document.
    pub fn width(&self) -> u32 { self.doc.attributes["width"].parse::<u32>().unwrap() }

    /// Returns the height of the SVG document.
    pub fn height(&self) -> u32 { self.doc.attributes["height"].parse::<u32>().unwrap() }

    /// Adds the given shape as a child element.
    pub fn add_child_shape<S:IntoShape>(&mut self, s: S) {
        self.doc.children.push(s.into_shape().into_element());
    }

    /// Adds the given named object as an (unrendered but referencable) definition.
    pub fn add_def<Def:Identified>(&mut self, def: Def) {
        let def = def.into_element();
        if let Some(defs) = self.doc.find_child_mut(|e| e.name == "defs") {
            defs.children.push(def);
            return;
        }
        self.doc.children.push(Element::new("defs"));
        let defs = self.doc.children.last_mut().unwrap();
        defs.children.push(def);
    }
}

pub struct Pattern {
    pub id: String,
    pub width: u32,
    pub height: u32,
    pub content: Vec<Shape>,
}

impl IntoElement for Pattern {
    fn into_element(self) -> Element {
        let mut e = Element::new("pattern");
        e.insert_attribute("id", self.id);
        e.insert_attribute("width", self.width.to_string());
        e.insert_attribute("height", self.height.to_string());
        e.insert_attribute("patternUnits", "userSpaceOnUse");
        for shape in self.content {
            e.children.push(shape.into_element());
        }
        e
    }
}

impl Identified for Pattern {
    fn id(&self) -> &str { &self.id }
}

/// `Identified` marks an XML element-structure that is known to carry
/// an `id` attribute, and thus is suitable for e.g. putting into a
/// `defs` block.
pub trait Identified: IntoElement {
    fn id(&self) -> &str;
}



#[cfg(test)]
mod tests {
    use super::{Svg, Fill, Color, Circle, Rect, Text, Dim};
    use super::{text};

    #[test]
    fn it_works() {
        let s = Svg::new(300, 200);
        assert_eq!(s.version(), "1.1");
        assert_eq!(s.width(), 300);
        assert_eq!(s.height(), 200);
    }

    #[test]
    fn dmo_simple_example() {
        let mut s = Svg::new(300, 200);
        s.add_child_shape(Rect { x: Dim::U(0,0),
                                 y: Dim::U(0,0),
                                 width: Dim::Pc(100,0),
                                 height: Dim::Pc(100,0),
                                 fill: Fill::Color(Color::Red),
                                 stroke: None,
                                 rounded: None,
                                 id: None,
                                 attrs: vec![],
        });
        s.add_child_shape(Circle { cx: Dim::U(150,0),
                                   cy: Dim::U(100,0),
                                   r: Dim::U(80,0),
                                   fill: Color::Green });
        s.add_child_shape(Text { x: Dim::U(150,0),
                                 y: Dim::U(125,0),
                                 font_family: "Monaco".to_string(),
                                 font_size: Dim::U(60,0),
                                 text_anchor: text::TextAnchor::Middle,
                                 fill: Color::White,
                                 content: "SVG".to_string(),
                                 id: None,
                                 attrs: vec![],
        });
    }
}