1use std::ops::{BitOr, Div};
27
28use crate::guide::legend;
29use crate::plot::{GGError, GGPlot, RenderMeta};
30use crate::render::backend::{
31 DrawBackend, LineStyle, PointStyle, RectStyle, TextAnchor, TextStyle,
32};
33use crate::render::renderer::PlotRenderer;
34use crate::render::svg_backend::{root_data_attrs, SvgBackend};
35use crate::render::{Rect, RenderError};
36use crate::theme::{LegendPosition, Theme};
37
38#[derive(Clone, Debug, PartialEq)]
40pub enum TagLevels {
41 Lower,
43 Upper,
45 Numeric,
47 LowerRoman,
49 UpperRoman,
51 Custom(Vec<String>),
53}
54
55impl TagLevels {
56 pub fn tag(&self, i: usize) -> String {
58 match self {
59 TagLevels::Lower => alpha(i, b'a'),
60 TagLevels::Upper => alpha(i, b'A'),
61 TagLevels::Numeric => (i + 1).to_string(),
62 TagLevels::LowerRoman => roman(i + 1).to_lowercase(),
63 TagLevels::UpperRoman => roman(i + 1),
64 TagLevels::Custom(v) => v.get(i).cloned().unwrap_or_else(|| (i + 1).to_string()),
65 }
66 }
67}
68
69fn alpha(mut i: usize, base: u8) -> String {
70 let mut out = Vec::new();
72 loop {
73 out.push(base + (i % 26) as u8);
74 if i < 26 {
75 break;
76 }
77 i = i / 26 - 1;
78 }
79 out.reverse();
80 String::from_utf8(out).unwrap_or_default()
81}
82
83fn roman(mut n: usize) -> String {
84 if n >= 4000 {
85 return n.to_string();
86 }
87 const T: [(usize, &str); 13] = [
88 (1000, "M"),
89 (900, "CM"),
90 (500, "D"),
91 (400, "CD"),
92 (100, "C"),
93 (90, "XC"),
94 (50, "L"),
95 (40, "XL"),
96 (10, "X"),
97 (9, "IX"),
98 (5, "V"),
99 (4, "IV"),
100 (1, "I"),
101 ];
102 let mut s = String::new();
103 for (v, r) in T {
104 while n >= v {
105 s.push_str(r);
106 n -= v;
107 }
108 }
109 s
110}
111
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
114pub enum GridLegendPosition {
115 #[default]
117 Right,
118 Bottom,
120}
121
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125enum Op {
126 Row,
127 Col,
128}
129
130pub enum GridCell {
132 Plot(Box<GGPlot>),
133 Grid(Box<PlotGrid>),
134 Spacer,
136}
137
138impl From<GGPlot> for GridCell {
139 fn from(p: GGPlot) -> Self {
140 GridCell::Plot(Box::new(p))
141 }
142}
143
144impl From<PlotGrid> for GridCell {
145 fn from(g: PlotGrid) -> Self {
146 GridCell::Grid(Box::new(g))
147 }
148}
149
150pub struct PlotGrid {
169 cells: Vec<GridCell>,
170 ncol: Option<usize>,
171 nrow: Option<usize>,
172 byrow: bool,
173 widths: Vec<f64>,
174 heights: Vec<f64>,
175 title: Option<String>,
176 subtitle: Option<String>,
177 caption: Option<String>,
178 tags: Option<TagLevels>,
179 tag_prefix: String,
180 tag_suffix: String,
181 collect_legends: bool,
182 legend_position: GridLegendPosition,
183 spacing: f64,
184 theme: Theme,
185 op: Option<Op>,
186 root_attrs: Vec<(String, String)>,
189 svg_warnings_attr: bool,
194}
195
196impl Default for PlotGrid {
197 fn default() -> Self {
198 PlotGrid {
199 cells: Vec::new(),
200 ncol: None,
201 nrow: None,
202 byrow: true,
203 widths: Vec::new(),
204 heights: Vec::new(),
205 title: None,
206 subtitle: None,
207 caption: None,
208 tags: None,
209 tag_prefix: String::new(),
210 tag_suffix: String::new(),
211 collect_legends: false,
212 legend_position: GridLegendPosition::Right,
213 spacing: 0.0,
214 theme: Theme::default(),
215 op: None,
216 root_attrs: Vec::new(),
217 svg_warnings_attr: false,
218 }
219 }
220}
221
222const MAX_TRACKS: usize = 10_000;
224
225impl PlotGrid {
226 pub fn new() -> Self {
227 Self::default()
228 }
229
230 #[allow(clippy::should_implement_trait)]
232 pub fn add(mut self, cell: impl Into<GridCell>) -> Self {
233 self.cells.push(cell.into());
234 self
235 }
236
237 pub fn add_all(mut self, plots: impl IntoIterator<Item = GGPlot>) -> Self {
239 self.cells.extend(plots.into_iter().map(GridCell::from));
240 self
241 }
242
243 pub fn add_spacer(mut self) -> Self {
245 self.cells.push(GridCell::Spacer);
246 self
247 }
248
249 pub fn ncol(mut self, n: usize) -> Self {
251 self.ncol = (n > 0).then_some(n.min(MAX_TRACKS));
252 self
253 }
254
255 pub fn nrow(mut self, n: usize) -> Self {
257 self.nrow = (n > 0).then_some(n.min(MAX_TRACKS));
258 self
259 }
260
261 pub fn byrow(mut self, byrow: bool) -> Self {
263 self.byrow = byrow;
264 self
265 }
266
267 pub fn widths(mut self, widths: &[f64]) -> Self {
269 self.widths = widths.to_vec();
270 self
271 }
272
273 pub fn heights(mut self, heights: &[f64]) -> Self {
275 self.heights = heights.to_vec();
276 self
277 }
278
279 pub fn title(mut self, title: &str) -> Self {
281 self.title = Some(title.to_string());
282 self
283 }
284
285 pub fn subtitle(mut self, subtitle: &str) -> Self {
287 self.subtitle = Some(subtitle.to_string());
288 self
289 }
290
291 pub fn caption(mut self, caption: &str) -> Self {
293 self.caption = Some(caption.to_string());
294 self
295 }
296
297 pub fn tag_levels(mut self, levels: TagLevels) -> Self {
299 self.tags = Some(levels);
300 self
301 }
302
303 pub fn tag_affixes(mut self, prefix: &str, suffix: &str) -> Self {
305 self.tag_prefix = prefix.to_string();
306 self.tag_suffix = suffix.to_string();
307 self
308 }
309
310 pub fn collect_legends(mut self, collect: bool) -> Self {
313 self.collect_legends = collect;
314 self
315 }
316
317 pub fn legend_position(mut self, pos: GridLegendPosition) -> Self {
319 self.legend_position = pos;
320 self
321 }
322
323 pub fn spacing(mut self, px: f64) -> Self {
325 self.spacing = if px.is_finite() { px.max(0.0) } else { 0.0 };
326 self
327 }
328
329 pub fn theme(mut self, theme: Theme) -> Self {
332 self.theme = theme;
333 self
334 }
335
336 pub fn svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
343 self.root_attrs.push((name.into(), value.into()));
344 self
345 }
346
347 pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
349 self.root_attrs.extend(attrs);
350 self
351 }
352
353 pub fn svg_warnings_attr(mut self, on: bool) -> Self {
357 self.svg_warnings_attr = on;
358 self
359 }
360
361 pub fn len(&self) -> usize {
363 self.cells.len()
364 }
365
366 pub fn is_empty(&self) -> bool {
368 self.cells.is_empty()
369 }
370
371 pub fn render_svg_native(self) -> Result<String, GGError> {
373 self.render_svg_native_with_size(800, 600)
374 }
375
376 pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
380 Ok(self.render_page(w, h)?.0.finish())
381 }
382
383 pub fn render_svg_native_with_warnings(
386 self,
387 w: u32,
388 h: u32,
389 ) -> Result<(String, Vec<String>), GGError> {
390 let (page, warnings) = self.render_page(w, h)?;
391 Ok((page.finish(), warnings))
392 }
393
394 pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
397 Ok(self.render_page(w, h)?.0.finish_fragment(x, y))
398 }
399
400 fn render_page(self, w: u32, h: u32) -> Result<(SvgBackend, Vec<String>), GGError> {
401 let (w, h) = (w.max(1), h.max(1));
402 let mut theme = self.theme.clone();
403 theme.resolve_inheritance();
404 let collect = self.collect_legends;
405 let legend_pos = self.legend_position;
406 let root_attrs = self.root_attrs.clone();
407 let svg_warnings_attr = self.svg_warnings_attr;
408
409 let mut ctx = PrepCtx {
412 tags: self
413 .tags
414 .clone()
415 .map(|t| (t, self.tag_prefix.clone(), self.tag_suffix.clone())),
416 next_tag: 0,
417 next_index: 0,
418 collect: collect.then_some(legend_pos),
419 legends: Vec::new(),
420 page_w: w as f64,
421 page_h: h as f64,
422 };
423 let prepared = prepare_grid(self, &mut ctx)?;
424 let legends = ctx.legends;
425
426 let full = Rect {
428 x: 0.0,
429 y: 0.0,
430 width: w as f64,
431 height: h as f64,
432 };
433 let mut page = SvgBackend::new(w, h, full.clone());
434 page.without_plot_attr();
435 let (rows, cols) = prepared.dims();
436 let data_grid_attr = ("data-grid".to_string(), format!("{rows} {cols}"));
437 page.set_root_attrs(vec![data_grid_attr.clone()]);
438 if let Some(fill) = theme
439 .plot_background
440 .fill
441 .filter(|_| theme.plot_background.visible)
442 {
443 page.draw_rect(
444 (0.0, 0.0),
445 (w as f64, h as f64),
446 &RectStyle {
447 fill: Some(fill),
448 stroke: None,
449 stroke_width: 0.0,
450 alpha: 1.0,
451 clip: false,
452 },
453 )
454 .map_err(GGError::Render)?;
455 }
456
457 let mut body = full;
458 if !legends.is_empty() {
459 let gap = theme.legend_spacing.max(0.0) * 2.0;
460 let pad = 8.0;
461 match legend_pos {
462 GridLegendPosition::Right => {
463 let strip_w = legends.iter().map(|l| l.w).fold(0.0, f64::max) + 2.0 * pad;
464 let strip_w = strip_w.min(body.width * 0.4);
465 body.width -= strip_w;
466 let total_h =
467 legends.iter().map(|l| l.h).sum::<f64>() + gap * (legends.len() - 1) as f64;
468 let mut y = (body.y + (body.height - total_h) / 2.0).max(body.y + pad);
469 for l in &legends {
470 place_legend(&mut page, l, body.x + body.width + pad, y);
471 y += l.h + gap;
472 }
473 }
474 GridLegendPosition::Bottom => {
475 let strip_h = legends.iter().map(|l| l.h).fold(0.0, f64::max) + 2.0 * pad;
476 let strip_h = strip_h.min(body.height * 0.4);
477 body.height -= strip_h;
478 let total_w =
479 legends.iter().map(|l| l.w).sum::<f64>() + gap * (legends.len() - 1) as f64;
480 let mut x = (body.x + (body.width - total_w) / 2.0).max(body.x + pad);
481 for l in &legends {
482 place_legend(&mut page, l, x, body.y + body.height + pad);
483 x += l.w + gap;
484 }
485 }
486 }
487 }
488
489 let mut warnings = Vec::new();
491 render_prepared(prepared, &body, &mut page, &mut warnings)?;
492
493 let mut reserved = vec![data_grid_attr];
494 if svg_warnings_attr {
495 reserved.push(("data-warnings".to_string(), String::new()));
496 }
497 let extra = crate::render::svg_backend::validate_root_attrs(
498 &root_attrs,
499 &reserved,
500 "grid",
501 &mut warnings,
502 );
503 page.extend_root_attrs(extra);
504 if svg_warnings_attr {
505 page.extend_root_attrs(vec![(
506 "data-warnings".to_string(),
507 crate::render::svg_backend::warnings_json(&warnings),
508 )]);
509 }
510 Ok((page, warnings))
511 }
512}
513
514struct Legend {
516 body: String,
517 x0: f64,
518 y0: f64,
519 w: f64,
520 h: f64,
521}
522
523fn place_legend(page: &mut SvgBackend, l: &Legend, x: f64, y: f64) {
524 let (tx, ty) = (x - l.x0, y - l.y0);
525 if tx.is_finite() && ty.is_finite() {
526 page.push_raw(&format!(
527 "<g class=\"legend\" transform=\"translate({tx:.2} {ty:.2})\">{}</g>",
528 l.body
529 ));
530 }
531}
532
533struct PrepCtx {
534 tags: Option<(TagLevels, String, String)>,
535 next_tag: usize,
536 next_index: usize,
537 collect: Option<GridLegendPosition>,
538 legends: Vec<Legend>,
539 page_w: f64,
545 page_h: f64,
546}
547
548struct PreparedPlot {
550 built: crate::build::BuiltPlot,
551 meta: RenderMeta,
552 panel: String,
553 svg_formatted_values: bool,
561}
562
563enum Prepared {
564 Plot(Box<PreparedPlot>),
565 Grid(Box<PreparedGrid>),
566 Spacer,
567}
568
569struct PreparedGrid {
570 cells: Vec<Prepared>,
571 ncol: usize,
572 nrow: usize,
573 byrow: bool,
574 widths: Vec<f64>,
575 heights: Vec<f64>,
576 title: Option<String>,
577 subtitle: Option<String>,
578 caption: Option<String>,
579 spacing: f64,
580 theme: Theme,
581}
582
583impl Prepared {
584 fn dims(&self) -> (usize, usize) {
585 match self {
586 Prepared::Grid(g) => (g.nrow, g.ncol),
587 _ => (1, 1),
588 }
589 }
590}
591
592fn prepare_grid(grid: PlotGrid, ctx: &mut PrepCtx) -> Result<Prepared, GGError> {
593 let n = grid.cells.len();
594 let (ncol, nrow) = match (grid.ncol, grid.nrow, grid.op) {
595 (Some(c), Some(r), _) => {
596 (c, r.max(n.div_ceil(c)))
598 }
599 (Some(c), None, _) => (c, n.div_ceil(c).max(1)),
600 (None, Some(r), _) => (n.div_ceil(r).max(1), r),
601 (None, None, Some(Op::Row)) => (n.max(1), 1),
602 (None, None, Some(Op::Col)) => (1, n.max(1)),
603 (None, None, None) => {
604 let c = ((n as f64).sqrt().ceil() as usize).max(1);
605 (c, n.div_ceil(c).max(1))
606 }
607 };
608 let mut theme = grid.theme;
609 theme.resolve_inheritance();
610 let mut cells = Vec::with_capacity(n);
611 for cell in grid.cells {
612 cells.push(match cell {
613 GridCell::Spacer => Prepared::Spacer,
614 GridCell::Grid(g) => prepare_grid(*g, ctx)?,
615 GridCell::Plot(p) => Prepared::Plot(Box::new(prepare_plot(*p, ctx)?)),
616 });
617 }
618 Ok(Prepared::Grid(Box::new(PreparedGrid {
619 cells,
620 ncol,
621 nrow,
622 byrow: grid.byrow,
623 widths: grid.widths,
624 heights: grid.heights,
625 title: grid.title,
626 subtitle: grid.subtitle,
627 caption: grid.caption,
628 spacing: grid.spacing,
629 theme,
630 })))
631}
632
633fn prepare_plot(mut plot: GGPlot, ctx: &mut PrepCtx) -> Result<PreparedPlot, GGError> {
634 ctx.next_index += 1;
635 if let Some((levels, pre, suf)) = &ctx.tags {
636 plot.labels.tag = Some(format!("{pre}{}{suf}", levels.tag(ctx.next_tag)));
637 ctx.next_tag += 1;
638 }
639 let panel = plot
640 .labels
641 .tag
642 .clone()
643 .unwrap_or_else(|| ctx.next_index.to_string());
644
645 let original = plot.theme.legend_position.clone();
647 let collect = ctx.collect.filter(|_| {
648 matches!(
649 original,
650 LegendPosition::Right
651 | LegendPosition::Left
652 | LegendPosition::Top
653 | LegendPosition::Bottom
654 )
655 });
656 if collect.is_some() {
657 plot.theme.legend_position = LegendPosition::None;
658 }
659 let svg_formatted_values = plot.svg_formatted_values;
660 let (built, mut meta) = plot.build_for_render()?;
661 if let Some(pos) = collect {
662 meta.has_legend = false;
663 if let Some(l) =
664 capture_legend(&built, pos, ctx.page_w, ctx.page_h).map_err(GGError::Render)?
665 {
666 if !ctx.legends.iter().any(|o| o.body == l.body) {
667 ctx.legends.push(l);
668 }
669 }
670 }
671 Ok(PreparedPlot {
672 built,
673 meta,
674 panel,
675 svg_formatted_values,
676 })
677}
678
679fn capture_legend(
687 built: &crate::build::BuiltPlot,
688 pos: GridLegendPosition,
689 page_w: f64,
690 page_h: f64,
691) -> Result<Option<Legend>, RenderError> {
692 let mut theme = built.theme.clone();
693 let m = theme.legend_margin.clone();
694 let (pa, lp, is_horizontal) = match pos {
696 GridLegendPosition::Right => (
697 Rect {
698 x: -m.left,
699 y: -m.top,
700 width: 0.0,
701 height: 0.0,
702 },
703 LegendPosition::Right,
704 false,
705 ),
706 GridLegendPosition::Bottom => (
707 Rect {
708 x: -m.left,
709 y: -(m.top + 30.0),
710 width: 0.0,
711 height: 0.0,
712 },
713 LegendPosition::Bottom,
714 true,
715 ),
716 };
717 theme.legend_position = lp;
718 let mut svg = SvgBackend::new(1, 1, pa.clone());
719 let mut meas = Measure::new(&mut svg, pa.clone());
720 let avail_width = (page_w + m.left).max(0.0);
721 let avail_height = (page_h + m.top).max(0.0);
722 let mut legend_warnings = Vec::new();
723 let legend_plans = legend::plan_all_legends(
724 &built.scales,
725 &built.guide_legend,
726 &theme,
727 &built.suppressed_aes,
728 avail_width,
729 avail_height,
730 is_horizontal,
731 &mut legend_warnings,
732 );
733 legend::draw_legend_planned(
734 &built.scales,
735 &theme,
736 &pa,
737 avail_width,
744 &mut meas,
745 &built.guide_legend,
746 &built.suppressed_aes,
747 &legend_plans,
748 )?;
749 let ext = meas.extent();
750 if svg.body().is_empty() {
751 return Ok(None);
752 }
753 let (x0, y0, x1, y1) = match ext {
754 Some(e) => e,
755 None => return Ok(None),
756 };
757 Ok(Some(Legend {
758 body: svg.body().to_string(),
759 x0,
760 y0,
761 w: (x1 - x0).max(0.0),
762 h: (y1 - y0).max(0.0),
763 }))
764}
765
766fn tracks(weights: &[f64], n: usize, total: f64, gap: f64) -> Vec<(f64, f64)> {
768 let ws: Vec<f64> = (0..n)
769 .map(|i| {
770 if weights.is_empty() {
771 1.0
772 } else {
773 let w = weights[i % weights.len()];
774 if w.is_finite() && w > 0.0 {
775 w
776 } else {
777 1.0
778 }
779 }
780 })
781 .collect();
782 let sum: f64 = ws.iter().sum();
783 let avail = (total - gap * n.saturating_sub(1) as f64).max(0.0);
784 let mut pos = 0.0;
785 ws.iter()
786 .map(|w| {
787 let size = avail * w / sum;
788 let t = (pos, size);
789 pos += size + gap;
790 t
791 })
792 .collect()
793}
794
795fn text_style(el: &crate::theme::elements::ElementText, anchor: TextAnchor) -> TextStyle {
796 TextStyle {
797 color: el.color,
798 size: el.size,
799 anchor,
800 angle: 0.0,
801 family: (!el.family.is_empty()).then(|| el.family.clone()),
802 face: el.face,
803 }
804}
805
806fn hjust_x(el: &crate::theme::elements::ElementText, x0: f64, x1: f64) -> (f64, TextAnchor) {
807 let hj = if el.hjust.is_finite() {
808 el.hjust.clamp(0.0, 1.0)
809 } else {
810 0.0
811 };
812 let anchor = if hj <= 0.02 {
813 TextAnchor::Start
814 } else if hj >= 0.98 {
815 TextAnchor::End
816 } else {
817 TextAnchor::Middle
818 };
819 (x0 + hj * (x1 - x0), anchor)
820}
821
822fn render_prepared(
823 prepared: Prepared,
824 area: &Rect,
825 page: &mut SvgBackend,
826 warnings: &mut Vec<String>,
827) -> Result<(), GGError> {
828 match prepared {
829 Prepared::Spacer => Ok(()),
830 Prepared::Plot(p) => {
831 let PreparedPlot {
832 mut built,
833 meta,
834 panel,
835 svg_formatted_values,
836 } = *p;
837 let (cw, ch) = (
838 area.width.floor().max(1.0) as u32,
839 area.height.floor().max(1.0) as u32,
840 );
841 let layout = GGPlot::layout_built(&mut built, &meta, cw, ch);
842 let mut backend = SvgBackend::new(cw, ch, layout.plot_area.clone());
843 backend.set_formatted_values(svg_formatted_values);
844 let mut attrs = root_data_attrs(&built);
845 attrs.push(("data-panel".into(), panel.clone()));
846 backend.set_root_attrs(attrs);
847 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
848 warnings.extend(
849 built
850 .warnings
851 .iter()
852 .cloned()
853 .chain(backend.take_warnings())
854 .map(|w| format!("panel {panel}: {w}")),
855 );
856 page.push_raw(&backend.finish_fragment(area.x, area.y));
857 Ok(())
858 }
859 Prepared::Grid(g) => {
860 let g = *g;
861 let theme = &g.theme;
862 let m = &theme.plot_margin;
863 let mut top = area.y;
865 let (x0, x1) = (area.x + m.left, area.x + area.width - m.right);
866 if let Some(t) = &g.title {
867 top += m.top;
868 let (tx, anchor) = hjust_x(&theme.title, x0, x1);
869 page.draw_text(
870 t,
871 (tx, top + theme.title.size * 0.8),
872 &text_style(&theme.title, anchor),
873 )
874 .map_err(GGError::Render)?;
875 top += theme.title.size * 1.6;
876 }
877 if let Some(s) = &g.subtitle {
878 if g.title.is_none() {
879 top += m.top;
880 }
881 let (sx, anchor) = hjust_x(&theme.subtitle, x0, x1);
882 page.draw_text(
883 s,
884 (sx, top + theme.subtitle.size * 0.7),
885 &text_style(&theme.subtitle, anchor),
886 )
887 .map_err(GGError::Render)?;
888 top += theme.subtitle.size * 1.5;
889 }
890 let mut bottom = area.y + area.height;
891 if let Some(c) = &g.caption {
892 let (cx, anchor) = hjust_x(&theme.caption, x0, x1);
893 bottom -= theme.caption.size * 1.8;
894 page.draw_text(
895 c,
896 (cx, bottom + theme.caption.size * 0.9),
897 &text_style(&theme.caption, anchor),
898 )
899 .map_err(GGError::Render)?;
900 }
901 let body_h = (bottom - top).max(1.0);
902 let cols = tracks(&g.widths, g.ncol, area.width, g.spacing);
903 let rows = tracks(&g.heights, g.nrow, body_h, g.spacing);
904 for (k, cell) in g.cells.into_iter().enumerate() {
905 let (r, c) = if g.byrow {
906 (k / g.ncol, k % g.ncol)
907 } else {
908 (k % g.nrow, k / g.nrow)
909 };
910 if r >= g.nrow || c >= g.ncol {
911 warnings.push(format!(
913 "plot_grid: cell {} does not fit a {}×{} grid; skipped",
914 k + 1,
915 g.nrow,
916 g.ncol
917 ));
918 continue;
919 }
920 let rect = Rect {
921 x: area.x + cols[c].0,
922 y: top + rows[r].0,
923 width: cols[c].1,
924 height: rows[r].1,
925 };
926 render_prepared(cell, &rect, page, warnings)?;
927 }
928 Ok(())
929 }
930 }
931}
932
933struct Measure<'a> {
935 inner: &'a mut SvgBackend,
936 pa: Rect,
937 bbox: Option<(f64, f64, f64, f64)>,
938}
939
940impl<'a> Measure<'a> {
941 fn new(inner: &'a mut SvgBackend, pa: Rect) -> Self {
942 Measure {
943 inner,
944 pa,
945 bbox: None,
946 }
947 }
948
949 fn grow(&mut self, x0: f64, y0: f64, x1: f64, y1: f64) {
950 if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) {
951 return;
952 }
953 self.bbox = Some(match self.bbox {
954 None => (x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)),
955 Some((a, b, c, d)) => (
956 a.min(x0.min(x1)),
957 b.min(y0.min(y1)),
958 c.max(x0.max(x1)),
959 d.max(y0.max(y1)),
960 ),
961 });
962 }
963
964 fn extent(&self) -> Option<(f64, f64, f64, f64)> {
965 self.bbox
966 }
967}
968
969impl DrawBackend for Measure<'_> {
970 fn draw_circle(
971 &mut self,
972 c: (f64, f64),
973 r: f64,
974 style: &PointStyle,
975 ) -> Result<(), RenderError> {
976 self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
977 self.inner.draw_circle(c, r, style)
978 }
979 fn draw_line(&mut self, pts: &[(f64, f64)], style: &LineStyle) -> Result<(), RenderError> {
980 for p in pts {
981 self.grow(p.0, p.1, p.0, p.1);
982 }
983 self.inner.draw_line(pts, style)
984 }
985 fn draw_quadratic(
986 &mut self,
987 p0: (f64, f64),
988 ctrl: (f64, f64),
989 p1: (f64, f64),
990 style: &LineStyle,
991 ) -> Result<(), RenderError> {
992 self.grow(p0.0, p0.1, p0.0, p0.1);
993 self.grow(ctrl.0, ctrl.1, ctrl.0, ctrl.1);
994 self.grow(p1.0, p1.1, p1.0, p1.1);
995 self.inner.draw_quadratic(p0, ctrl, p1, style)
996 }
997 fn draw_rect(
998 &mut self,
999 a: (f64, f64),
1000 b: (f64, f64),
1001 style: &RectStyle,
1002 ) -> Result<(), RenderError> {
1003 self.grow(a.0, a.1, b.0, b.1);
1004 self.inner.draw_rect(a, b, style)
1005 }
1006 fn draw_text(
1007 &mut self,
1008 text: &str,
1009 pos: (f64, f64),
1010 style: &TextStyle,
1011 ) -> Result<(), RenderError> {
1012 let w = text.chars().count() as f64 * style.size * 0.6;
1013 let (x0, x1) = match style.anchor {
1014 TextAnchor::Start => (pos.0, pos.0 + w),
1015 TextAnchor::Middle => (pos.0 - w / 2.0, pos.0 + w / 2.0),
1016 TextAnchor::End => (pos.0 - w, pos.0),
1017 };
1018 self.grow(x0, pos.1 - style.size / 2.0, x1, pos.1 + style.size / 2.0);
1019 self.inner.draw_text(text, pos, style)
1020 }
1021 fn draw_polygon(&mut self, pts: &[(f64, f64)], style: &RectStyle) -> Result<(), RenderError> {
1022 for p in pts {
1023 self.grow(p.0, p.1, p.0, p.1);
1024 }
1025 self.inner.draw_polygon(pts, style)
1026 }
1027 fn draw_shape(&mut self, c: (f64, f64), r: f64, style: &PointStyle) -> Result<(), RenderError> {
1028 self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
1029 self.inner.draw_shape(c, r, style)
1030 }
1031 fn plot_area(&self) -> Rect {
1032 self.pa.clone()
1033 }
1034 fn total_area(&self) -> Rect {
1035 self.inner.total_area()
1036 }
1037 fn set_tooltip(&mut self, t: Option<String>) {
1038 self.inner.set_tooltip(t)
1039 }
1040 fn set_mark_axis(&mut self, k: Option<String>) {
1041 self.inner.set_mark_axis(k)
1042 }
1043 fn set_mark_series(&mut self, s: Option<String>) {
1044 self.inner.set_mark_series(s)
1045 }
1046 fn set_mark_value(&mut self, v: Option<String>) {
1047 self.inner.set_mark_value(v)
1048 }
1049 fn warn(&mut self, m: String) {
1050 self.inner.warn(m)
1051 }
1052 fn set_mark_geom(&mut self, geom: Option<&str>) {
1053 self.inner.set_mark_geom(geom)
1054 }
1055 fn set_mark_part(&mut self, part: Option<&str>) {
1056 self.inner.set_mark_part(part)
1057 }
1058 fn set_mark_attrs(&mut self, attrs: Vec<(String, String)>) {
1059 self.inner.set_mark_attrs(attrs)
1060 }
1061 fn wants_formatted_values(&self) -> bool {
1062 self.inner.wants_formatted_values()
1063 }
1064 fn set_mark_fvalue(&mut self, value: Option<String>) {
1065 self.inner.set_mark_fvalue(value)
1066 }
1067 fn set_mark_fx(&mut self, value: Option<String>) {
1068 self.inner.set_mark_fx(value)
1069 }
1070}
1071
1072fn join(op: Op, a: GridCell, b: GridCell) -> PlotGrid {
1075 let flatten = |c: GridCell| -> Vec<GridCell> {
1076 match c {
1077 GridCell::Grid(g) if g.op == Some(op) && g.is_plain() => g.cells,
1078 other => vec![other],
1079 }
1080 };
1081 let mut cells = flatten(a);
1082 cells.extend(flatten(b));
1083 PlotGrid {
1084 cells,
1085 op: Some(op),
1086 ..PlotGrid::default()
1087 }
1088}
1089
1090impl PlotGrid {
1091 fn is_plain(&self) -> bool {
1094 self.ncol.is_none()
1095 && self.nrow.is_none()
1096 && self.widths.is_empty()
1097 && self.heights.is_empty()
1098 && self.title.is_none()
1099 && self.subtitle.is_none()
1100 && self.caption.is_none()
1101 && self.tags.is_none()
1102 && !self.collect_legends
1103 }
1104}
1105
1106macro_rules! grid_ops {
1107 ($lhs:ty, $rhs:ty) => {
1108 impl BitOr<$rhs> for $lhs {
1110 type Output = PlotGrid;
1111 fn bitor(self, rhs: $rhs) -> PlotGrid {
1112 join(Op::Row, self.into(), rhs.into())
1113 }
1114 }
1115 impl Div<$rhs> for $lhs {
1117 type Output = PlotGrid;
1118 fn div(self, rhs: $rhs) -> PlotGrid {
1119 join(Op::Col, self.into(), rhs.into())
1120 }
1121 }
1122 };
1123}
1124
1125grid_ops!(GGPlot, GGPlot);
1126grid_ops!(GGPlot, PlotGrid);
1127grid_ops!(PlotGrid, GGPlot);
1128grid_ops!(PlotGrid, PlotGrid);
1129
1130#[cfg(test)]
1131mod tests {
1132 use super::*;
1133
1134 #[test]
1135 fn tag_sequences() {
1136 let l: Vec<String> = (0..28).map(|i| TagLevels::Lower.tag(i)).collect();
1137 assert_eq!(&l[..3], &["a", "b", "c"]);
1138 assert_eq!(l[25], "z");
1139 assert_eq!(l[26], "aa");
1140 assert_eq!(l[27], "ab");
1141 assert_eq!(TagLevels::Upper.tag(1), "B");
1142 assert_eq!(TagLevels::Numeric.tag(9), "10");
1143 assert_eq!(TagLevels::LowerRoman.tag(3), "iv");
1144 assert_eq!(TagLevels::UpperRoman.tag(13), "XIV");
1145 assert_eq!(TagLevels::Custom(vec!["x".into()]).tag(1), "2");
1146 }
1147
1148 #[test]
1149 fn tracks_are_relative_and_robust() {
1150 let t = tracks(&[2.0, 1.0], 2, 300.0, 0.0);
1151 assert_eq!(t, vec![(0.0, 200.0), (200.0, 100.0)]);
1152 let t = tracks(&[f64::NAN, -1.0], 2, 100.0, 10.0);
1153 assert_eq!(t, vec![(0.0, 45.0), (55.0, 45.0)]);
1154 let t = tracks(&[], 3, 30.0, 100.0);
1155 assert!(t.iter().all(|(p, s)| p.is_finite() && *s == 0.0));
1156 }
1157
1158 #[test]
1162 fn measure_forwards_draw_quadratic_and_mark_metadata_and_grows_its_extent() {
1163 let pa = Rect {
1164 x: 0.0,
1165 y: 0.0,
1166 width: 100.0,
1167 height: 100.0,
1168 };
1169 let mut backend = SvgBackend::new(100, 100, pa.clone());
1170 backend.set_formatted_values(true);
1171 let mut meas = Measure::new(&mut backend, pa);
1172
1173 assert!(meas.extent().is_none());
1174 assert!(meas.wants_formatted_values());
1176 meas.set_mark_geom(Some("line"));
1177 meas.set_mark_part(Some("arrow"));
1178 meas.set_mark_attrs(vec![("data-x".to_string(), "v".to_string())]);
1179 meas.set_mark_fvalue(Some("1,234.5".to_string()));
1180 meas.set_mark_fx(Some("2026-10-12".to_string()));
1181 meas.draw_quadratic(
1182 (10.0, 20.0),
1183 (90.0, 5.0),
1184 (50.0, 80.0),
1185 &LineStyle::default(),
1186 )
1187 .unwrap();
1188 meas.set_mark_geom(None);
1189 meas.set_mark_part(None);
1190 meas.set_mark_attrs(Vec::new());
1191 meas.set_mark_fvalue(None);
1192 meas.set_mark_fx(None);
1193
1194 let (x0, y0, x1, y1) = meas.extent().expect("extent after drawing");
1195 assert_eq!((x0, y0, x1, y1), (10.0, 5.0, 90.0, 80.0));
1196
1197 let svg = backend.finish();
1201 assert!(svg.contains("data-part=\"arrow\""));
1202 assert!(svg.contains("data-x=\"v\""));
1203 assert!(svg.contains("gg-arrow"));
1204 assert!(svg.contains("data-fvalue=\"1,234.5\""));
1205 assert!(svg.contains("data-fx=\"2026-10-12\""));
1206 }
1207}