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
//!
//! poloto - plot to SVG and style with CSS
//!
//! ### Usage
//!
//! Check out the [github examples](https://github.com/tiby312/poloto/tree/master/examples).
//! * Plots containing NaN or Infinity are ignored.
//! * After 8 plots, the colors cycle back and are repeated.
//!
use core::fmt::Write;

pub use tagger;
mod util;

///The poloto prelude.
pub mod prelude {
    pub use super::iter::PlotIterator;
    pub use super::move_format;
}
use core::fmt;

mod render;
pub use render::StyleBuilder;

use iter::DoubleIterator;

///Contains the [`DoubleIterator`] trait and three different
///implementers of it.
pub mod iter;

///Contains building blocks for create the default svg an styling tags from scratch.
pub mod default_tags {
    pub use super::render::NUM_COLORS;
    use core::fmt;

    ///The class of the svg tag.
    pub const CLASS: &str = "poloto";
    ///The width of the svg tag.
    pub const WIDTH: f64 = 800.0;
    ///The height of the svg tag.
    pub const HEIGHT: f64 = 500.0;
    ///The xmlns: `http://www.w3.org/2000/svg`
    pub const XMLNS: &str = "http://www.w3.org/2000/svg";

    ///Write default svg tag attributes.
    pub fn default_svg_attrs<'a, 'b, T: fmt::Write>(
        w: &'a mut tagger::AttributeWriter<'b, T>,
    ) -> Result<&'a mut tagger::AttributeWriter<'b, T>, fmt::Error> {
        use tagger::prelude::*;

        w.attr("class", CLASS)?
            .attr("width", WIDTH)?
            .attr("height", HEIGHT)?
            .with_attr("viewBox", wr!("0 0 {} {}", WIDTH, HEIGHT))?
            .attr("xmlns", XMLNS)
    }
}

trait PlotTrait {
    fn write_name(&self, a: &mut fmt::Formatter) -> fmt::Result;
    fn iter_first(&mut self) -> &mut dyn Iterator<Item = [f64; 2]>;
    fn iter_second(&mut self) -> &mut dyn Iterator<Item = [f64; 2]>;
}

use fmt::Display;
struct Wrapper2<D: DoubleIterator, F: Display> {
    a: Option<D>,
    b: Option<D::Next>,
    func: F,
}

impl<I: DoubleIterator<Item = [f64; 2]>, F: Display> Wrapper2<I, F> {
    fn new(it: I, func: F) -> Self {
        Wrapper2 {
            a: Some(it),
            b: None,
            func,
        }
    }
}

impl<D: DoubleIterator<Item = [f64; 2]>, F: Display> PlotTrait for Wrapper2<D, F> {
    fn write_name(&self, a: &mut fmt::Formatter) -> fmt::Result {
        self.func.fmt(a)
    }
    fn iter_first(&mut self) -> &mut dyn Iterator<Item = [f64; 2]> {
        self.a.as_mut().unwrap()
    }

    fn iter_second(&mut self) -> &mut dyn Iterator<Item = [f64; 2]> {
        self.b = Some(self.a.take().unwrap().finish_first());
        self.b.as_mut().unwrap()
    }
}

enum PlotType {
    Scatter,
    Line,
    Histo,
    LineFill,
}

struct Plot<'a> {
    plot_type: PlotType,
    plots: Box<dyn PlotTrait + 'a>,
}


/// Shorthand for `moveable_format(move |w|write!(w,...))`
/// Similar to `format_args!()` except has a more flexible lifetime.
#[macro_export]
macro_rules! move_format {
    ($($arg:tt)*) => {
        $crate::moveable_format(move |w| write!(w,$($arg)*))
    }
}

