quill 0.2.0

A lightweight Rust plotting library for creating simple SVG 2D plots
Documentation
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
use crate::{
    traits::PlotValue,
    draw::{
        draw_axis_lines, draw_data_series, draw_legend, draw_ticks_and_grids, draw_title,
        draw_x_label, draw_y_label,
    },
    elements::*,
    series::Series,
    style::*,
};
use bon::Builder;
use svg::{
    Document,
    node::element::{ClipPath, Definitions, Rectangle},
};

#[cfg(feature = "png")]
use resvg::usvg;
#[cfg(feature = "png")]
use tiny_skia as skia;

#[derive(Builder)]
pub struct Plot<'a, T: PlotValue = f32, const N: usize = 1> {
    // --- Plot Settings ---
    #[builder(default = (800, 600))]
    pub dimensions: (i32, i32),
    #[builder(default = "")]
    pub title: &'a str,
    #[builder(default = "")]
    pub x_label: &'a str,
    #[builder(default = "")]
    pub y_label: &'a str,
    #[builder(default = Range::Auto)]
    pub x_range: Range<T>,
    #[builder(default = Range::Auto)]
    pub y_range: Range<T>,
    #[builder(default = Legend::None)]
    pub legend: Legend,
    #[builder(default = Axis::Box)]
    pub axis: Axis,
    #[builder(default = Tick::Inward)]
    pub tick: Tick,
    #[builder(default = Grid::Solid)]
    pub grid: Grid,
    #[builder(default = MinorGrid::None)]
    pub minor_grid: MinorGrid,
    #[builder(default = Scale::None)]
    pub x_scale: Scale,
    #[builder(default = Scale::Engineering)]
    pub y_scale: Scale,
    #[builder(default = "Times New Roman")]
    pub font: &'a str,

    // --- Style Configurations ---
    #[builder(default = Margin::default())]
    pub margin: Margin,
    #[builder(default = TitleConfig::default())]
    pub title_config: TitleConfig,
    #[builder(default = LabelConfig::default())]
    pub x_label_config: LabelConfig,
    #[builder(default = LabelConfig::default())]
    pub y_label_config: LabelConfig,
    #[builder(default = TickConfig::default())]
    pub tick_config: TickConfig,
    #[builder(default = LegendConfig::default())]
    pub legend_config: LegendConfig,
    #[builder(default = AxisConfig::default())]
    pub axis_config: AxisConfig,
    #[builder(default = GridConfig::default())]
    pub grid_config: GridConfig,

    // --- Data ---
    pub data: [Series<'a, T>; N],
}

impl<'a, T: PlotValue, const N: usize> Plot<'a, T, N> {
    /// Saves the plot as an SVG file
    pub fn to_svg(&self, filename: &str) -> Result<(), std::io::Error> {
        let document = self.plot()?;
        svg::save(filename, &document)?;
        Ok(())
    }

    /// Saves the plot as a PNG file, scaling the size of the image by the given scale factor.
    ///
    /// This method is only available when the "png" feature is enabled.
    #[cfg(feature = "png")]
    pub fn to_png(&self, filename: &str, scale: f32) -> Result<(), Box<dyn std::error::Error>> {
        let document = self.plot()?;
        let svg_string = document.to_string();

        let mut opt = usvg::Options::default();
        opt.fontdb_mut().load_system_fonts();

        let tree = usvg::Tree::from_str(&svg_string, &opt)?;

        let pixmap_size = tree
            .size()
            .to_int_size()
            .scale_by(scale)
            .ok_or("Invalid size")?;
        let mut pixmap = skia::Pixmap::new(pixmap_size.width(), pixmap_size.height())
            .ok_or("Failed to create pixmap")?;

        let render_ts = skia::Transform::from_scale(scale, scale);
        resvg::render(&tree, render_ts, &mut pixmap.as_mut());

        pixmap.save_png(filename)?;
        Ok(())
    }

    /// Converts the plot to PNG bytes, scaling the size of the image by the given scale factor.
    ///
    /// This method is only available when the "png" feature is enabled.
    #[cfg(feature = "png")]
    pub fn to_png_bytes(&self, scale: f32) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let document = self.plot()?;
        let svg_string = document.to_string();

        let mut opt = usvg::Options::default();
        opt.fontdb_mut().load_system_fonts();

        let tree = usvg::Tree::from_str(&svg_string, &opt)?;

