1use std::ops::{BitOr, Div};
27
28use crate::aes::Aesthetic;
29use crate::guide::legend;
30use crate::plot::{GGError, GGPlot, RenderMeta};
31use crate::render::backend::{
32 DrawBackend, LineStyle, PointStyle, RectStyle, TextAnchor, TextStyle,
33};
34use crate::render::renderer::PlotRenderer;
35use crate::render::svg_backend::{root_data_attrs, validate_root_attrs, SvgBackend};
36use crate::render::{Rect, RenderError};
37use crate::theme::elements::{ElementLine, ElementText};
38use crate::theme::{AxisLabelFit, LegendPosition, Theme};
39
40#[derive(Clone, Debug, PartialEq)]
42pub enum TagLevels {
43 Lower,
45 Upper,
47 Numeric,
49 LowerRoman,
51 UpperRoman,
53 Custom(Vec<String>),
55}
56
57impl TagLevels {
58 pub fn tag(&self, i: usize) -> String {
60 match self {
61 TagLevels::Lower => alpha(i, b'a'),
62 TagLevels::Upper => alpha(i, b'A'),
63 TagLevels::Numeric => (i + 1).to_string(),
64 TagLevels::LowerRoman => roman(i + 1).to_lowercase(),
65 TagLevels::UpperRoman => roman(i + 1),
66 TagLevels::Custom(v) => v.get(i).cloned().unwrap_or_else(|| (i + 1).to_string()),
67 }
68 }
69}
70
71fn alpha(mut i: usize, base: u8) -> String {
72 let mut out = Vec::new();
74 loop {
75 out.push(base + (i % 26) as u8);
76 if i < 26 {
77 break;
78 }
79 i = i / 26 - 1;
80 }
81 out.reverse();
82 String::from_utf8(out).unwrap_or_default()
83}
84
85fn roman(mut n: usize) -> String {
86 if n >= 4000 {
87 return n.to_string();
88 }
89 const T: [(usize, &str); 13] = [
90 (1000, "M"),
91 (900, "CM"),
92 (500, "D"),
93 (400, "CD"),
94 (100, "C"),
95 (90, "XC"),
96 (50, "L"),
97 (40, "XL"),
98 (10, "X"),
99 (9, "IX"),
100 (5, "V"),
101 (4, "IV"),
102 (1, "I"),
103 ];
104 let mut s = String::new();
105 for (v, r) in T {
106 while n >= v {
107 s.push_str(r);
108 n -= v;
109 }
110 }
111 s
112}
113
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
122pub enum AxisCollect {
123 #[default]
125 Keep,
126 Align,
141 CollectX,
148}
149
150#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
152pub enum GridLegendPosition {
153 #[default]
155 Right,
156 Bottom,
158}
159
160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163enum Op {
164 Row,
165 Col,
166}
167
168pub enum GridCell {
170 Plot(Box<GGPlot>),
171 Grid(Box<PlotGrid>),
172 Spacer,
174 Element(Box<GridElement>),
177}
178
179enum ElementContent {
181 Fixed {
184 svg: String,
185 width: f64,
186 height: f64,
187 },
188 Fill(Box<dyn Fn(f64, f64) -> String + Send + Sync>),
190}
191
192pub struct GridElement {
200 content: ElementContent,
201}
202
203impl GridElement {
204 pub fn fixed(svg: impl Into<String>, width: f64, height: f64) -> Self {
207 GridElement {
208 content: ElementContent::Fixed {
209 svg: svg.into(),
210 width,
211 height,
212 },
213 }
214 }
215
216 pub fn fill(render: impl Fn(f64, f64) -> String + Send + Sync + 'static) -> Self {
219 GridElement {
220 content: ElementContent::Fill(Box::new(render)),
221 }
222 }
223}
224
225impl From<GridElement> for GridCell {
226 fn from(e: GridElement) -> Self {
227 GridCell::Element(Box::new(e))
228 }
229}
230
231impl From<GGPlot> for GridCell {
232 fn from(p: GGPlot) -> Self {
233 GridCell::Plot(Box::new(p))
234 }
235}
236
237impl From<PlotGrid> for GridCell {
238 fn from(g: PlotGrid) -> Self {
239 GridCell::Grid(Box::new(g))
240 }
241}
242
243pub struct PlotGrid {
262 cells: Vec<GridCell>,
263 ncol: Option<usize>,
264 nrow: Option<usize>,
265 byrow: bool,
266 widths: Vec<f64>,
267 heights: Vec<f64>,
268 title: Option<String>,
269 subtitle: Option<String>,
270 caption: Option<String>,
271 tags: Option<TagLevels>,
272 tag_prefix: String,
273 tag_suffix: String,
274 collect_legends: bool,
275 legend_position: GridLegendPosition,
276 legend_bottom_share: Option<f64>,
278 spacing: f64,
279 theme: Theme,
280 axis_collect: AxisCollect,
281 op: Option<Op>,
282 root_attrs: Vec<(String, String)>,
285 svg_warnings_attr: bool,
290}
291
292impl Default for PlotGrid {
293 fn default() -> Self {
294 PlotGrid {
295 cells: Vec::new(),
296 ncol: None,
297 nrow: None,
298 byrow: true,
299 widths: Vec::new(),
300 heights: Vec::new(),
301 title: None,
302 subtitle: None,
303 caption: None,
304 tags: None,
305 tag_prefix: String::new(),
306 tag_suffix: String::new(),
307 collect_legends: false,
308 legend_position: GridLegendPosition::Right,
309 legend_bottom_share: None,
310 spacing: 0.0,
311 theme: Theme::default(),
312 axis_collect: AxisCollect::Keep,
313 op: None,
314 root_attrs: Vec::new(),
315 svg_warnings_attr: false,
316 }
317 }
318}
319
320const MAX_TRACKS: usize = 10_000;
322
323impl PlotGrid {
324 pub fn new() -> Self {
325 Self::default()
326 }
327
328 #[allow(clippy::should_implement_trait)]
330 pub fn add(mut self, cell: impl Into<GridCell>) -> Self {
331 self.cells.push(cell.into());
332 self
333 }
334
335 pub fn add_all(mut self, plots: impl IntoIterator<Item = GGPlot>) -> Self {
337 self.cells.extend(plots.into_iter().map(GridCell::from));
338 self
339 }
340
341 pub fn add_spacer(mut self) -> Self {
343 self.cells.push(GridCell::Spacer);
344 self
345 }
346
347 pub fn ncol(mut self, n: usize) -> Self {
349 self.ncol = (n > 0).then_some(n.min(MAX_TRACKS));
350 self
351 }
352
353 pub fn nrow(mut self, n: usize) -> Self {
355 self.nrow = (n > 0).then_some(n.min(MAX_TRACKS));
356 self
357 }
358
359 pub fn byrow(mut self, byrow: bool) -> Self {
361 self.byrow = byrow;
362 self
363 }
364
365 pub fn widths(mut self, widths: &[f64]) -> Self {
367 self.widths = widths.to_vec();
368 self
369 }
370
371 pub fn heights(mut self, heights: &[f64]) -> Self {
373 self.heights = heights.to_vec();
374 self
375 }
376
377 pub fn title(mut self, title: &str) -> Self {
379 self.title = Some(title.to_string());
380 self
381 }
382
383 pub fn subtitle(mut self, subtitle: &str) -> Self {
385 self.subtitle = Some(subtitle.to_string());
386 self
387 }
388
389 pub fn caption(mut self, caption: &str) -> Self {
391 self.caption = Some(caption.to_string());
392 self
393 }
394
395 pub fn tag_levels(mut self, levels: TagLevels) -> Self {
397 self.tags = Some(levels);
398 self
399 }
400
401 pub fn tag_affixes(mut self, prefix: &str, suffix: &str) -> Self {
403 self.tag_prefix = prefix.to_string();
404 self.tag_suffix = suffix.to_string();
405 self
406 }
407
408 pub fn collect_legends(mut self, collect: bool) -> Self {
411 self.collect_legends = collect;
412 self
413 }
414
415 pub fn legend_position(mut self, pos: GridLegendPosition) -> Self {
417 self.legend_position = pos;
418 self
419 }
420
421 pub fn legend_bottom_when_narrow(mut self, share: f64) -> Self {
429 self.legend_bottom_share = Some(share);
430 self
431 }
432
433 pub fn axis_collect(mut self, mode: AxisCollect) -> Self {
437 self.axis_collect = mode;
438 self
439 }
440
441 pub fn spacing(mut self, px: f64) -> Self {
443 self.spacing = if px.is_finite() { px.max(0.0) } else { 0.0 };
444 self
445 }
446
447 pub fn theme(mut self, theme: Theme) -> Self {
450 self.theme = theme;
451 self
452 }
453
454 pub fn svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
461 self.root_attrs.push((name.into(), value.into()));
462 self
463 }
464
465 pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
467 self.root_attrs.extend(attrs);
468 self
469 }
470
471 pub fn svg_warnings_attr(mut self, on: bool) -> Self {
475 self.svg_warnings_attr = on;
476 self
477 }
478
479 pub fn len(&self) -> usize {
481 self.cells.len()
482 }
483
484 pub fn is_empty(&self) -> bool {
486 self.cells.is_empty()
487 }
488
489 pub fn render_svg_native(self) -> Result<String, GGError> {
491 self.render_svg_native_with_size(800, 600)
492 }
493
494 pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
498 Ok(self.render_page(w, h)?.0.finish())
499 }
500
501 pub fn render_svg_native_with_warnings(
504 self,
505 w: u32,
506 h: u32,
507 ) -> Result<(String, Vec<String>), GGError> {
508 let (page, warnings) = self.render_page(w, h)?;
509 Ok((page.finish(), warnings))
510 }
511
512 pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
515 Ok(self.render_page(w, h)?.0.finish_fragment(x, y))
516 }
517
518 fn render_page(self, w: u32, h: u32) -> Result<(SvgBackend, Vec<String>), GGError> {
519 let (w, h) = (w.max(1), h.max(1));
520 let mut theme = self.theme.clone();
521 theme.resolve_inheritance();
522 let collect = self.collect_legends;
523 let mut legend_pos = self.legend_position;
524 let alt_pos = self
527 .legend_bottom_share
528 .filter(|_| legend_pos == GridLegendPosition::Right)
529 .map(|share| (share, GridLegendPosition::Bottom));
530 let root_attrs = self.root_attrs.clone();
531 let svg_warnings_attr = self.svg_warnings_attr;
532
533 let mut ctx = PrepCtx {
536 tags: self
537 .tags
538 .clone()
539 .map(|t| (t, self.tag_prefix.clone(), self.tag_suffix.clone())),
540 next_tag: 0,
541 next_index: 0,
542 collect: collect.then_some(legend_pos),
543 collect_alt: alt_pos.map(|(_, p)| p),
544 legends: Vec::new(),
545 page_w: w as f64,
546 page_h: h as f64,
547 legend_warnings: Vec::new(),
548 };
549 let prepared = prepare_grid(self, &mut ctx)?;
550 let (mut legends, alt_legends): (Vec<Legend>, Vec<Option<Legend>>) =
551 ctx.legends.into_iter().unzip();
552 if let Some((share, alt)) = alt_pos {
553 let strip_w = legends.iter().map(|l| l.w).fold(0.0, f64::max) + 2.0 * LEGEND_PAD;
554 if !legends.is_empty() && strip_w > share * w as f64 {
555 legend_pos = alt;
556 legends = alt_legends.into_iter().flatten().collect();
557 }
558 }
559 let legend_warnings = ctx.legend_warnings;
560
561 let full = Rect {
563 x: 0.0,
564 y: 0.0,
565 width: w as f64,
566 height: h as f64,
567 };
568 let mut page = SvgBackend::new(w, h, full.clone());
569 page.without_plot_attr();
570 let (rows, cols) = prepared.dims();
571 let data_grid_attr = ("data-grid".to_string(), format!("{rows} {cols}"));
572 page.set_root_attrs(vec![data_grid_attr.clone()]);
573 if let Some(fill) = theme
574 .plot_background
575 .fill
576 .filter(|_| theme.plot_background.visible)
577 {
578 page.draw_rect(
579 (0.0, 0.0),
580 (w as f64, h as f64),
581 &RectStyle {
582 fill: Some(fill),
583 stroke: None,
584 stroke_width: 0.0,
585 alpha: 1.0,
586 clip: false,
587 corner_radius: 0.0,
588 },
589 )
590 .map_err(GGError::Render)?;
591 }
592
593 let mut body = full;
594 if !legends.is_empty() {
595 let gap = theme.legend_spacing.max(0.0) * 2.0;
596 let pad = LEGEND_PAD;
597 match legend_pos {
598 GridLegendPosition::Right => {
599 let strip_w = legends.iter().map(|l| l.w).fold(0.0, f64::max) + 2.0 * pad;
600 let strip_w = strip_w.min(body.width * 0.4);
601 body.width -= strip_w;
602 let total_h =
603 legends.iter().map(|l| l.h).sum::<f64>() + gap * (legends.len() - 1) as f64;
604 let mut y = (body.y + (body.height - total_h) / 2.0).max(body.y + pad);
605 for l in &legends {
606 place_legend(&mut page, l, body.x + body.width + pad, y);
607 y += l.h + gap;
608 }
609 }
610 GridLegendPosition::Bottom => {
611 let strip_h = legends.iter().map(|l| l.h).fold(0.0, f64::max) + 2.0 * pad;
612 let strip_h = strip_h.min(body.height * 0.4);
613 body.height -= strip_h;
614 let total_w =
615 legends.iter().map(|l| l.w).sum::<f64>() + gap * (legends.len() - 1) as f64;
616 let mut x = (body.x + (body.width - total_w) / 2.0).max(body.x + pad);
617 for l in &legends {
618 place_legend(&mut page, l, x, body.y + body.height + pad);
619 x += l.w + gap;
620 }
621 }
622 }
623 }
624
625 let mut warnings = legend_warnings;
627 render_prepared(prepared, &body, &mut page, &mut warnings)?;
628
629 let mut reserved = vec![data_grid_attr];
630 if svg_warnings_attr {
631 reserved.push(("data-warnings".to_string(), String::new()));
632 }
633 let extra = crate::render::svg_backend::validate_root_attrs(
634 &root_attrs,
635 &reserved,
636 "grid",
637 &mut warnings,
638 );
639 page.extend_root_attrs(extra);
640 if svg_warnings_attr {
641 page.extend_root_attrs(vec![(
642 "data-warnings".to_string(),
643 crate::render::svg_backend::warnings_json(&warnings),
644 )]);
645 }
646 Ok((page, warnings))
647 }
648}
649
650const LEGEND_PAD: f64 = 8.0;
652
653struct Legend {
655 body: String,
656 x0: f64,
657 y0: f64,
658 w: f64,
659 h: f64,
660}
661
662fn place_legend(page: &mut SvgBackend, l: &Legend, x: f64, y: f64) {
663 let (tx, ty) = (x - l.x0, y - l.y0);
664 if tx.is_finite() && ty.is_finite() {
665 page.push_raw(&format!(
666 "<g class=\"legend\" transform=\"translate({tx:.2} {ty:.2})\">{}</g>",
667 l.body
668 ));
669 }
670}
671
672struct PrepCtx {
673 tags: Option<(TagLevels, String, String)>,
674 next_tag: usize,
675 next_index: usize,
676 collect: Option<GridLegendPosition>,
677 collect_alt: Option<GridLegendPosition>,
680 legends: Vec<(Legend, Option<Legend>)>,
682 page_w: f64,
688 page_h: f64,
689 legend_warnings: Vec<String>,
695}
696
697struct PreparedPlot {
699 built: crate::build::BuiltPlot,
700 meta: RenderMeta,
701 panel: String,
702 svg_formatted_values: bool,
710 root_attrs: Vec<(String, String)>,
718}
719
720struct PreparedElement {
722 element: GridElement,
723 index: usize,
724 tag: Option<String>,
725 theme: Theme,
727}
728
729enum Prepared {
730 Plot(Box<PreparedPlot>),
731 Element(Box<PreparedElement>),
732 Grid(Box<PreparedGrid>),
733 Spacer,
734}
735
736struct PreparedGrid {
737 cells: Vec<Prepared>,
738 ncol: usize,
739 nrow: usize,
740 byrow: bool,
741 widths: Vec<f64>,
742 heights: Vec<f64>,
743 title: Option<String>,
744 subtitle: Option<String>,
745 caption: Option<String>,
746 spacing: f64,
747 theme: Theme,
748 axis_collect: AxisCollect,
749}
750
751impl Prepared {
752 fn dims(&self) -> (usize, usize) {
753 match self {
754 Prepared::Grid(g) => (g.nrow, g.ncol),
755 _ => (1, 1),
756 }
757 }
758}
759
760fn prepare_grid(grid: PlotGrid, ctx: &mut PrepCtx) -> Result<Prepared, GGError> {
761 let n = grid.cells.len();
762 let (ncol, nrow) = match (grid.ncol, grid.nrow, grid.op) {
763 (Some(c), Some(r), _) => {
764 (c, r.max(n.div_ceil(c)))
766 }
767 (Some(c), None, _) => (c, n.div_ceil(c).max(1)),
768 (None, Some(r), _) => (n.div_ceil(r).max(1), r),
769 (None, None, Some(Op::Row)) => (n.max(1), 1),
770 (None, None, Some(Op::Col)) => (1, n.max(1)),
771 (None, None, None) => {
772 let c = ((n as f64).sqrt().ceil() as usize).max(1);
773 (c, n.div_ceil(c).max(1))
774 }
775 };
776 let mut theme = grid.theme;
777 theme.resolve_inheritance();
778 let mut cells = Vec::with_capacity(n);
779 for cell in grid.cells {
780 cells.push(match cell {
781 GridCell::Spacer => Prepared::Spacer,
782 GridCell::Grid(g) => prepare_grid(*g, ctx)?,
783 GridCell::Plot(p) => Prepared::Plot(Box::new(prepare_plot(*p, ctx)?)),
784 GridCell::Element(e) => {
785 ctx.next_index += 1;
786 let tag = ctx
787 .tags
788 .as_ref()
789 .map(|(levels, pre, suf)| format!("{pre}{}{suf}", levels.tag(ctx.next_tag)));
790 if tag.is_some() {
791 ctx.next_tag += 1;
792 }
793 Prepared::Element(Box::new(PreparedElement {
794 element: *e,
795 index: ctx.next_index,
796 tag,
797 theme: theme.clone(),
798 }))
799 }
800 });
801 }
802 Ok(Prepared::Grid(Box::new(PreparedGrid {
803 cells,
804 ncol,
805 nrow,
806 byrow: grid.byrow,
807 widths: grid.widths,
808 heights: grid.heights,
809 title: grid.title,
810 subtitle: grid.subtitle,
811 caption: grid.caption,
812 spacing: grid.spacing,
813 theme,
814 axis_collect: grid.axis_collect,
815 })))
816}
817
818fn prepare_plot(mut plot: GGPlot, ctx: &mut PrepCtx) -> Result<PreparedPlot, GGError> {
819 ctx.next_index += 1;
820 if let Some((levels, pre, suf)) = &ctx.tags {
821 plot.labels.tag = Some(format!("{pre}{}{suf}", levels.tag(ctx.next_tag)));
822 ctx.next_tag += 1;
823 }
824 let panel = plot
825 .labels
826 .tag
827 .clone()
828 .unwrap_or_else(|| ctx.next_index.to_string());
829
830 let original = plot.theme.legend_position.clone();
832 let collect = ctx.collect.filter(|_| {
833 matches!(
834 original,
835 LegendPosition::Right
836 | LegendPosition::Left
837 | LegendPosition::Top
838 | LegendPosition::Bottom
839 )
840 });
841 if collect.is_some() {
842 plot.theme.legend_position = LegendPosition::None;
843 }
844 let svg_formatted_values = plot.svg_formatted_values;
845 let root_attrs = plot.root_attrs.clone();
846 let (built, mut meta) = plot.build_for_render()?;
847 if let Some(pos) = collect {
848 meta.has_legend = false;
849 if let Some(l) = capture_legend(
850 &built,
851 pos,
852 ctx.page_w,
853 ctx.page_h,
854 &mut ctx.legend_warnings,
855 )
856 .map_err(GGError::Render)?
857 {
858 if !ctx.legends.iter().any(|(o, _)| o.body == l.body) {
859 let alt = match ctx.collect_alt {
860 Some(alt) => {
861 capture_legend(&built, alt, ctx.page_w, ctx.page_h, &mut Vec::new())
862 .map_err(GGError::Render)?
863 }
864 None => None,
865 };
866 ctx.legends.push((l, alt));
867 }
868 }
869 }
870 Ok(PreparedPlot {
871 built,
872 meta,
873 panel,
874 svg_formatted_values,
875 root_attrs,
876 })
877}
878
879fn capture_legend(
887 built: &crate::build::BuiltPlot,
888 pos: GridLegendPosition,
889 page_w: f64,
890 page_h: f64,
891 warnings: &mut Vec<String>,
899) -> Result<Option<Legend>, RenderError> {
900 let mut theme = built.theme.clone();
901 let m = theme.legend_margin.clone();
902 let (pa, lp, is_horizontal) = match pos {
904 GridLegendPosition::Right => (
905 Rect {
906 x: -m.left,
907 y: -m.top,
908 width: 0.0,
909 height: 0.0,
910 },
911 LegendPosition::Right,
912 false,
913 ),
914 GridLegendPosition::Bottom => (
915 Rect {
916 x: -m.left,
917 y: -(m.top + 30.0),
918 width: 0.0,
919 height: 0.0,
920 },
921 LegendPosition::Bottom,
922 true,
923 ),
924 };
925 theme.legend_position = lp;
926 let mut svg = SvgBackend::new(1, 1, pa.clone());
927 let mut meas = Measure::new(&mut svg, pa.clone());
928 let avail_width = (page_w + m.left).max(0.0);
929 let avail_height = (page_h + m.top).max(0.0);
930 let legend_plans = legend::plan_all_legends(
931 &built.scales,
932 &built.guide_legend,
933 &theme,
934 &built.suppressed_aes,
935 avail_width,
936 avail_height,
937 is_horizontal,
938 warnings,
939 );
940 legend::draw_legend_planned(
941 &built.scales,
942 &theme,
943 &pa,
944 avail_width,
951 &mut meas,
952 &built.guide_legend,
953 &built.suppressed_aes,
954 &legend_plans,
955 )?;
956 let ext = meas.extent();
957 if svg.body().is_empty() {
958 return Ok(None);
959 }
960 let (x0, y0, x1, y1) = match ext {
961 Some(e) => e,
962 None => return Ok(None),
963 };
964 Ok(Some(Legend {
965 body: svg.body().to_string(),
966 x0,
967 y0,
968 w: (x1 - x0).max(0.0),
969 h: (y1 - y0).max(0.0),
970 }))
971}
972
973fn tracks(weights: &[f64], n: usize, total: f64, gap: f64) -> Vec<(f64, f64)> {
975 let ws: Vec<f64> = (0..n)
976 .map(|i| {
977 if weights.is_empty() {
978 1.0
979 } else {
980 let w = weights[i % weights.len()];
981 if w.is_finite() && w > 0.0 {
982 w
983 } else {
984 1.0
985 }
986 }
987 })
988 .collect();
989 let sum: f64 = ws.iter().sum();
990 let avail = (total - gap * n.saturating_sub(1) as f64).max(0.0);
991 let mut pos = 0.0;
992 ws.iter()
993 .map(|w| {
994 let size = avail * w / sum;
995 let t = (pos, size);
996 pos += size + gap;
997 t
998 })
999 .collect()
1000}
1001
1002fn text_style(el: &crate::theme::elements::ElementText, anchor: TextAnchor) -> TextStyle {
1003 TextStyle {
1004 color: el.color,
1005 size: el.size,
1006 anchor,
1007 angle: 0.0,
1008 family: (!el.family.is_empty()).then(|| el.family.clone()),
1009 face: el.face,
1010 bg_colour: None,
1011 bg_r: 0.0,
1012 }
1013}
1014
1015fn hjust_x(el: &crate::theme::elements::ElementText, x0: f64, x1: f64) -> (f64, TextAnchor) {
1016 let hj = if el.hjust.is_finite() {
1017 el.hjust.clamp(0.0, 1.0)
1018 } else {
1019 0.0
1020 };
1021 let anchor = if hj <= 0.02 {
1022 TextAnchor::Start
1023 } else if hj >= 0.98 {
1024 TextAnchor::End
1025 } else {
1026 TextAnchor::Middle
1027 };
1028 (x0 + hj * (x1 - x0), anchor)
1029}
1030
1031fn render_prepared(
1032 prepared: Prepared,
1033 area: &Rect,
1034 page: &mut SvgBackend,
1035 warnings: &mut Vec<String>,
1036) -> Result<(), GGError> {
1037 match prepared {
1038 Prepared::Spacer => Ok(()),
1039 Prepared::Element(e) => {
1040 let PreparedElement {
1041 element,
1042 index,
1043 tag,
1044 theme,
1045 } = *e;
1046 let (x, y, w, h) = (area.x, area.y, area.width.max(0.0), area.height.max(0.0));
1047 let (view_box, body) = match element.content {
1048 ElementContent::Fixed { svg, width, height } => {
1049 let ok = width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0;
1050 if !ok {
1051 warnings.push(format!(
1052 "plot_grid: element cell {index} has an invalid size {width}×{height}; skipped"
1053 ));
1054 return Ok(());
1055 }
1056 (format!(" viewBox=\"0 0 {width} {height}\""), svg)
1057 }
1058 ElementContent::Fill(render) => (String::new(), render(w, h)),
1059 };
1060 page.push_raw(&format!(
1061 "<svg x=\"{x:.2}\" y=\"{y:.2}\" width=\"{w:.2}\" height=\"{h:.2}\"{view_box} data-cell=\"{index}\">{body}</svg>"
1062 ));
1063 if let Some(tag) = tag {
1065 let labels = crate::plot::Labels {
1066 tag: Some(tag),
1067 ..Default::default()
1068 };
1069 PlotRenderer::draw_cell_tag(&labels, &theme, area, page)
1070 .map_err(GGError::Render)?;
1071 }
1072 Ok(())
1073 }
1074 Prepared::Plot(p) => {
1075 let PreparedPlot {
1076 mut built,
1077 meta,
1078 panel,
1079 svg_formatted_values,
1080 root_attrs,
1081 } = *p;
1082 let (cw, ch) = (
1083 area.width.floor().max(1.0) as u32,
1084 area.height.floor().max(1.0) as u32,
1085 );
1086 let layout = GGPlot::layout_built(&mut built, &meta, cw, ch);
1087 let mut backend = SvgBackend::new(cw, ch, layout.plot_area.clone());
1088 backend.set_formatted_values(svg_formatted_values);
1089 let mut attrs = root_data_attrs(&built);
1090 attrs.push(("data-panel".into(), panel.clone()));
1091 backend.set_root_attrs(attrs);
1092 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
1093 let mut attr_warnings = Vec::new();
1100 let group_attrs = validate_root_attrs(&root_attrs, &[], "plot", &mut attr_warnings);
1101 backend.wrap_body_in_group(&group_attrs);
1102 warnings.extend(
1103 built
1104 .warnings
1105 .iter()
1106 .cloned()
1107 .chain(backend.take_warnings())
1108 .chain(attr_warnings)
1109 .map(|w| format!("panel {panel}: {w}")),
1110 );
1111 page.push_raw(&backend.finish_fragment(area.x, area.y));
1112 Ok(())
1113 }
1114 Prepared::Grid(g) => {
1115 let mut g = *g;
1116 let theme = &g.theme;
1117 let m = &theme.plot_margin;
1118 let mut top = area.y;
1120 let (x0, x1) = (area.x + m.left, area.x + area.width - m.right);
1121 if let Some(t) = &g.title {
1122 top += m.top;
1123 let (tx, anchor) = hjust_x(&theme.title, x0, x1);
1124 page.draw_text(
1125 t,
1126 (tx, top + theme.title.size * 0.8),
1127 &text_style(&theme.title, anchor),
1128 )
1129 .map_err(GGError::Render)?;
1130 top += theme.title.size * 1.6;
1131 }
1132 if let Some(s) = &g.subtitle {
1133 if g.title.is_none() {
1134 top += m.top;
1135 }
1136 let (sx, anchor) = hjust_x(&theme.subtitle, x0, x1);
1137 page.draw_text(
1138 s,
1139 (sx, top + theme.subtitle.size * 0.7),
1140 &text_style(&theme.subtitle, anchor),
1141 )
1142 .map_err(GGError::Render)?;
1143 top += theme.subtitle.size * 1.5;
1144 }
1145 let mut bottom = area.y + area.height;
1146 if let Some(c) = &g.caption {
1147 let (cx, anchor) = hjust_x(&theme.caption, x0, x1);
1148 bottom -= theme.caption.size * 1.8;
1149 page.draw_text(
1150 c,
1151 (cx, bottom + theme.caption.size * 0.9),
1152 &text_style(&theme.caption, anchor),
1153 )
1154 .map_err(GGError::Render)?;
1155 }
1156 let body_h = (bottom - top).max(1.0);
1157 let cols = tracks(&g.widths, g.ncol, area.width, g.spacing);
1158 let rows = tracks(&g.heights, g.nrow, body_h, g.spacing);
1159 if g.axis_collect != AxisCollect::Keep {
1160 align_axes(
1161 &mut g.cells,
1162 (g.ncol, g.nrow, g.byrow),
1163 &cols,
1164 &rows,
1165 g.axis_collect,
1166 warnings,
1167 );
1168 }
1169 for (k, cell) in g.cells.into_iter().enumerate() {
1170 let (r, c) = if g.byrow {
1171 (k / g.ncol, k % g.ncol)
1172 } else {
1173 (k % g.nrow, k / g.nrow)
1174 };
1175 if r >= g.nrow || c >= g.ncol {
1176 warnings.push(format!(
1178 "plot_grid: cell {} does not fit a {}×{} grid; skipped",
1179 k + 1,
1180 g.nrow,
1181 g.ncol
1182 ));
1183 continue;
1184 }
1185 let rect = Rect {
1186 x: area.x + cols[c].0,
1187 y: top + rows[r].0,
1188 width: cols[c].1,
1189 height: rows[r].1,
1190 };
1191 render_prepared(cell, &rect, page, warnings)?;
1192 }
1193 Ok(())
1194 }
1195 }
1196}
1197
1198fn align_axes(
1204 cells: &mut [Prepared],
1205 (ncol, nrow, byrow): (usize, usize, bool),
1208 cols: &[(f64, f64)],
1209 rows: &[(f64, f64)],
1210 mode: AxisCollect,
1211 warnings: &mut Vec<String>,
1212) {
1213 let idx_of = |r: usize, c: usize| -> usize {
1214 if byrow {
1215 r * ncol + c
1216 } else {
1217 c * nrow + r
1218 }
1219 };
1220 for c in 0..ncol {
1221 let cw = cols.get(c).map_or(0.0, |t| t.1);
1222 if !cw.is_finite() || cw <= 0.0 {
1223 continue;
1224 }
1225 let plot_cells: Vec<(usize, usize)> = (0..nrow)
1229 .filter_map(|r| {
1230 let k = idx_of(r, c);
1231 (k < cells.len() && matches!(cells[k], Prepared::Plot(_))).then_some((r, k))
1232 })
1233 .collect();
1234 if plot_cells.len() < 2 {
1235 continue; }
1237 let bottom_row = plot_cells.iter().map(|&(r, _)| r).max().unwrap();
1238
1239 for &(r, k) in &plot_cells {
1244 if let Prepared::Plot(p) = &mut cells[k] {
1245 p.built.theme.axis_text_x_fit = AxisLabelFit::Shift;
1246 if mode == AxisCollect::CollectX && r != bottom_row {
1247 p.built.theme.axis_text_x = ElementText::blank();
1248 p.built.theme.axis_title_x = ElementText::blank();
1249 p.built.theme.axis_ticks_x = Some(ElementLine::blank());
1250 }
1251 }
1252 }
1253
1254 let mut natural: Vec<(f64, f64, f64, f64, f64)> = Vec::with_capacity(plot_cells.len());
1263 for &(r, k) in &plot_cells {
1264 let ch = rows.get(r).map_or(0.0, |t| t.1);
1265 match &mut cells[k] {
1266 Prepared::Plot(p) => {
1267 let layout = GGPlot::layout_built(
1268 &mut p.built,
1269 &p.meta,
1270 cw.floor().max(1.0) as u32,
1271 ch.floor().max(1.0) as u32,
1272 );
1273 natural.push((
1274 layout.plot_area.x,
1275 layout.plot_area.x + layout.plot_area.width,
1276 layout.plot_area.y,
1277 layout.plot_area.height,
1278 ch,
1279 ));
1280 }
1281 _ => unreachable!("plot_cells only holds Prepared::Plot indices"),
1282 }
1283 }
1284
1285 let target_left = natural.iter().fold(f64::MIN, |m, &(l, ..)| m.max(l));
1290 let target_right_inset = natural
1291 .iter()
1292 .fold(f64::MIN, |m, &(_, r, ..)| m.max(cw - r));
1293 let width = cw - target_right_inset - target_left;
1294 if target_left.is_finite() && target_right_inset.is_finite() {
1295 for (&(_, k), &(nl, nr, ..)) in plot_cells.iter().zip(&natural) {
1296 if let Prepared::Plot(p) = &mut cells[k] {
1297 p.built.theme.plot_margin.left += (target_left - nl).max(0.0);
1298 p.built.theme.plot_margin.right += (target_right_inset - (cw - nr)).max(0.0);
1299 }
1300 }
1301 }
1302
1303 if width.is_finite() && width > 0.0 {
1314 for (&(_, k), &(_, _, y, h, ch)) in plot_cells.iter().zip(&natural) {
1315 if let Prepared::Plot(p) = &mut cells[k] {
1316 let bottom_budget = ch - p.built.theme.plot_margin.bottom;
1317 if y + h > bottom_budget + 0.5 {
1318 let fits = (ch - y - p.built.theme.plot_margin.bottom).max(8.0);
1319 p.built.theme.aspect_ratio = Some(fits / width);
1320 p.built.theme.plot_margin.top -= (h - fits) / 2.0;
1321 }
1322 }
1323 }
1324 }
1325
1326 if mode == AxisCollect::CollectX {
1327 collect_x_domain(cells, &plot_cells, warnings);
1328 }
1329 }
1330}
1331
1332fn collect_x_domain(
1341 cells: &mut [Prepared],
1342 plot_cells: &[(usize, usize)],
1343 warnings: &mut Vec<String>,
1344) {
1345 let mut domains = Vec::with_capacity(plot_cells.len());
1346 for &(_, k) in plot_cells {
1347 let d = match &cells[k] {
1348 Prepared::Plot(p) => match p.built.scales.get(&Aesthetic::X) {
1349 Some(s) if !s.is_discrete() => s.domain(),
1350 _ => None,
1351 },
1352 _ => None,
1353 };
1354 match d {
1355 Some(d) => domains.push(d),
1356 None => {
1357 warnings.push(
1358 "plot_grid: a column's x scale is discrete or untrained; x domain not \
1359 collected"
1360 .to_string(),
1361 );
1362 return;
1363 }
1364 }
1365 }
1366 let lo = domains.iter().map(|d| d.0).fold(f64::INFINITY, f64::min);
1367 let hi = domains
1368 .iter()
1369 .map(|d| d.1)
1370 .fold(f64::NEG_INFINITY, f64::max);
1371 if lo.is_finite() && hi.is_finite() && hi >= lo {
1372 for &(_, k) in plot_cells {
1373 if let Prepared::Plot(p) = &mut cells[k] {
1374 p.built.scales.set_limits(&Aesthetic::X, lo, hi);
1375 }
1376 }
1377 }
1378}
1379
1380struct Measure<'a> {
1382 inner: &'a mut SvgBackend,
1383 pa: Rect,
1384 bbox: Option<(f64, f64, f64, f64)>,
1385}
1386
1387impl<'a> Measure<'a> {
1388 fn new(inner: &'a mut SvgBackend, pa: Rect) -> Self {
1389 Measure {
1390 inner,
1391 pa,
1392 bbox: None,
1393 }
1394 }
1395
1396 fn grow(&mut self, x0: f64, y0: f64, x1: f64, y1: f64) {
1397 if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) {
1398 return;
1399 }
1400 self.bbox = Some(match self.bbox {
1401 None => (x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)),
1402 Some((a, b, c, d)) => (
1403 a.min(x0.min(x1)),
1404 b.min(y0.min(y1)),
1405 c.max(x0.max(x1)),
1406 d.max(y0.max(y1)),
1407 ),
1408 });
1409 }
1410
1411 fn extent(&self) -> Option<(f64, f64, f64, f64)> {
1412 self.bbox
1413 }
1414}
1415
1416impl DrawBackend for Measure<'_> {
1417 fn draw_circle(
1418 &mut self,
1419 c: (f64, f64),
1420 r: f64,
1421 style: &PointStyle,
1422 ) -> Result<(), RenderError> {
1423 self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
1424 self.inner.draw_circle(c, r, style)
1425 }
1426 fn draw_line(&mut self, pts: &[(f64, f64)], style: &LineStyle) -> Result<(), RenderError> {
1427 for p in pts {
1428 self.grow(p.0, p.1, p.0, p.1);
1429 }
1430 self.inner.draw_line(pts, style)
1431 }
1432 fn draw_quadratic(
1433 &mut self,
1434 p0: (f64, f64),
1435 ctrl: (f64, f64),
1436 p1: (f64, f64),
1437 style: &LineStyle,
1438 ) -> Result<(), RenderError> {
1439 self.grow(p0.0, p0.1, p0.0, p0.1);
1440 self.grow(ctrl.0, ctrl.1, ctrl.0, ctrl.1);
1441 self.grow(p1.0, p1.1, p1.0, p1.1);
1442 self.inner.draw_quadratic(p0, ctrl, p1, style)
1443 }
1444 fn draw_rect(
1445 &mut self,
1446 a: (f64, f64),
1447 b: (f64, f64),
1448 style: &RectStyle,
1449 ) -> Result<(), RenderError> {
1450 self.grow(a.0, a.1, b.0, b.1);
1451 self.inner.draw_rect(a, b, style)
1452 }
1453 fn draw_text(
1454 &mut self,
1455 text: &str,
1456 pos: (f64, f64),
1457 style: &TextStyle,
1458 ) -> Result<(), RenderError> {
1459 self.draw_text_with_title(text, pos, style, None)
1460 }
1461 fn draw_text_with_title(
1462 &mut self,
1463 text: &str,
1464 pos: (f64, f64),
1465 style: &TextStyle,
1466 title: Option<&str>,
1467 ) -> Result<(), RenderError> {
1468 let w = text.chars().count() as f64 * style.size * 0.6;
1476 let (x0, x1) = match style.anchor {
1477 TextAnchor::Start => (pos.0, pos.0 + w),
1478 TextAnchor::Middle => (pos.0 - w / 2.0, pos.0 + w / 2.0),
1479 TextAnchor::End => (pos.0 - w, pos.0),
1480 };
1481 self.grow(x0, pos.1 - style.size / 2.0, x1, pos.1 + style.size / 2.0);
1482 self.inner.draw_text_with_title(text, pos, style, title)
1483 }
1484 fn draw_polygon(&mut self, pts: &[(f64, f64)], style: &RectStyle) -> Result<(), RenderError> {
1485 for p in pts {
1486 self.grow(p.0, p.1, p.0, p.1);
1487 }
1488 self.inner.draw_polygon(pts, style)
1489 }
1490 fn draw_shape(&mut self, c: (f64, f64), r: f64, style: &PointStyle) -> Result<(), RenderError> {
1491 self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
1492 self.inner.draw_shape(c, r, style)
1493 }
1494 fn plot_area(&self) -> Rect {
1495 self.pa.clone()
1496 }
1497 fn total_area(&self) -> Rect {
1498 self.inner.total_area()
1499 }
1500 fn set_tooltip(&mut self, t: Option<String>) {
1501 self.inner.set_tooltip(t)
1502 }
1503 fn set_mark_axis(&mut self, k: Option<String>) {
1504 self.inner.set_mark_axis(k)
1505 }
1506 fn set_mark_series(&mut self, s: Option<String>) {
1507 self.inner.set_mark_series(s)
1508 }
1509 fn set_mark_value(&mut self, v: Option<String>) {
1510 self.inner.set_mark_value(v)
1511 }
1512 fn warn(&mut self, m: String) {
1513 self.inner.warn(m)
1514 }
1515 fn set_mark_geom(&mut self, geom: Option<&str>) {
1516 self.inner.set_mark_geom(geom)
1517 }
1518 fn set_mark_part(&mut self, part: Option<&str>) {
1519 self.inner.set_mark_part(part)
1520 }
1521 fn set_mark_attrs(&mut self, attrs: Vec<(String, String)>) {
1522 self.inner.set_mark_attrs(attrs)
1523 }
1524
1525 fn set_mark_class(&mut self, class: Option<String>) {
1526 self.inner.set_mark_class(class)
1527 }
1528
1529 fn set_mark_group(&mut self, group: Option<(String, String)>) {
1530 self.inner.set_mark_group(group)
1531 }
1532
1533 fn set_layer_attrs(&mut self, attrs: Vec<(String, String)>) {
1534 self.inner.set_layer_attrs(attrs)
1535 }
1536 fn wants_formatted_values(&self) -> bool {
1537 self.inner.wants_formatted_values()
1538 }
1539 fn set_mark_fvalue(&mut self, value: Option<String>) {
1540 self.inner.set_mark_fvalue(value)
1541 }
1542 fn set_mark_fx(&mut self, value: Option<String>) {
1543 self.inner.set_mark_fx(value)
1544 }
1545}
1546
1547fn join(op: Op, a: GridCell, b: GridCell) -> PlotGrid {
1550 let flatten = |c: GridCell| -> Vec<GridCell> {
1551 match c {
1552 GridCell::Grid(g) if g.op == Some(op) && g.is_plain() => g.cells,
1553 other => vec![other],
1554 }
1555 };
1556 let mut cells = flatten(a);
1557 cells.extend(flatten(b));
1558 PlotGrid {
1559 cells,
1560 op: Some(op),
1561 ..PlotGrid::default()
1562 }
1563}
1564
1565impl PlotGrid {
1566 fn is_plain(&self) -> bool {
1569 self.ncol.is_none()
1570 && self.nrow.is_none()
1571 && self.widths.is_empty()
1572 && self.heights.is_empty()
1573 && self.title.is_none()
1574 && self.subtitle.is_none()
1575 && self.caption.is_none()
1576 && self.tags.is_none()
1577 && !self.collect_legends
1578 && self.legend_bottom_share.is_none()
1579 && self.axis_collect == AxisCollect::Keep
1580 }
1581}
1582
1583macro_rules! grid_ops {
1584 ($lhs:ty, $rhs:ty) => {
1585 impl BitOr<$rhs> for $lhs {
1587 type Output = PlotGrid;
1588 fn bitor(self, rhs: $rhs) -> PlotGrid {
1589 join(Op::Row, self.into(), rhs.into())
1590 }
1591 }
1592 impl Div<$rhs> for $lhs {
1594 type Output = PlotGrid;
1595 fn div(self, rhs: $rhs) -> PlotGrid {
1596 join(Op::Col, self.into(), rhs.into())
1597 }
1598 }
1599 };
1600}
1601
1602grid_ops!(GGPlot, GGPlot);
1603grid_ops!(GGPlot, PlotGrid);
1604grid_ops!(PlotGrid, GGPlot);
1605grid_ops!(PlotGrid, PlotGrid);
1606grid_ops!(GGPlot, GridElement);
1607grid_ops!(GridElement, GGPlot);
1608grid_ops!(PlotGrid, GridElement);
1609grid_ops!(GridElement, PlotGrid);
1610
1611#[cfg(test)]
1612mod tests {
1613 use super::*;
1614
1615 #[test]
1616 fn tag_sequences() {
1617 let l: Vec<String> = (0..28).map(|i| TagLevels::Lower.tag(i)).collect();
1618 assert_eq!(&l[..3], &["a", "b", "c"]);
1619 assert_eq!(l[25], "z");
1620 assert_eq!(l[26], "aa");
1621 assert_eq!(l[27], "ab");
1622 assert_eq!(TagLevels::Upper.tag(1), "B");
1623 assert_eq!(TagLevels::Numeric.tag(9), "10");
1624 assert_eq!(TagLevels::LowerRoman.tag(3), "iv");
1625 assert_eq!(TagLevels::UpperRoman.tag(13), "XIV");
1626 assert_eq!(TagLevels::Custom(vec!["x".into()]).tag(1), "2");
1627 }
1628
1629 #[test]
1630 fn tracks_are_relative_and_robust() {
1631 let t = tracks(&[2.0, 1.0], 2, 300.0, 0.0);
1632 assert_eq!(t, vec![(0.0, 200.0), (200.0, 100.0)]);
1633 let t = tracks(&[f64::NAN, -1.0], 2, 100.0, 10.0);
1634 assert_eq!(t, vec![(0.0, 45.0), (55.0, 45.0)]);
1635 let t = tracks(&[], 3, 30.0, 100.0);
1636 assert!(t.iter().all(|(p, s)| p.is_finite() && *s == 0.0));
1637 }
1638
1639 #[test]
1643 fn measure_forwards_draw_quadratic_and_mark_metadata_and_grows_its_extent() {
1644 let pa = Rect {
1645 x: 0.0,
1646 y: 0.0,
1647 width: 100.0,
1648 height: 100.0,
1649 };
1650 let mut backend = SvgBackend::new(100, 100, pa.clone());
1651 backend.set_formatted_values(true);
1652 let mut meas = Measure::new(&mut backend, pa);
1653
1654 assert!(meas.extent().is_none());
1655 assert!(meas.wants_formatted_values());
1657 meas.set_mark_geom(Some("line"));
1658 meas.set_mark_part(Some("arrow"));
1659 meas.set_mark_attrs(vec![("data-x".to_string(), "v".to_string())]);
1660 meas.set_mark_fvalue(Some("1,234.5".to_string()));
1661 meas.set_mark_fx(Some("2026-10-12".to_string()));
1662 meas.draw_quadratic(
1663 (10.0, 20.0),
1664 (90.0, 5.0),
1665 (50.0, 80.0),
1666 &LineStyle::default(),
1667 )
1668 .unwrap();
1669 meas.set_mark_geom(None);
1670 meas.set_mark_part(None);
1671 meas.set_mark_attrs(Vec::new());
1672 meas.set_mark_fvalue(None);
1673 meas.set_mark_fx(None);
1674
1675 let (x0, y0, x1, y1) = meas.extent().expect("extent after drawing");
1676 assert_eq!((x0, y0, x1, y1), (10.0, 5.0, 90.0, 80.0));
1677
1678 let svg = backend.finish();
1682 assert!(svg.contains("data-part=\"arrow\""));
1683 assert!(svg.contains("data-x=\"v\""));
1684 assert!(svg.contains("gg-arrow"));
1685 assert!(svg.contains("data-fvalue=\"1,234.5\""));
1686 assert!(svg.contains("data-fx=\"2026-10-12\""));
1687 }
1688
1689 #[test]
1700 fn measure_forwards_the_title_to_its_inner_backend() {
1701 let pa = Rect {
1702 x: 0.0,
1703 y: 0.0,
1704 width: 100.0,
1705 height: 100.0,
1706 };
1707 let mut backend = SvgBackend::new(100, 100, pa.clone());
1708 let mut meas = Measure::new(&mut backend, pa);
1709 meas.draw_text_with_title(
1710 "Grp…",
1711 (10.0, 20.0),
1712 &TextStyle {
1713 size: 12.0,
1714 anchor: TextAnchor::Start,
1715 ..Default::default()
1716 },
1717 Some("Group 01"),
1718 )
1719 .unwrap();
1720 let svg = backend.finish();
1721 assert!(
1722 svg.contains("<title>Group 01</title>"),
1723 "the full label should reach the inner backend's <title>: {svg}"
1724 );
1725 }
1726}