/*
pub struct DisplayList<'a, T> {
    seperator: T,
    a: Vec<Box<dyn Display + 'a>>,
}
impl<'a, T: fmt::Display> DisplayList<'a, T> {
    pub fn new(seperator: T) -> Self {
        DisplayList {
            seperator,
            a: Vec::new(),
        }
    }
    pub fn add(&mut self, a: impl Display + 'a) {
        self.a.push(Box::new(a));
    }
}
impl<'a, T: fmt::Display> fmt::Display for DisplayList<'a, T> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        for a in self.a.iter() {
            a.fmt(formatter)?;
            self.seperator.fmt(formatter)?;
        }
        Ok(())
    }
}
*/

///Concatenate two display objects with the specified spacing inbetween.
pub fn concatenate_display(
    spacing: impl fmt::Display,
    a: impl fmt::Display,
    b: impl fmt::Display,
) -> impl fmt::Display {
    struct Foo<A, B, C> {
        spacing: A,
        a: B,
        b: C,
    }
    impl<A, B, C> fmt::Display for Foo<A, B, C>
    where
        A: fmt::Display,
        B: fmt::Display,
        C: fmt::Display,
    {
        fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            self.a.fmt(formatter)?;
            self.spacing.fmt(formatter)?;
            self.b.fmt(formatter)
        }
    }
    Foo { spacing, a, b }
}

///Convert a moved closure into a impl fmt::Display.
///This is useful because std's `format_args!()` macro
///has a shorter lifetime.
pub fn moveable_format(func: impl Fn(&mut fmt::Formatter) -> fmt::Result) -> impl fmt::Display {
    struct Foo<F>(F);
    impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Display for Foo<F> {
        fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            (self.0)(formatter)
        }
    }
    Foo(func)
}

struct NamesStruct<A, B, C,D> {
    title: A,
    xname: B,
    yname: C,
    header: D
}
impl<A: Display, B: Display, C: Display,D:Display> Names for NamesStruct<A, B, C,D> {
    fn write_header(&self, fm: &mut fmt::Formatter) -> fmt::Result {
        self.header.fmt(fm)
    }
    fn write_title(&self, fm: &mut fmt::Formatter) -> fmt::Result {
        self.title.fmt(fm)
    }
    fn write_xname(&self, fm: &mut fmt::Formatter) -> fmt::Result {
        self.xname.fmt(fm)
    }
    fn write_yname(&self, fm: &mut fmt::Formatter) -> fmt::Result {
        self.yname.fmt(fm)
    }
}

///Used internally to write out the header/title/xname/yname.
pub trait Names {
    fn write_header(&self, fm: &mut fmt::Formatter) -> fmt::Result;
    fn write_title(&self, fm: &mut fmt::Formatter) -> fmt::Result;
    fn write_xname(&self, fm: &mut fmt::Formatter) -> fmt::Result;
    fn write_yname(&self, fm: &mut fmt::Formatter) -> fmt::Result;
}

///Convenience function for [`PlotterBuilder`] with default css tag, and with svg tag.
///In most cases, these defaults are good enough.
pub fn plot<'a>(
    title: impl Display + 'a,
    xname: impl Display + 'a,
    yname: impl Display + 'a,
) -> Plotter<'a,impl Names> {
    PlotterBuilder::new()
        .with_data(DataBuilder::new().push_css_default())
        .build(title, xname, yname)
}

#[derive(Copy, Clone)]
enum SvgTagOption {
    Svg,
    NoSvg,
}

///Insert svg data after the svg element, but before the plot elements.
pub struct DataBuilder<D: Display> {
    header: D,
}

impl Default for DataBuilder<&'static str> {
    fn default() -> Self {
        Self::new()
    }
}

impl DataBuilder<&'static str> {
    pub fn new() -> Self {
        DataBuilder { header: "" }
    }
}
impl<D: Display> DataBuilder<D> {
    ///Push the default poloto css styling.
    pub fn push_css_default(self) -> DataBuilder<impl Display> {
        DataBuilder {
            header: concatenate_display("", self.header, StyleBuilder::new().build()),
        }
    }

