Skip to main content

ggplot_rs/
compose.rs

1//! Plot composition for the native SVG path — a patchwork-style [`PlotGrid`].
2//!
3//! ```
4//! use ggplot_rs::prelude::*;
5//! use ggplot_rs::data::Value;
6//! let data = || vec![
7//!     ("x".to_string(), (0..10).map(|i| Value::Float(i as f64)).collect::<Vec<_>>()),
8//!     ("y".to_string(), (0..10).map(|i| Value::Float((i * i) as f64)).collect::<Vec<_>>()),
9//! ];
10//! let p = || GGPlot::new(data()).aes(Aes::new().x("x").y("y"));
11//! // a | b puts plots side by side, a / b stacks them; `/` binds tighter.
12//! let svg = ((p().geom_point() | p().geom_line()) / p().geom_col())
13//!     .title("Diagnostics")
14//!     .tag_levels(TagLevels::Lower)
15//!     .render_svg_native_with_size(900, 700)
16//!     .unwrap();
17//! assert!(svg.contains("data-panel=\"a\"") && svg.contains("data-panel=\"c\""));
18//! ```
19//!
20//! Every sub-plot is rendered as a positioned nested `<svg>` fragment (see
21//! [`GGPlot::render_svg_native_at`]) that keeps all of its host attributes
22//! (`data-plot`, `data-domain`, marks' `data-x`/`data-series`/`data-value`)
23//! and additionally carries `data-panel="<tag or index>"`. A host maps a
24//! pointer to data coordinates by first finding the enclosing sub-`<svg>`.
25
26use 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/// Panel-tag sequence (patchwork's `tag_levels`).
39#[derive(Clone, Debug, PartialEq)]
40pub enum TagLevels {
41    /// `a`, `b`, … `z`, `aa`, …
42    Lower,
43    /// `A`, `B`, …
44    Upper,
45    /// `1`, `2`, …
46    Numeric,
47    /// `i`, `ii`, `iii`, …
48    LowerRoman,
49    /// `I`, `II`, …
50    UpperRoman,
51    /// Explicit tags; panels beyond the list are numbered.
52    Custom(Vec<String>),
53}
54
55impl TagLevels {
56    /// The tag of the `i`-th (0-based) panel.
57    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    // Bijective base-26: a..z, aa..az, ba..
71    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/// Where a [`PlotGrid`] puts its collected legends.
113#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
114pub enum GridLegendPosition {
115    /// A column to the right of the grid (default).
116    #[default]
117    Right,
118    /// A row below the grid.
119    Bottom,
120}
121
122/// How a grid was built by the `|` / `/` operators, so chains flatten
123/// (`a | b | c` is one row) while mixed operators nest.
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125enum Op {
126    Row,
127    Col,
128}
129
130/// One grid cell.
131pub enum GridCell {
132    Plot(Box<GGPlot>),
133    Grid(Box<PlotGrid>),
134    /// An empty cell (patchwork's `plot_spacer()`).
135    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
150/// A patchwork-style arrangement of plots rendered into **one** SVG on the
151/// plotters-free native path.
152///
153/// - cells fill row-major (or column-major with [`byrow(false)`](Self::byrow))
154///   across [`ncol`](Self::ncol) / [`nrow`](Self::nrow) (default: a near-square
155///   grid; `a | b` is one row, `a / b` one column);
156/// - [`widths`](Self::widths) / [`heights`](Self::heights) set relative
157///   column widths / row heights;
158/// - [`title`](Self::title) / [`subtitle`](Self::subtitle) /
159///   [`caption`](Self::caption) annotate the whole grid;
160/// - [`tag_levels`](Self::tag_levels) tags panels `a, b, …` (`A`, `1`, roman,
161///   custom) in reading order, through nested grids;
162/// - [`collect_legends`](Self::collect_legends) removes the sub-plots'
163///   legends and draws each distinct legend once beside the grid (identical
164///   legends are de-duplicated).
165///
166/// Nested grids keep their own layout and annotations; tagging and legend
167/// collection are controlled by the outermost grid.
168pub 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    /// Extra root `<svg>` attributes requested via [`PlotGrid::svg_attr`]/
187    /// [`PlotGrid::svg_attrs`], validated and applied at render time.
188    root_attrs: Vec<(String, String)>,
189    /// Whether to emit a `data-warnings` JSON array of the panels'
190    /// combined build warnings on the root `<svg>`
191    /// ([`PlotGrid::svg_warnings_attr`]). Default off; byte-identical
192    /// output when off.
193    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
222/// Upper bound on grid columns/rows — a guard against absurd user input.
223const MAX_TRACKS: usize = 10_000;
224
225impl PlotGrid {
226    pub fn new() -> Self {
227        Self::default()
228    }
229
230    /// Append a plot (or a nested grid) as the next cell.
231    #[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    /// Append several plots.
238    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    /// Append an empty cell (patchwork's `plot_spacer()`).
244    pub fn add_spacer(mut self) -> Self {
245        self.cells.push(GridCell::Spacer);
246        self
247    }
248
249    /// Number of columns.
250    pub fn ncol(mut self, n: usize) -> Self {
251        self.ncol = (n > 0).then_some(n.min(MAX_TRACKS));
252        self
253    }
254
255    /// Number of rows.
256    pub fn nrow(mut self, n: usize) -> Self {
257        self.nrow = (n > 0).then_some(n.min(MAX_TRACKS));
258        self
259    }
260
261    /// Fill cells row by row (default) or column by column.
262    pub fn byrow(mut self, byrow: bool) -> Self {
263        self.byrow = byrow;
264        self
265    }
266
267    /// Relative column widths (recycled; non-positive / non-finite = 1).
268    pub fn widths(mut self, widths: &[f64]) -> Self {
269        self.widths = widths.to_vec();
270        self
271    }
272
273    /// Relative row heights (recycled; non-positive / non-finite = 1).
274    pub fn heights(mut self, heights: &[f64]) -> Self {
275        self.heights = heights.to_vec();
276        self
277    }
278
279    /// Title over the whole grid.
280    pub fn title(mut self, title: &str) -> Self {
281        self.title = Some(title.to_string());
282        self
283    }
284
285    /// Subtitle over the whole grid.
286    pub fn subtitle(mut self, subtitle: &str) -> Self {
287        self.subtitle = Some(subtitle.to_string());
288        self
289    }
290
291    /// Caption under the whole grid.
292    pub fn caption(mut self, caption: &str) -> Self {
293        self.caption = Some(caption.to_string());
294        self
295    }
296
297    /// Tag the panels (`labs(tag)` of each sub-plot is replaced).
298    pub fn tag_levels(mut self, levels: TagLevels) -> Self {
299        self.tags = Some(levels);
300        self
301    }
302
303    /// Text around each tag, e.g. `("(", ")")` for `(a)`.
304    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    /// Collect the sub-plots' legends into one strip (identical legends are
311    /// drawn once). Sub-plots with an inside or hidden legend keep it.
312    pub fn collect_legends(mut self, collect: bool) -> Self {
313        self.collect_legends = collect;
314        self
315    }
316
317    /// Where collected legends go.
318    pub fn legend_position(mut self, pos: GridLegendPosition) -> Self {
319        self.legend_position = pos;
320        self
321    }
322
323    /// Gap between cells, in px (default 0).
324    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    /// Theme for the grid's own title/subtitle/caption and the collected
330    /// legends' text.
331    pub fn theme(mut self, theme: Theme) -> Self {
332        self.theme = theme;
333        self
334    }
335
336    /// Add one extra attribute to the root `<svg>` element — see
337    /// [`GGPlot::svg_attr`](crate::plot::GGPlot::svg_attr), same allow-list
338    /// (`data-*`, `aria-*`, `role`, `id`, `class`, `lang`) and the same
339    /// "ignored with a warning" rule for anything else or a collision with
340    /// what ggplot-rs already writes (`data-grid`, or `data-warnings` when
341    /// [`svg_warnings_attr`](Self::svg_warnings_attr) is also on).
342    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    /// [`svg_attr`](Self::svg_attr) for several attributes at once.
348    pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
349        self.root_attrs.extend(attrs);
350        self
351    }
352
353    /// Emit a `data-warnings` attribute on the root `<svg>` — a JSON array
354    /// of every panel's combined build warnings, `[]` when there are none.
355    /// Default off, and omitted entirely when off.
356    pub fn svg_warnings_attr(mut self, on: bool) -> Self {
357        self.svg_warnings_attr = on;
358        self
359    }
360
361    /// Number of cells (plots, nested grids and spacers).
362    pub fn len(&self) -> usize {
363        self.cells.len()
364    }
365
366    /// Whether the grid has no cells.
367    pub fn is_empty(&self) -> bool {
368        self.cells.is_empty()
369    }
370
371    /// Render at 800×600.
372    pub fn render_svg_native(self) -> Result<String, GGError> {
373        self.render_svg_native_with_size(800, 600)
374    }
375
376    /// Render the grid to one standalone SVG document of `w`×`h` px. The root
377    /// carries `data-grid="<rows> <cols>"` (and no `data-plot`: each sub-`<svg>`
378    /// has its own).
379    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    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
384    /// also returning every sub-plot's warnings, prefixed `panel <tag>: `.
385    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    /// Render as a nested `<svg>` fragment positioned at `(x, y)` — for
395    /// composing the grid into a larger SVG (cf. [`GGPlot::render_svg_native_at`]).
396    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        // Phase 1 (size-independent): build every plot, assign tags and
410        // capture legends to collect.
411        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        // Phase 2: page layout.
427        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        // Phase 3: render cells into their rects.
490        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
514/// A collected legend: rendered markup (also its identity) and extent.
515struct 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    /// The grid's overall page size (sipemu/ggplot-rs#155): a collected
540    /// legend's available width/height for its own B3-2 wrap/grid plan,
541    /// since a `PlotGrid`'s legend strip has no other natural bound —
542    /// it's sized by whatever the legend needs, so the legend instead
543    /// wraps to fit within the page itself.
544    page_w: f64,
545    page_h: f64,
546}
547
548/// A built sub-plot awaiting its cell size.
549struct PreparedPlot {
550    built: crate::build::BuiltPlot,
551    meta: RenderMeta,
552    panel: String,
553    /// The cell's own `GGPlot::svg_formatted_values` setting (review
554    /// PR#141 finding 6, LOW): `build_for_render` consumes the `GGPlot`
555    /// and discards this field (it only matters at render time, and
556    /// `PlotGrid` builds its cells independently of
557    /// `GGPlot::render_native`, the only place that previously read it),
558    /// so it has to be captured here and carried to the cell's own
559    /// backend in `render_prepared`.
560    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            // Grow rows if the cells don't fit.
597            (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    // Collect an outside legend: suppress it in the plot, draw it separately.
646    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
679/// Draw a built plot's legend in isolation, measuring its extent.
680///
681/// `page_w`/`page_h` are the grid's overall page size (sipemu/
682/// ggplot-rs#155): a collected legend has no natural width/height bound
683/// of its own — the strip that holds it is sized by whatever the legend
684/// needs — so a discrete guide wraps/grids here against the page itself,
685/// the same way a single plot's legend wraps against its own canvas.
686fn 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    // Fake a zero-size panel so the legend's origin lands at (0, 0).
695    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        // Review #167 finding 1: step by the same `avail_width` share
738        // `plan_all_legends` just planned against, not `pa.width` (always
739        // 0.0 — `pa` is a fake zero-size panel so the legend's origin
740        // lands at (0, 0)). Using `pa.width` made every discrete guide
741        // after the first advance by zero, so two collected guides (e.g.
742        // `colour` and `shape`) were drawn on top of each other.
743        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
766/// Normalised track sizes: `n` relative weights (recycled, invalid → 1).
767fn 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            // Header / footer bands.
864            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                    // More cells than nrow × ncol: the rest do not fit.
912                    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
933/// A backend wrapper that records the bounding box of everything drawn.
934struct 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
1072// ─── Operator sugar ─────────────────────────────────────────────────
1073
1074fn 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    /// Built purely by an operator chain (no explicit layout/annotations), so
1092    /// it can be flattened into a longer chain of the same operator.
1093    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        /// `a | b`: place side by side (patchwork).
1109        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        /// `a / b`: stack vertically (patchwork).
1116        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    /// `Measure` (the legend bbox pre-pass) forwards every `DrawBackend`
1159    /// method to its inner backend and grows its tracked extent to include
1160    /// a quadratic curve's control points — not just straight lines/shapes.
1161    #[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        // B2-4: Measure forwards the formatted-values query/setters too.
1175        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        // The marks actually reached the inner SvgBackend (data-part, the
1198        // data_attr, the mark class and the formatted values all appear in
1199        // its output).
1200        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}