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 };
421 let prepared = prepare_grid(self, &mut ctx)?;
422 let legends = ctx.legends;
423
424 let full = Rect {
426 x: 0.0,
427 y: 0.0,
428 width: w as f64,
429 height: h as f64,
430 };
431 let mut page = SvgBackend::new(w, h, full.clone());
432 page.without_plot_attr();
433 let (rows, cols) = prepared.dims();
434 let data_grid_attr = ("data-grid".to_string(), format!("{rows} {cols}"));
435 page.set_root_attrs(vec![data_grid_attr.clone()]);
436 if let Some(fill) = theme
437 .plot_background
438 .fill
439 .filter(|_| theme.plot_background.visible)
440 {
441 page.draw_rect(
442 (0.0, 0.0),
443 (w as f64, h as f64),
444 &RectStyle {
445 fill: Some(fill),
446 stroke: None,
447 stroke_width: 0.0,
448 alpha: 1.0,
449 clip: false,
450 },
451 )
452 .map_err(GGError::Render)?;
453 }
454
455 let mut body = full;
456 if !legends.is_empty() {
457 let gap = theme.legend_spacing.max(0.0) * 2.0;
458 let pad = 8.0;
459 match legend_pos {
460 GridLegendPosition::Right => {
461 let strip_w = legends.iter().map(|l| l.w).fold(0.0, f64::max) + 2.0 * pad;
462 let strip_w = strip_w.min(body.width * 0.4);
463 body.width -= strip_w;
464 let total_h =
465 legends.iter().map(|l| l.h).sum::<f64>() + gap * (legends.len() - 1) as f64;
466 let mut y = (body.y + (body.height - total_h) / 2.0).max(body.y + pad);
467 for l in &legends {
468 place_legend(&mut page, l, body.x + body.width + pad, y);
469 y += l.h + gap;
470 }
471 }
472 GridLegendPosition::Bottom => {
473 let strip_h = legends.iter().map(|l| l.h).fold(0.0, f64::max) + 2.0 * pad;
474 let strip_h = strip_h.min(body.height * 0.4);
475 body.height -= strip_h;
476 let total_w =
477 legends.iter().map(|l| l.w).sum::<f64>() + gap * (legends.len() - 1) as f64;
478 let mut x = (body.x + (body.width - total_w) / 2.0).max(body.x + pad);
479 for l in &legends {
480 place_legend(&mut page, l, x, body.y + body.height + pad);
481 x += l.w + gap;
482 }
483 }
484 }
485 }
486
487 let mut warnings = Vec::new();
489 render_prepared(prepared, &body, &mut page, &mut warnings)?;
490
491 let mut reserved = vec![data_grid_attr];
492 if svg_warnings_attr {
493 reserved.push(("data-warnings".to_string(), String::new()));
494 }
495 let extra = crate::render::svg_backend::validate_root_attrs(
496 &root_attrs,
497 &reserved,
498 "grid",
499 &mut warnings,
500 );
501 page.extend_root_attrs(extra);
502 if svg_warnings_attr {
503 page.extend_root_attrs(vec![(
504 "data-warnings".to_string(),
505 crate::render::svg_backend::warnings_json(&warnings),
506 )]);
507 }
508 Ok((page, warnings))
509 }
510}
511
512struct Legend {
514 body: String,
515 x0: f64,
516 y0: f64,
517 w: f64,
518 h: f64,
519}
520
521fn place_legend(page: &mut SvgBackend, l: &Legend, x: f64, y: f64) {
522 let (tx, ty) = (x - l.x0, y - l.y0);
523 if tx.is_finite() && ty.is_finite() {
524 page.push_raw(&format!(
525 "<g class=\"legend\" transform=\"translate({tx:.2} {ty:.2})\">{}</g>",
526 l.body
527 ));
528 }
529}
530
531struct PrepCtx {
532 tags: Option<(TagLevels, String, String)>,
533 next_tag: usize,
534 next_index: usize,
535 collect: Option<GridLegendPosition>,
536 legends: Vec<Legend>,
537}
538
539struct PreparedPlot {
541 built: crate::build::BuiltPlot,
542 meta: RenderMeta,
543 panel: String,
544 svg_formatted_values: bool,
552}
553
554enum Prepared {
555 Plot(Box<PreparedPlot>),
556 Grid(Box<PreparedGrid>),
557 Spacer,
558}
559
560struct PreparedGrid {
561 cells: Vec<Prepared>,
562 ncol: usize,
563 nrow: usize,
564 byrow: bool,
565 widths: Vec<f64>,
566 heights: Vec<f64>,
567 title: Option<String>,
568 subtitle: Option<String>,
569 caption: Option<String>,
570 spacing: f64,
571 theme: Theme,
572}
573
574impl Prepared {
575 fn dims(&self) -> (usize, usize) {
576 match self {
577 Prepared::Grid(g) => (g.nrow, g.ncol),
578 _ => (1, 1),
579 }
580 }
581}
582
583fn prepare_grid(grid: PlotGrid, ctx: &mut PrepCtx) -> Result<Prepared, GGError> {
584 let n = grid.cells.len();
585 let (ncol, nrow) = match (grid.ncol, grid.nrow, grid.op) {
586 (Some(c), Some(r), _) => {
587 (c, r.max(n.div_ceil(c)))
589 }
590 (Some(c), None, _) => (c, n.div_ceil(c).max(1)),
591 (None, Some(r), _) => (n.div_ceil(r).max(1), r),
592 (None, None, Some(Op::Row)) => (n.max(1), 1),
593 (None, None, Some(Op::Col)) => (1, n.max(1)),
594 (None, None, None) => {
595 let c = ((n as f64).sqrt().ceil() as usize).max(1);
596 (c, n.div_ceil(c).max(1))
597 }
598 };
599 let mut theme = grid.theme;
600 theme.resolve_inheritance();
601 let mut cells = Vec::with_capacity(n);
602 for cell in grid.cells {
603 cells.push(match cell {
604 GridCell::Spacer => Prepared::Spacer,
605 GridCell::Grid(g) => prepare_grid(*g, ctx)?,
606 GridCell::Plot(p) => Prepared::Plot(Box::new(prepare_plot(*p, ctx)?)),
607 });
608 }
609 Ok(Prepared::Grid(Box::new(PreparedGrid {
610 cells,
611 ncol,
612 nrow,
613 byrow: grid.byrow,
614 widths: grid.widths,
615 heights: grid.heights,
616 title: grid.title,
617 subtitle: grid.subtitle,
618 caption: grid.caption,
619 spacing: grid.spacing,
620 theme,
621 })))
622}
623
624fn prepare_plot(mut plot: GGPlot, ctx: &mut PrepCtx) -> Result<PreparedPlot, GGError> {
625 ctx.next_index += 1;
626 if let Some((levels, pre, suf)) = &ctx.tags {
627 plot.labels.tag = Some(format!("{pre}{}{suf}", levels.tag(ctx.next_tag)));
628 ctx.next_tag += 1;
629 }
630 let panel = plot
631 .labels
632 .tag
633 .clone()
634 .unwrap_or_else(|| ctx.next_index.to_string());
635
636 let original = plot.theme.legend_position.clone();
638 let collect = ctx.collect.filter(|_| {
639 matches!(
640 original,
641 LegendPosition::Right
642 | LegendPosition::Left
643 | LegendPosition::Top
644 | LegendPosition::Bottom
645 )
646 });
647 if collect.is_some() {
648 plot.theme.legend_position = LegendPosition::None;
649 }
650 let svg_formatted_values = plot.svg_formatted_values;
651 let (built, mut meta) = plot.build_for_render()?;
652 if let Some(pos) = collect {
653 meta.has_legend = false;
654 if let Some(l) = capture_legend(&built, pos).map_err(GGError::Render)? {
655 if !ctx.legends.iter().any(|o| o.body == l.body) {
656 ctx.legends.push(l);
657 }
658 }
659 }
660 Ok(PreparedPlot {
661 built,
662 meta,
663 panel,
664 svg_formatted_values,
665 })
666}
667
668fn capture_legend(
670 built: &crate::build::BuiltPlot,
671 pos: GridLegendPosition,
672) -> Result<Option<Legend>, RenderError> {
673 let mut theme = built.theme.clone();
674 let m = theme.legend_margin.clone();
675 let (pa, lp) = match pos {
677 GridLegendPosition::Right => (
678 Rect {
679 x: -m.left,
680 y: -m.top,
681 width: 0.0,
682 height: 0.0,
683 },
684 LegendPosition::Right,
685 ),
686 GridLegendPosition::Bottom => (
687 Rect {
688 x: -m.left,
689 y: -(m.top + 30.0),
690 width: 0.0,
691 height: 0.0,
692 },
693 LegendPosition::Bottom,
694 ),
695 };
696 theme.legend_position = lp;
697 let mut svg = SvgBackend::new(1, 1, pa.clone());
698 let mut meas = Measure::new(&mut svg, pa.clone());
699 legend::draw_legend(
700 &built.scales,
701 &theme,
702 &pa,
703 &mut meas,
704 &built.guide_legend,
705 &built.suppressed_aes,
706 )?;
707 let ext = meas.extent();
708 if svg.body().is_empty() {
709 return Ok(None);
710 }
711 let (x0, y0, x1, y1) = match ext {
712 Some(e) => e,
713 None => return Ok(None),
714 };
715 Ok(Some(Legend {
716 body: svg.body().to_string(),
717 x0,
718 y0,
719 w: (x1 - x0).max(0.0),
720 h: (y1 - y0).max(0.0),
721 }))
722}
723
724fn tracks(weights: &[f64], n: usize, total: f64, gap: f64) -> Vec<(f64, f64)> {
726 let ws: Vec<f64> = (0..n)
727 .map(|i| {
728 if weights.is_empty() {
729 1.0
730 } else {
731 let w = weights[i % weights.len()];
732 if w.is_finite() && w > 0.0 {
733 w
734 } else {
735 1.0
736 }
737 }
738 })
739 .collect();
740 let sum: f64 = ws.iter().sum();
741 let avail = (total - gap * n.saturating_sub(1) as f64).max(0.0);
742 let mut pos = 0.0;
743 ws.iter()
744 .map(|w| {
745 let size = avail * w / sum;
746 let t = (pos, size);
747 pos += size + gap;
748 t
749 })
750 .collect()
751}
752
753fn text_style(el: &crate::theme::elements::ElementText, anchor: TextAnchor) -> TextStyle {
754 TextStyle {
755 color: el.color,
756 size: el.size,
757 anchor,
758 angle: 0.0,
759 family: (!el.family.is_empty()).then(|| el.family.clone()),
760 face: el.face,
761 }
762}
763
764fn hjust_x(el: &crate::theme::elements::ElementText, x0: f64, x1: f64) -> (f64, TextAnchor) {
765 let hj = if el.hjust.is_finite() {
766 el.hjust.clamp(0.0, 1.0)
767 } else {
768 0.0
769 };
770 let anchor = if hj <= 0.02 {
771 TextAnchor::Start
772 } else if hj >= 0.98 {
773 TextAnchor::End
774 } else {
775 TextAnchor::Middle
776 };
777 (x0 + hj * (x1 - x0), anchor)
778}
779
780fn render_prepared(
781 prepared: Prepared,
782 area: &Rect,
783 page: &mut SvgBackend,
784 warnings: &mut Vec<String>,
785) -> Result<(), GGError> {
786 match prepared {
787 Prepared::Spacer => Ok(()),
788 Prepared::Plot(p) => {
789 let PreparedPlot {
790 mut built,
791 meta,
792 panel,
793 svg_formatted_values,
794 } = *p;
795 let (cw, ch) = (
796 area.width.floor().max(1.0) as u32,
797 area.height.floor().max(1.0) as u32,
798 );
799 let layout = GGPlot::layout_built(&mut built, &meta, cw, ch);
800 let mut backend = SvgBackend::new(cw, ch, layout.plot_area.clone());
801 backend.set_formatted_values(svg_formatted_values);
802 let mut attrs = root_data_attrs(&built);
803 attrs.push(("data-panel".into(), panel.clone()));
804 backend.set_root_attrs(attrs);
805 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
806 warnings.extend(
807 built
808 .warnings
809 .iter()
810 .cloned()
811 .chain(backend.take_warnings())
812 .map(|w| format!("panel {panel}: {w}")),
813 );
814 page.push_raw(&backend.finish_fragment(area.x, area.y));
815 Ok(())
816 }
817 Prepared::Grid(g) => {
818 let g = *g;
819 let theme = &g.theme;
820 let m = &theme.plot_margin;
821 let mut top = area.y;
823 let (x0, x1) = (area.x + m.left, area.x + area.width - m.right);
824 if let Some(t) = &g.title {
825 top += m.top;
826 let (tx, anchor) = hjust_x(&theme.title, x0, x1);
827 page.draw_text(
828 t,
829 (tx, top + theme.title.size * 0.8),
830 &text_style(&theme.title, anchor),
831 )
832 .map_err(GGError::Render)?;
833 top += theme.title.size * 1.6;
834 }
835 if let Some(s) = &g.subtitle {
836 if g.title.is_none() {
837 top += m.top;
838 }
839 let (sx, anchor) = hjust_x(&theme.subtitle, x0, x1);
840 page.draw_text(
841 s,
842 (sx, top + theme.subtitle.size * 0.7),
843 &text_style(&theme.subtitle, anchor),
844 )
845 .map_err(GGError::Render)?;
846 top += theme.subtitle.size * 1.5;
847 }
848 let mut bottom = area.y + area.height;
849 if let Some(c) = &g.caption {
850 let (cx, anchor) = hjust_x(&theme.caption, x0, x1);
851 bottom -= theme.caption.size * 1.8;
852 page.draw_text(
853 c,
854 (cx, bottom + theme.caption.size * 0.9),
855 &text_style(&theme.caption, anchor),
856 )
857 .map_err(GGError::Render)?;
858 }
859 let body_h = (bottom - top).max(1.0);
860 let cols = tracks(&g.widths, g.ncol, area.width, g.spacing);
861 let rows = tracks(&g.heights, g.nrow, body_h, g.spacing);
862 for (k, cell) in g.cells.into_iter().enumerate() {
863 let (r, c) = if g.byrow {
864 (k / g.ncol, k % g.ncol)
865 } else {
866 (k % g.nrow, k / g.nrow)
867 };
868 if r >= g.nrow || c >= g.ncol {
869 warnings.push(format!(
871 "plot_grid: cell {} does not fit a {}×{} grid; skipped",
872 k + 1,
873 g.nrow,
874 g.ncol
875 ));
876 continue;
877 }
878 let rect = Rect {
879 x: area.x + cols[c].0,
880 y: top + rows[r].0,
881 width: cols[c].1,
882 height: rows[r].1,
883 };
884 render_prepared(cell, &rect, page, warnings)?;
885 }
886 Ok(())
887 }
888 }
889}
890
891struct Measure<'a> {
893 inner: &'a mut SvgBackend,
894 pa: Rect,
895 bbox: Option<(f64, f64, f64, f64)>,
896}
897
898impl<'a> Measure<'a> {
899 fn new(inner: &'a mut SvgBackend, pa: Rect) -> Self {
900 Measure {
901 inner,
902 pa,
903 bbox: None,
904 }
905 }
906
907 fn grow(&mut self, x0: f64, y0: f64, x1: f64, y1: f64) {
908 if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) {
909 return;
910 }
911 self.bbox = Some(match self.bbox {
912 None => (x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)),
913 Some((a, b, c, d)) => (
914 a.min(x0.min(x1)),
915 b.min(y0.min(y1)),
916 c.max(x0.max(x1)),
917 d.max(y0.max(y1)),
918 ),
919 });
920 }
921
922 fn extent(&self) -> Option<(f64, f64, f64, f64)> {
923 self.bbox
924 }
925}
926
927impl DrawBackend for Measure<'_> {
928 fn draw_circle(
929 &mut self,
930 c: (f64, f64),
931 r: f64,
932 style: &PointStyle,
933 ) -> Result<(), RenderError> {
934 self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
935 self.inner.draw_circle(c, r, style)
936 }
937 fn draw_line(&mut self, pts: &[(f64, f64)], style: &LineStyle) -> Result<(), RenderError> {
938 for p in pts {
939 self.grow(p.0, p.1, p.0, p.1);
940 }
941 self.inner.draw_line(pts, style)
942 }
943 fn draw_quadratic(
944 &mut self,
945 p0: (f64, f64),
946 ctrl: (f64, f64),
947 p1: (f64, f64),
948 style: &LineStyle,
949 ) -> Result<(), RenderError> {
950 self.grow(p0.0, p0.1, p0.0, p0.1);
951 self.grow(ctrl.0, ctrl.1, ctrl.0, ctrl.1);
952 self.grow(p1.0, p1.1, p1.0, p1.1);
953 self.inner.draw_quadratic(p0, ctrl, p1, style)
954 }
955 fn draw_rect(
956 &mut self,
957 a: (f64, f64),
958 b: (f64, f64),
959 style: &RectStyle,
960 ) -> Result<(), RenderError> {
961 self.grow(a.0, a.1, b.0, b.1);
962 self.inner.draw_rect(a, b, style)
963 }
964 fn draw_text(
965 &mut self,
966 text: &str,
967 pos: (f64, f64),
968 style: &TextStyle,
969 ) -> Result<(), RenderError> {
970 let w = text.chars().count() as f64 * style.size * 0.6;
971 let (x0, x1) = match style.anchor {
972 TextAnchor::Start => (pos.0, pos.0 + w),
973 TextAnchor::Middle => (pos.0 - w / 2.0, pos.0 + w / 2.0),
974 TextAnchor::End => (pos.0 - w, pos.0),
975 };
976 self.grow(x0, pos.1 - style.size / 2.0, x1, pos.1 + style.size / 2.0);
977 self.inner.draw_text(text, pos, style)
978 }
979 fn draw_polygon(&mut self, pts: &[(f64, f64)], style: &RectStyle) -> Result<(), RenderError> {
980 for p in pts {
981 self.grow(p.0, p.1, p.0, p.1);
982 }
983 self.inner.draw_polygon(pts, style)
984 }
985 fn draw_shape(&mut self, c: (f64, f64), r: f64, style: &PointStyle) -> Result<(), RenderError> {
986 self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
987 self.inner.draw_shape(c, r, style)
988 }
989 fn plot_area(&self) -> Rect {
990 self.pa.clone()
991 }
992 fn total_area(&self) -> Rect {
993 self.inner.total_area()
994 }
995 fn set_tooltip(&mut self, t: Option<String>) {
996 self.inner.set_tooltip(t)
997 }
998 fn set_mark_axis(&mut self, k: Option<String>) {
999 self.inner.set_mark_axis(k)
1000 }
1001 fn set_mark_series(&mut self, s: Option<String>) {
1002 self.inner.set_mark_series(s)
1003 }
1004 fn set_mark_value(&mut self, v: Option<String>) {
1005 self.inner.set_mark_value(v)
1006 }
1007 fn warn(&mut self, m: String) {
1008 self.inner.warn(m)
1009 }
1010 fn set_mark_geom(&mut self, geom: Option<&str>) {
1011 self.inner.set_mark_geom(geom)
1012 }
1013 fn set_mark_part(&mut self, part: Option<&str>) {
1014 self.inner.set_mark_part(part)
1015 }
1016 fn set_mark_attrs(&mut self, attrs: Vec<(String, String)>) {
1017 self.inner.set_mark_attrs(attrs)
1018 }
1019 fn wants_formatted_values(&self) -> bool {
1020 self.inner.wants_formatted_values()
1021 }
1022 fn set_mark_fvalue(&mut self, value: Option<String>) {
1023 self.inner.set_mark_fvalue(value)
1024 }
1025 fn set_mark_fx(&mut self, value: Option<String>) {
1026 self.inner.set_mark_fx(value)
1027 }
1028}
1029
1030fn join(op: Op, a: GridCell, b: GridCell) -> PlotGrid {
1033 let flatten = |c: GridCell| -> Vec<GridCell> {
1034 match c {
1035 GridCell::Grid(g) if g.op == Some(op) && g.is_plain() => g.cells,
1036 other => vec![other],
1037 }
1038 };
1039 let mut cells = flatten(a);
1040 cells.extend(flatten(b));
1041 PlotGrid {
1042 cells,
1043 op: Some(op),
1044 ..PlotGrid::default()
1045 }
1046}
1047
1048impl PlotGrid {
1049 fn is_plain(&self) -> bool {
1052 self.ncol.is_none()
1053 && self.nrow.is_none()
1054 && self.widths.is_empty()
1055 && self.heights.is_empty()
1056 && self.title.is_none()
1057 && self.subtitle.is_none()
1058 && self.caption.is_none()
1059 && self.tags.is_none()
1060 && !self.collect_legends
1061 }
1062}
1063
1064macro_rules! grid_ops {
1065 ($lhs:ty, $rhs:ty) => {
1066 impl BitOr<$rhs> for $lhs {
1068 type Output = PlotGrid;
1069 fn bitor(self, rhs: $rhs) -> PlotGrid {
1070 join(Op::Row, self.into(), rhs.into())
1071 }
1072 }
1073 impl Div<$rhs> for $lhs {
1075 type Output = PlotGrid;
1076 fn div(self, rhs: $rhs) -> PlotGrid {
1077 join(Op::Col, self.into(), rhs.into())
1078 }
1079 }
1080 };
1081}
1082
1083grid_ops!(GGPlot, GGPlot);
1084grid_ops!(GGPlot, PlotGrid);
1085grid_ops!(PlotGrid, GGPlot);
1086grid_ops!(PlotGrid, PlotGrid);
1087
1088#[cfg(test)]
1089mod tests {
1090 use super::*;
1091
1092 #[test]
1093 fn tag_sequences() {
1094 let l: Vec<String> = (0..28).map(|i| TagLevels::Lower.tag(i)).collect();
1095 assert_eq!(&l[..3], &["a", "b", "c"]);
1096 assert_eq!(l[25], "z");
1097 assert_eq!(l[26], "aa");
1098 assert_eq!(l[27], "ab");
1099 assert_eq!(TagLevels::Upper.tag(1), "B");
1100 assert_eq!(TagLevels::Numeric.tag(9), "10");
1101 assert_eq!(TagLevels::LowerRoman.tag(3), "iv");
1102 assert_eq!(TagLevels::UpperRoman.tag(13), "XIV");
1103 assert_eq!(TagLevels::Custom(vec!["x".into()]).tag(1), "2");
1104 }
1105
1106 #[test]
1107 fn tracks_are_relative_and_robust() {
1108 let t = tracks(&[2.0, 1.0], 2, 300.0, 0.0);
1109 assert_eq!(t, vec![(0.0, 200.0), (200.0, 100.0)]);
1110 let t = tracks(&[f64::NAN, -1.0], 2, 100.0, 10.0);
1111 assert_eq!(t, vec![(0.0, 45.0), (55.0, 45.0)]);
1112 let t = tracks(&[], 3, 30.0, 100.0);
1113 assert!(t.iter().all(|(p, s)| p.is_finite() && *s == 0.0));
1114 }
1115
1116 #[test]
1120 fn measure_forwards_draw_quadratic_and_mark_metadata_and_grows_its_extent() {
1121 let pa = Rect {
1122 x: 0.0,
1123 y: 0.0,
1124 width: 100.0,
1125 height: 100.0,
1126 };
1127 let mut backend = SvgBackend::new(100, 100, pa.clone());
1128 backend.set_formatted_values(true);
1129 let mut meas = Measure::new(&mut backend, pa);
1130
1131 assert!(meas.extent().is_none());
1132 assert!(meas.wants_formatted_values());
1134 meas.set_mark_geom(Some("line"));
1135 meas.set_mark_part(Some("arrow"));
1136 meas.set_mark_attrs(vec![("data-x".to_string(), "v".to_string())]);
1137 meas.set_mark_fvalue(Some("1,234.5".to_string()));
1138 meas.set_mark_fx(Some("2026-10-12".to_string()));
1139 meas.draw_quadratic(
1140 (10.0, 20.0),
1141 (90.0, 5.0),
1142 (50.0, 80.0),
1143 &LineStyle::default(),
1144 )
1145 .unwrap();
1146 meas.set_mark_geom(None);
1147 meas.set_mark_part(None);
1148 meas.set_mark_attrs(Vec::new());
1149 meas.set_mark_fvalue(None);
1150 meas.set_mark_fx(None);
1151
1152 let (x0, y0, x1, y1) = meas.extent().expect("extent after drawing");
1153 assert_eq!((x0, y0, x1, y1), (10.0, 5.0, 90.0, 80.0));
1154
1155 let svg = backend.finish();
1159 assert!(svg.contains("data-part=\"arrow\""));
1160 assert!(svg.contains("data-x=\"v\""));
1161 assert!(svg.contains("gg-arrow"));
1162 assert!(svg.contains("data-fvalue=\"1,234.5\""));
1163 assert!(svg.contains("data-fx=\"2026-10-12\""));
1164 }
1165}