    /// Instead of the default style, use one that adds variables.
    ///
    /// This injects what is produced by [`StyleBuilder::build_with_css_variables`] instead of
    /// the default [`StyleBuilder::build`].
    ///
    /// If you embed the generated svg into a html file,
    /// then you can add this example:
    /// ```css
    /// .poloto{
    ///    --poloto_bg_color:"black";
    ///    --poloto_fg_color:"white;
    ///    --poloto_color0:"red";
    ///    --poloto_color1:"green";
    ///    --poloto_color2:"yellow";
    ///    --poloto_color3:"orange";
    ///    --poloto_color4:"purple";
    ///    --poloto_color5:"pink";
    ///    --poloto_color6:"aqua";
    ///    --poloto_color7:"red";
    /// }
    /// ```  
    /// By default these variables are not defined, so the svg falls back on some default colors.
    pub fn push_default_css_with_variable(self) -> DataBuilder<impl Display> {
        DataBuilder {
            header: concatenate_display(
                "",
                self.header,
                StyleBuilder::new().build_with_css_variables(),
            ),
        }
    }
    /// User can inject some svg elements using this function.
    /// They will be inserted right after the svg and default svg tags.
    ///
    /// You can override the css in regular html if you embed the generated svg.
    /// This gives you a lot of flexibility giving your the power to dynamically
    /// change the theme of your svg.
    ///
    /// However, if you want to embed the svg as an image, you lose this ability.
    /// If embedding as IMG is desired, instead the user can insert a custom style into the generated svg itself.
    ///
    pub fn push(self, a: impl fmt::Display) -> DataBuilder<impl Display> {
        DataBuilder {
            header: concatenate_display("", self.header, a),
        }
    }
    fn finish(self) -> D {
        self.header
    }
}

///If [`plot`] isn't good enough, use this struct for more control.
pub struct PlotterBuilder<D: fmt::Display> {
    data: DataBuilder<D>,
    svgtag: bool,
}
impl Default for PlotterBuilder<&'static str> {
    fn default() -> Self {
        Self::new()
    }
}
impl PlotterBuilder<&'static str> {
    pub fn new() -> Self {
        PlotterBuilder {
            data: DataBuilder::new(),
            svgtag: true,
        }
    }
    pub fn with_data<J: Display>(self, data: DataBuilder<J>) -> PlotterBuilder<J> {
        PlotterBuilder {
            data,
            svgtag: self.svgtag,
        }
    }
    pub fn with_svg(mut self, svg: bool) -> Self {
        self.svgtag = svg;
        self
    }
}

impl<'a, D: Display + 'a> PlotterBuilder<D> {
    pub fn build(
        self,
        title: impl Display + 'a,
        xname: impl Display + 'a,
        yname: impl Display + 'a,
    ) -> Plotter<'a,impl Names> {
        let svgtag = if self.svgtag {
            SvgTagOption::Svg
        } else {
            SvgTagOption::NoSvg
        };

        Plotter {
            names: NamesStruct {
                title,
                xname,
                yname,
                header:self.data.finish()
            },
            plots: Vec::new(),
            svgtag,
        }
    }
}


///Keeps track of plots.
///User supplies iterators that will be iterated on when
///render is called.
//Its important to note that most of the time when this library is used,
//every run through the code is first accompanied by one compilation of the code.
//So inefficiencies in dynamically allocating strings using format!() to then
//be just passed to a writer are not that bad seeing as the solution
//would involve passing a lot of closures around.
pub struct Plotter<'a,D:Names> {
    names:D,
    plots: Vec<Plot<'a>>,
    svgtag: SvgTagOption,
}

impl<'a,D:Names> Plotter<'a,D> {
    
    /// Create a line from plots.
    ///
    /// # Example
    ///
    /// ```
    /// let data=[
    ///         [1.0f64,4.0],
    ///         [2.0,5.0],
    ///         [3.0,6.0]
    /// ];
    /// use poloto::prelude::*;
    /// let mut plotter = poloto::plot("title","x","y");
    /// plotter.line("data",data.iter().map(|&x|x).twice_iter());
    /// ```
    pub fn line(
        &mut self,
        name: impl Display + 'a,
        plots: impl DoubleIterator<Item = [f64; 2]> + 'a,
    ) -> &mut Self {
        self.plots.push(Plot {
            plot_type: PlotType::Line,
            plots: Box::new(Wrapper2::new(plots, name)),
        });
        self
    }