        let pixmap_size = tree
            .size()
            .to_int_size()
            .scale_by(scale)
            .ok_or("Invalid size")?;
        let mut pixmap = skia::Pixmap::new(pixmap_size.width(), pixmap_size.height())
            .ok_or("Failed to create pixmap")?;

        let render_ts = skia::Transform::from_scale(scale, scale);
        resvg::render(&tree, render_ts, &mut pixmap.as_mut());

        Ok(pixmap.encode_png()?)
    }

    /// Converts the plot to an SVG document.
    pub fn to_document(&self) -> Result<Document, std::io::Error> {
        self.plot()
    }

    /// Generates an SVG document representing the plot.
    fn plot(&self) -> Result<Document, std::io::Error> {
        let (total_width, total_height) = self.dimensions;
        let mut document = Document::new()
            .set("width", total_width)
            .set("height", total_height)
            .set("viewBox", (0, 0, total_width, total_height));

        // Background
        let background = Rectangle::new()
            .set("x", 0)
            .set("y", 0)
            .set("width", total_width)
            .set("height", total_height)
            .set("fill", "white");
        document = document.add(background);

        // Determine x_min, x_max, y_min, y_max based on Range
        let (actual_x_min, actual_x_max) = match self.x_range {
            Range::Auto => {
                if self.data.is_empty() || self.data.iter().all(|s| s.data.is_empty()) {
                    (T::from_f32(0.0), T::from_f32(1.0))
                } else {
                    let mut min_x = T::max_value();
                    let mut max_x = T::min_value();
                    for series in &self.data {
                        for (x, _) in &series.data {
                            if *x < min_x {
                                min_x = *x;
                            }
                            if *x > max_x {
                                max_x = *x;
                            }
                        }
                    }
                    if (max_x - min_x) < T::epsilon() {
                        (min_x - T::from_f32(0.5), max_x + T::from_f32(0.5))
                    } else {
                        // For logarithmic X scale, expand to nice power-of-10 bounds
                        if self.x_scale == Scale::Log && min_x.to_f32() > 0.0 {
                            let min_log = min_x.to_f32().log10().floor();
                            let max_log = max_x.to_f32().log10().ceil();
                            (T::from_f32(10.0_f32.powi(min_log as i32)), T::from_f32(10.0_f32.powi(max_log as i32)))
                        } else {
                            (min_x, max_x)
                        }
                    }
                }
            }
            Range::Manual { min, max } => (min, max),
        };

        let (actual_y_min, actual_y_max) = match self.y_range {
            Range::Auto => {
                if self.data.is_empty() || self.data.iter().all(|s| s.data.is_empty()) {
                    (T::from_f32(0.0), T::from_f32(1.0))
                } else {
                    let mut min_y = T::max_value();
                    let mut max_y = T::min_value();
                    for series in &self.data {
                        for (_, y) in &series.data {
                            if *y < min_y {
                                min_y = *y;
                            }
                            if *y > max_y {
                                max_y = *y;
                            }
                        }
                    }
                    if (max_y - min_y) < T::epsilon() {
                        (min_y - T::from_f32(0.5), max_y + T::from_f32(0.5))
                    } else {
                        // For logarithmic Y scale, expand to nice power-of-10 bounds
                        if self.y_scale == Scale::Log && min_y.to_f32() > 0.0 {
                            let min_log = min_y.to_f32().log10().floor();
                            let max_log = max_y.to_f32().log10().ceil();
                            (T::from_f32(10.0_f32.powi(min_log as i32)), T::from_f32(10.0_f32.powi(max_log as i32)))
                        } else {
                            (min_y, max_y)
                        }
                    }
                }
            }
            Range::Manual { min, max } => (min, max),
        };

        // Calculate legend dimensions
        let mut calculated_max_series_name_width = 0.0f32;
        if self.legend != Legend::None && !self.data.is_empty() {
            calculated_max_series_name_width = self
                .data
                .iter()
                .map(|s| s.name.len() as f32 * self.legend_config.font_size * 0.6)
                .fold(0.0f32, |a, b| a.max(b));
        }

        let legend_actual_box_width = if self.legend != Legend::None && !self.data.is_empty() {
            self.legend_config.color_swatch_width
                + self.legend_config.text_offset
                + calculated_max_series_name_width
        } else {
            0.0
        };
        let legend_height = if self.legend != Legend::None && !self.data.is_empty() {
            self.data.len() as f32 * self.legend_config.item_height
                + self.legend_config.padding * 2.0
        } else {
            0.0
        };

        // Adjust margins based on legend position
        let current_effective_margin_left = self.margin.left;
        let mut current_effective_margin_right = self.margin.right;
        let current_effective_margin_top = self.margin.top;
        let current_effective_margin_bottom = self.margin.bottom;

        if self.legend != Legend::None && !self.data.is_empty() {
            match self.legend {
                Legend::TopRightOutside
                | Legend::RightCenterOutside
                | Legend::BottomRightOutside => {
                    current_effective_margin_right +=
                        legend_actual_box_width + self.legend_config.padding;
                }
                _ => {}
            }
        }

        // Calculate plot area dimensions
        let plot_area_x_start = current_effective_margin_left;
        let plot_area_y_start = current_effective_margin_top;
        let plot_area_width =
            total_width as f32 - current_effective_margin_left - current_effective_margin_right;
        let plot_area_height =
            total_height as f32 - current_effective_margin_top - current_effective_margin_bottom;

        if plot_area_width <= 0.0 || plot_area_height <= 0.0 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!(
                    "Plot area is too small (width: {}, height: {}). Check dimensions and margins.",
                    plot_area_width, plot_area_height
                ),
            ));
        }

        // Helper closures to map data coordinates to screen coordinates
        let map_x = |data_x: T| -> f32 {
            if (actual_x_max - actual_x_min) < T::epsilon() {
                plot_area_x_start + plot_area_width / 2.0
            } else {
                let data_x_f32 = data_x.to_f32();
                let actual_x_min_f32 = actual_x_min.to_f32();
                let actual_x_max_f32 = actual_x_max.to_f32();
                
                // Apply logarithmic transformation if needed
                if self.x_scale == Scale::Log {
                    // Ensure positive values for logarithmic scale
                    let safe_data_x = if data_x_f32 > 0.0 { data_x_f32 } else { 0.001 };
                    let safe_min = if actual_x_min_f32 > 0.0 { actual_x_min_f32 } else { 1.0 };
                    let safe_max = if actual_x_max_f32 > 0.0 { actual_x_max_f32 } else { 10.0 };
                    
                    let log_data_x = safe_data_x.log10();
                    let log_min = safe_min.log10();
                    let log_max = safe_max.log10();
                    
                    if (log_max - log_min).abs() < f32::EPSILON {
                        plot_area_x_start + plot_area_width / 2.0
                    } else {
                        plot_area_x_start + ((log_data_x - log_min) / (log_max - log_min) * plot_area_width)
                    }
                } else {
                    plot_area_x_start
                        + ((data_x_f32 - actual_x_min_f32) / (actual_x_max_f32 - actual_x_min_f32)
                            * plot_area_width)
                }
            }
        };
        let map_y = |data_y: T| -> f32 {
            if (actual_y_max - actual_y_min) < T::epsilon() {
                plot_area_y_start + plot_area_height / 2.0
            } else {
                let data_y_f32 = data_y.to_f32();
                let actual_y_min_f32 = actual_y_min.to_f32();
                let actual_y_max_f32 = actual_y_max.to_f32();
                
                // Apply logarithmic transformation if needed
                if self.y_scale == Scale::Log {
                    // Ensure positive values for logarithmic scale
                    let safe_data_y = if data_y_f32 > 0.0 { data_y_f32 } else { 0.001 };
                    let safe_min = if actual_y_min_f32 > 0.0 { actual_y_min_f32 } else { 1.0 };
                    let safe_max = if actual_y_max_f32 > 0.0 { actual_y_max_f32 } else { 10.0 };
                    
                    let log_data_y = safe_data_y.log10();
                    let log_min = safe_min.log10();
                    let log_max = safe_max.log10();
                    
                    if (log_max - log_min).abs() < f32::EPSILON {
                        plot_area_y_start + plot_area_height / 2.0
                    } else {
                        plot_area_y_start + plot_area_height
                            - ((log_data_y - log_min) / (log_max - log_min) * plot_area_height)
                    }
                } else {
                    plot_area_y_start + plot_area_height
                        - ((data_y_f32 - actual_y_min_f32) / (actual_y_max_f32 - actual_y_min_f32)
                            * plot_area_height)
                }
            }
        };

        // --- Draw Title ---
        document = draw_title(
            document,
            self.title,
            self.font,
            &self.title_config,
            plot_area_x_start,
            plot_area_width,
            current_effective_margin_top,
        );

        // --- Draw X-axis Label ---
        document = draw_x_label(
            document,
            self.x_label,
            self.font,
            &self.x_label_config,
            plot_area_x_start,
            plot_area_width,
            plot_area_y_start,
            plot_area_height,
            current_effective_margin_bottom,
        );

        // --- Draw Y-axis Label ---
        document = draw_y_label(
            document,
            self.y_label,
            self.font,
            &self.y_label_config,
            current_effective_margin_left,
            plot_area_y_start,
            plot_area_height,
        );

        // --- Draw Axis Lines ---
        document = draw_axis_lines(
            document,
            self.axis,
            &self.axis_config,
            plot_area_x_start,
            plot_area_y_start,
            plot_area_width,
            plot_area_height,
        );

        // --- Tick Marks, Grid Lines, and Tick Labels ---
        let num_x_ticks = (plot_area_width / self.tick_config.density_x).max(2.0) as usize;
        let num_y_ticks = (plot_area_height / self.tick_config.density_y).max(2.0) as usize;

        let calculate_linear_ticks = |min_val: f32, max_val: f32, max_ticks: usize| -> Vec<f32> {
            if (max_val - min_val).abs() < f32::EPSILON {
                return vec![min_val];
            }
            let range = max_val - min_val;
            let rough_step = range / (max_ticks.saturating_sub(1) as f32).max(1.0);
            if rough_step == 0.0 {
                return vec![min_val];
            }
            let exponent = rough_step.log10().floor();
            let fraction = rough_step / 10f32.powf(exponent);
            let nice_fraction = if fraction < 1.5 {
                1.0
            } else if fraction < 3.5 {
                2.0
            } else if fraction < 7.5 {
                5.0
            } else {
                10.0
            };
            let step = nice_fraction * 10f32.powf(exponent);
            if step == 0.0 {
                return vec![min_val, max_val].into_iter().collect();
            }

            let start_tick = (min_val / step).floor() * step;
            let mut ticks = Vec::new();
            let mut current_tick = start_tick;

            while current_tick <= max_val + step * 0.5 {
                if current_tick >= min_val - step * 0.1 && current_tick <= max_val + step * 0.1 {
                    ticks.push(current_tick);
                }
                current_tick += step;
                if ticks.len() > max_ticks * 2 {
                    break;
                }
            }

            if ticks.is_empty() {
                if min_val == max_val {
                    ticks.push(min_val);
                } else {
                    ticks.extend_from_slice(&[min_val, max_val]);
                }
            } else if ticks.len() == 1 && min_val != max_val {
                ticks.push(max_val);
            }
            ticks
        };

        let calculate_log_ticks = |min_val: f32, max_val: f32| -> Vec<f32> {
            // Handle cases where min_val is 0 or negative by using a small positive value
            let safe_min_val = if min_val <= 0.0 {
                if max_val > 1.0 {
                    1.0 // Start from 1 if max is reasonable
                } else {
                    0.001 // Use a small positive value
                }
            } else {
                min_val
            };
            
            let safe_max_val = if max_val <= 0.0 {
                safe_min_val * 1000.0 // Ensure we have a reasonable range
            } else {
                max_val
            };

            let log_min = safe_min_val.log10().floor();
            let log_max = safe_max_val.log10().ceil();
            let mut ticks = Vec::new();

            // Generate only major ticks (powers of 10)
            for exp in (log_min as i32)..=(log_max as i32) {
                let tick_value = 10.0_f32.powi(exp);
                if tick_value >= safe_min_val && tick_value <= safe_max_val {
                    ticks.push(tick_value);
                }
            }

            // Ensure we have at least some ticks
            if ticks.is_empty() {
                ticks.push(safe_min_val);
                ticks.push(safe_max_val);
            }

            ticks
        };

        let x_ticks = if self.x_scale == Scale::Log {
            calculate_log_ticks(actual_x_min.to_f32(), actual_x_max.to_f32())
        } else {
            calculate_linear_ticks(actual_x_min.to_f32(), actual_x_max.to_f32(), num_x_ticks)
        };

        let y_ticks = if self.y_scale == Scale::Log {
            calculate_log_ticks(actual_y_min.to_f32(), actual_y_max.to_f32())
        } else {
            calculate_linear_ticks(actual_y_min.to_f32(), actual_y_max.to_f32(), num_y_ticks)
        };

        document = draw_ticks_and_grids(
            document,
            self.axis,
            self.tick,
            self.grid,
            self.minor_grid,
            self.x_scale,
            self.y_scale,
            &self.tick_config,
            &self.grid_config,
            self.font,
            plot_area_x_start,
            plot_area_y_start,
            plot_area_width,
            plot_area_height,
            &x_ticks,
            &y_ticks,
            |x_f32| map_x(T::from_f32(x_f32)),
            |y_f32| map_y(T::from_f32(y_f32)),
        );

        // --- Clipping Path for Plot Area ---
        let clip_path_id = "plotAreaClip";
        let clip_rect = Rectangle::new()
            .set("x", plot_area_x_start)
            .set("y", plot_area_y_start)
            .set("width", plot_area_width)
            .set("height", plot_area_height);
        let clip_path = ClipPath::new().set("id", clip_path_id).add(clip_rect);
        let mut defs = Definitions::new();
        defs = defs.add(clip_path);
        document = document.add(defs);

        // --- Data Series Drawing ---
        let data_group = draw_data_series(&self.data[..], map_x, map_y);
        document = document.add(data_group);

        // --- Legend Drawing ---
        if self.legend != Legend::None && !self.data.is_empty() {
            let legend_x_base;
            let legend_y_base;
            match self.legend {
                Legend::TopRightInside => {
                    legend_x_base = plot_area_x_start + plot_area_width
                        - legend_actual_box_width
                        - self.legend_config.padding;
                    legend_y_base = plot_area_y_start + self.legend_config.padding;
                }
                Legend::TopRightOutside => {
                    legend_x_base = total_width as f32 - current_effective_margin_right
                        + self.legend_config.padding;
                    legend_y_base = plot_area_y_start + self.legend_config.padding;
                }
                Legend::BottomRightInside => {
                    legend_x_base = plot_area_x_start + plot_area_width
                        - legend_actual_box_width
                        - self.legend_config.padding;
                    legend_y_base = plot_area_y_start + plot_area_height
                        - legend_height
                        - self.legend_config.padding;
                }
                Legend::BottomRightOutside => {
                    legend_x_base = total_width as f32 - current_effective_margin_right
                        + self.legend_config.padding;
                    legend_y_base = plot_area_y_start + plot_area_height
                        - legend_height
                        - self.legend_config.padding;
                }
                Legend::TopLeftInside => {
                    legend_x_base = plot_area_x_start + self.legend_config.padding;
                    legend_y_base = plot_area_y_start + self.legend_config.padding;
                }
                Legend::BottomLeftInside => {
                    legend_x_base = plot_area_x_start + self.legend_config.padding;
                    legend_y_base = plot_area_y_start + plot_area_height
                        - legend_height
                        - self.legend_config.padding;
                }
                Legend::RightCenterInside => {
                    legend_x_base = plot_area_x_start + plot_area_width
                        - legend_actual_box_width
                        - self.legend_config.padding;
                    legend_y_base = plot_area_y_start + (plot_area_height - legend_height) / 2.0;
                }
                Legend::RightCenterOutside => {
                    legend_x_base = total_width as f32 - current_effective_margin_right
                        + self.legend_config.padding;
                    legend_y_base = plot_area_y_start + (plot_area_height - legend_height) / 2.0;
                }
                Legend::LeftCenterInside => {
                    legend_x_base = plot_area_x_start + self.legend_config.padding;
                    legend_y_base = plot_area_y_start + (plot_area_height - legend_height) / 2.0;
                }
                Legend::TopCenter => {
                    legend_x_base =
                        plot_area_x_start + (plot_area_width - legend_actual_box_width) / 2.0;
                    legend_y_base = plot_area_y_start + self.legend_config.padding;
                }
                Legend::BottomCenter => {
                    legend_x_base =
                        plot_area_x_start + (plot_area_width - legend_actual_box_width) / 2.0;
                    legend_y_base = plot_area_y_start + plot_area_height
                        - legend_height
                        - self.legend_config.padding;
                }
                Legend::None => {
                    legend_x_base = 0.0;
                    legend_y_base = 0.0;
                }
            }

            document = draw_legend(
                document,
                &self.data[..],
                self.font,
                &self.legend_config,
                legend_x_base,
                legend_y_base,
                legend_actual_box_width,
                legend_height,
            );
        }
        Ok(document)
    }
}