    /// Create a line from plots that will be filled underneath.
    ///
    /// # Example
    ///
    /// ```
    /// let data=[
    ///         [1.0f64,4.0],
    ///         [2.0,5.0],
    ///         [3.0,6.0]
    /// ];
    /// use poloto::prelude::*;
    /// let mut plotter = poloto::plot("title","x","y");
    /// plotter.line_fill("data",data.iter().map(|&x|x).twice_iter());
    /// ```
    pub fn line_fill(
        &mut self,
        name: impl Display + 'a,
        plots: impl DoubleIterator<Item = [f64; 2]> + 'a,
    ) -> &mut Self {
        self.plots.push(Plot {
            plot_type: PlotType::LineFill,
            plots: Box::new(Wrapper2::new(plots, name)),
        });
        self
    }

    /// Create a scatter plot from plots.
    ///
    /// # Example
    ///
    /// ```
    /// let data=[
    ///         [1.0f64,4.0],
    ///         [2.0,5.0],
    ///         [3.0,6.0]
    /// ];
    /// use poloto::prelude::*;
    /// let mut plotter = poloto::plot("title","x","y");
    /// plotter.scatter("data",data.iter().map(|&x|x).twice_iter());
    /// ```
    pub fn scatter(
        &mut self,
        name: impl Display + 'a,
        plots: impl DoubleIterator<Item = [f64; 2]> + 'a,
    ) -> &mut Self {
        self.plots.push(Plot {
            plot_type: PlotType::Scatter,
            plots: Box::new(Wrapper2::new(plots, name)),
        });
        self
    }

    /// Create a histogram from plots.
    /// Each bar's left side will line up with a point
    ///
    /// # Example
    ///
    /// ```
    /// let data=[
    ///         [1.0f64,4.0],
    ///         [2.0,5.0],
    ///         [3.0,6.0]
    /// ];
    /// use poloto::prelude::*;
    /// let mut s=String::new();
    /// let mut plotter = poloto::plot("title","x","y");
    /// plotter.histogram("data",data.iter().map(|&x|x).twice_iter());
    /// ```
    pub fn histogram(
        &mut self,
        name: impl Display + 'a,
        plots: impl DoubleIterator<Item = [f64; 2]> + 'a,
    ) -> &mut Self {
        self.plots.push(Plot {
            plot_type: PlotType::Histo,
            plots: Box::new(Wrapper2::new(plots, name)),
        });
        self
    }

    pub fn render_to_string(self) -> Result<String, fmt::Error> {
        let mut s = String::new();
        self.render(&mut s)?;
        Ok(s)
    }
    pub fn render_fmt(self, f: &mut fmt::Formatter) -> fmt::Result {
        self.render(f)?;
        Ok(())
    }
    pub fn render_io<T: std::io::Write>(self, writer: T) -> Result<T, fmt::Error> {
        self.render(tagger::upgrade(writer)).map(|x| x.inner)
    }
    /// Render the svg to the writer.
    ///
    /// Up until now, nothing has been written to the writer. We
    /// have just accumulated a list of commands and closures. This call will
    /// actually call all the closures and consume all the plot iterators.
    pub fn render<T: fmt::Write>(self, writer: T) -> Result<T, fmt::Error> {
        let Plotter {
            names,
            plots,
            svgtag,
        } = self;
        let mut root = tagger::Element::new(writer);

        use default_tags::*;

        match svgtag {
            SvgTagOption::Svg => {
                root.elem("svg", |writer| {
                    let svg = writer.write(|w| default_svg_attrs(w))?;

                    render::render(svg.get_writer(), plots, names)?;
                    Ok(svg)
                })?;
            }
            SvgTagOption::NoSvg => {
                render::render(root.get_writer(), plots, names)?;
            }
        }
        Ok(root.into_writer())
    }
}