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::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/// Panel-tag sequence (patchwork's `tag_levels`).
41#[derive(Clone, Debug, PartialEq)]
42pub enum TagLevels {
43    /// `a`, `b`, … `z`, `aa`, …
44    Lower,
45    /// `A`, `B`, …
46    Upper,
47    /// `1`, `2`, …
48    Numeric,
49    /// `i`, `ii`, `iii`, …
50    LowerRoman,
51    /// `I`, `II`, …
52    UpperRoman,
53    /// Explicit tags; panels beyond the list are numbered.
54    Custom(Vec<String>),
55}
56
57impl TagLevels {
58    /// The tag of the `i`-th (0-based) panel.
59    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    // Bijective base-26: a..z, aa..az, ba..
73    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/// How a [`PlotGrid`] aligns its own direct cells' plot areas and x scale
115/// within each column (patchwork's `plot_layout(axes = ...)`, applied to
116/// the x axis and plot-area alignment specifically — sipemu/
117/// ggplot-rs#175, tracked from DataZooDE/anofox-visualization#318). Only a
118/// column of [`GridCell::Plot`] cells participates; a [`GridCell::Spacer`]
119/// or a nested [`PlotGrid`] cell keeps its own layout, and a column with
120/// fewer than two plot cells is a no-op. Set via [`PlotGrid::axis_collect`].
121#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
122pub enum AxisCollect {
123    /// Each cell keeps its own margins, x axis and x domain (default).
124    #[default]
125    Keep,
126    /// Equal left/right plot-area insets within each column, from the
127    /// widest y-axis label requirement in that column — the same idea as
128    /// anofox-visualization's `track.rs` `left = max(...)` fallback, done
129    /// here as one layout pass (`GGPlot::layout_built`'s own arithmetic)
130    /// rather than a render-measure-render loop. Every cell in the column
131    /// also switches to [`AxisLabelFit::Shift`](crate::theme::AxisLabelFit::Shift)
132    /// so an overflowing outer tick label can never perturb the alignment.
133    /// A cell set thinner than the plotting engine's 50px panel-height
134    /// floor via [`PlotGrid::heights`](Self::heights) (an
135    /// anofox-visualization `::TRACK` strip, typically 16-30px) gets a
136    /// centred `aspect_ratio` instead, so its panel comes out exactly as
137    /// tall as the cell rather than overflowing it — `track.rs`'s own
138    /// `Fit::correct` `aspect` trick, computed from the same layout pass.
139    /// Domains and axis text are otherwise untouched.
140    Align,
141    /// [`Align`](Self::Align), plus one x domain shared across the column
142    /// — the union of every cell's own trained x domain — with x-axis
143    /// ticks/title/labels drawn only on the bottom cell. Skipped (with a
144    /// warning), for a column whose x scale is discrete or untrained on
145    /// any cell, in which case the column still gets [`Align`](Self::Align)'s
146    /// plot-area alignment.
147    CollectX,
148}
149
150/// Where a [`PlotGrid`] puts its collected legends.
151#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
152pub enum GridLegendPosition {
153    /// A column to the right of the grid (default).
154    #[default]
155    Right,
156    /// A row below the grid.
157    Bottom,
158}
159
160/// How a grid was built by the `|` / `/` operators, so chains flatten
161/// (`a | b | c` is one row) while mixed operators nest.
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163enum Op {
164    Row,
165    Col,
166}
167
168/// One grid cell.
169pub enum GridCell {
170    Plot(Box<GGPlot>),
171    Grid(Box<PlotGrid>),
172    /// An empty cell (patchwork's `plot_spacer()`).
173    Spacer,
174}
175
176impl From<GGPlot> for GridCell {
177    fn from(p: GGPlot) -> Self {
178        GridCell::Plot(Box::new(p))
179    }
180}
181
182impl From<PlotGrid> for GridCell {
183    fn from(g: PlotGrid) -> Self {
184        GridCell::Grid(Box::new(g))
185    }
186}
187
188/// A patchwork-style arrangement of plots rendered into **one** SVG on the
189/// plotters-free native path.
190///
191/// - cells fill row-major (or column-major with [`byrow(false)`](Self::byrow))
192///   across [`ncol`](Self::ncol) / [`nrow`](Self::nrow) (default: a near-square
193///   grid; `a | b` is one row, `a / b` one column);
194/// - [`widths`](Self::widths) / [`heights`](Self::heights) set relative
195///   column widths / row heights;
196/// - [`title`](Self::title) / [`subtitle`](Self::subtitle) /
197///   [`caption`](Self::caption) annotate the whole grid;
198/// - [`tag_levels`](Self::tag_levels) tags panels `a, b, …` (`A`, `1`, roman,
199///   custom) in reading order, through nested grids;
200/// - [`collect_legends`](Self::collect_legends) removes the sub-plots'
201///   legends and draws each distinct legend once beside the grid (identical
202///   legends are de-duplicated).
203///
204/// Nested grids keep their own layout and annotations; tagging and legend
205/// collection are controlled by the outermost grid.
206pub struct PlotGrid {
207    cells: Vec<GridCell>,
208    ncol: Option<usize>,
209    nrow: Option<usize>,
210    byrow: bool,
211    widths: Vec<f64>,
212    heights: Vec<f64>,
213    title: Option<String>,
214    subtitle: Option<String>,
215    caption: Option<String>,
216    tags: Option<TagLevels>,
217    tag_prefix: String,
218    tag_suffix: String,
219    collect_legends: bool,
220    legend_position: GridLegendPosition,
221    spacing: f64,
222    theme: Theme,
223    axis_collect: AxisCollect,
224    op: Option<Op>,
225    /// Extra root `<svg>` attributes requested via [`PlotGrid::svg_attr`]/
226    /// [`PlotGrid::svg_attrs`], validated and applied at render time.
227    root_attrs: Vec<(String, String)>,
228    /// Whether to emit a `data-warnings` JSON array of the panels'
229    /// combined build warnings on the root `<svg>`
230    /// ([`PlotGrid::svg_warnings_attr`]). Default off; byte-identical
231    /// output when off.
232    svg_warnings_attr: bool,
233}
234
235impl Default for PlotGrid {
236    fn default() -> Self {
237        PlotGrid {
238            cells: Vec::new(),
239            ncol: None,
240            nrow: None,
241            byrow: true,
242            widths: Vec::new(),
243            heights: Vec::new(),
244            title: None,
245            subtitle: None,
246            caption: None,
247            tags: None,
248            tag_prefix: String::new(),
249            tag_suffix: String::new(),
250            collect_legends: false,
251            legend_position: GridLegendPosition::Right,
252            spacing: 0.0,
253            theme: Theme::default(),
254            axis_collect: AxisCollect::Keep,
255            op: None,
256            root_attrs: Vec::new(),
257            svg_warnings_attr: false,
258        }
259    }
260}
261
262/// Upper bound on grid columns/rows — a guard against absurd user input.
263const MAX_TRACKS: usize = 10_000;
264
265impl PlotGrid {
266    pub fn new() -> Self {
267        Self::default()
268    }
269
270    /// Append a plot (or a nested grid) as the next cell.
271    #[allow(clippy::should_implement_trait)]
272    pub fn add(mut self, cell: impl Into<GridCell>) -> Self {
273        self.cells.push(cell.into());
274        self
275    }
276
277    /// Append several plots.
278    pub fn add_all(mut self, plots: impl IntoIterator<Item = GGPlot>) -> Self {
279        self.cells.extend(plots.into_iter().map(GridCell::from));
280        self
281    }
282
283    /// Append an empty cell (patchwork's `plot_spacer()`).
284    pub fn add_spacer(mut self) -> Self {
285        self.cells.push(GridCell::Spacer);
286        self
287    }
288
289    /// Number of columns.
290    pub fn ncol(mut self, n: usize) -> Self {
291        self.ncol = (n > 0).then_some(n.min(MAX_TRACKS));
292        self
293    }
294
295    /// Number of rows.
296    pub fn nrow(mut self, n: usize) -> Self {
297        self.nrow = (n > 0).then_some(n.min(MAX_TRACKS));
298        self
299    }
300
301    /// Fill cells row by row (default) or column by column.
302    pub fn byrow(mut self, byrow: bool) -> Self {
303        self.byrow = byrow;
304        self
305    }
306
307    /// Relative column widths (recycled; non-positive / non-finite = 1).
308    pub fn widths(mut self, widths: &[f64]) -> Self {
309        self.widths = widths.to_vec();
310        self
311    }
312
313    /// Relative row heights (recycled; non-positive / non-finite = 1).
314    pub fn heights(mut self, heights: &[f64]) -> Self {
315        self.heights = heights.to_vec();
316        self
317    }
318
319    /// Title over the whole grid.
320    pub fn title(mut self, title: &str) -> Self {
321        self.title = Some(title.to_string());
322        self
323    }
324
325    /// Subtitle over the whole grid.
326    pub fn subtitle(mut self, subtitle: &str) -> Self {
327        self.subtitle = Some(subtitle.to_string());
328        self
329    }
330
331    /// Caption under the whole grid.
332    pub fn caption(mut self, caption: &str) -> Self {
333        self.caption = Some(caption.to_string());
334        self
335    }
336
337    /// Tag the panels (`labs(tag)` of each sub-plot is replaced).
338    pub fn tag_levels(mut self, levels: TagLevels) -> Self {
339        self.tags = Some(levels);
340        self
341    }
342
343    /// Text around each tag, e.g. `("(", ")")` for `(a)`.
344    pub fn tag_affixes(mut self, prefix: &str, suffix: &str) -> Self {
345        self.tag_prefix = prefix.to_string();
346        self.tag_suffix = suffix.to_string();
347        self
348    }
349
350    /// Collect the sub-plots' legends into one strip (identical legends are
351    /// drawn once). Sub-plots with an inside or hidden legend keep it.
352    pub fn collect_legends(mut self, collect: bool) -> Self {
353        self.collect_legends = collect;
354        self
355    }
356
357    /// Where collected legends go.
358    pub fn legend_position(mut self, pos: GridLegendPosition) -> Self {
359        self.legend_position = pos;
360        self
361    }
362
363    /// Align this grid's own direct cells' plot areas and/or x scale,
364    /// one column at a time — see [`AxisCollect`] (sipemu/ggplot-rs#175).
365    /// Default [`AxisCollect::Keep`] (no change, byte-identical output).
366    pub fn axis_collect(mut self, mode: AxisCollect) -> Self {
367        self.axis_collect = mode;
368        self
369    }
370
371    /// Gap between cells, in px (default 0).
372    pub fn spacing(mut self, px: f64) -> Self {
373        self.spacing = if px.is_finite() { px.max(0.0) } else { 0.0 };
374        self
375    }
376
377    /// Theme for the grid's own title/subtitle/caption and the collected
378    /// legends' text.
379    pub fn theme(mut self, theme: Theme) -> Self {
380        self.theme = theme;
381        self
382    }
383
384    /// Add one extra attribute to the root `<svg>` element — see
385    /// [`GGPlot::svg_attr`](crate::plot::GGPlot::svg_attr), same allow-list
386    /// (`data-*`, `aria-*`, `role`, `id`, `class`, `lang`) and the same
387    /// "ignored with a warning" rule for anything else or a collision with
388    /// what ggplot-rs already writes (`data-grid`, or `data-warnings` when
389    /// [`svg_warnings_attr`](Self::svg_warnings_attr) is also on).
390    pub fn svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
391        self.root_attrs.push((name.into(), value.into()));
392        self
393    }
394
395    /// [`svg_attr`](Self::svg_attr) for several attributes at once.
396    pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
397        self.root_attrs.extend(attrs);
398        self
399    }
400
401    /// Emit a `data-warnings` attribute on the root `<svg>` — a JSON array
402    /// of every panel's combined build warnings, `[]` when there are none.
403    /// Default off, and omitted entirely when off.
404    pub fn svg_warnings_attr(mut self, on: bool) -> Self {
405        self.svg_warnings_attr = on;
406        self
407    }
408
409    /// Number of cells (plots, nested grids and spacers).
410    pub fn len(&self) -> usize {
411        self.cells.len()
412    }
413
414    /// Whether the grid has no cells.
415    pub fn is_empty(&self) -> bool {
416        self.cells.is_empty()
417    }
418
419    /// Render at 800×600.
420    pub fn render_svg_native(self) -> Result<String, GGError> {
421        self.render_svg_native_with_size(800, 600)
422    }
423
424    /// Render the grid to one standalone SVG document of `w`×`h` px. The root
425    /// carries `data-grid="<rows> <cols>"` (and no `data-plot`: each sub-`<svg>`
426    /// has its own).
427    pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
428        Ok(self.render_page(w, h)?.0.finish())
429    }
430
431    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
432    /// also returning every sub-plot's warnings, prefixed `panel <tag>: `.
433    pub fn render_svg_native_with_warnings(
434        self,
435        w: u32,
436        h: u32,
437    ) -> Result<(String, Vec<String>), GGError> {
438        let (page, warnings) = self.render_page(w, h)?;
439        Ok((page.finish(), warnings))
440    }
441
442    /// Render as a nested `<svg>` fragment positioned at `(x, y)` — for
443    /// composing the grid into a larger SVG (cf. [`GGPlot::render_svg_native_at`]).
444    pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
445        Ok(self.render_page(w, h)?.0.finish_fragment(x, y))
446    }
447
448    fn render_page(self, w: u32, h: u32) -> Result<(SvgBackend, Vec<String>), GGError> {
449        let (w, h) = (w.max(1), h.max(1));
450        let mut theme = self.theme.clone();
451        theme.resolve_inheritance();
452        let collect = self.collect_legends;
453        let legend_pos = self.legend_position;
454        let root_attrs = self.root_attrs.clone();
455        let svg_warnings_attr = self.svg_warnings_attr;
456
457        // Phase 1 (size-independent): build every plot, assign tags and
458        // capture legends to collect.
459        let mut ctx = PrepCtx {
460            tags: self
461                .tags
462                .clone()
463                .map(|t| (t, self.tag_prefix.clone(), self.tag_suffix.clone())),
464            next_tag: 0,
465            next_index: 0,
466            collect: collect.then_some(legend_pos),
467            legends: Vec::new(),
468            page_w: w as f64,
469            page_h: h as f64,
470            legend_warnings: Vec::new(),
471        };
472        let prepared = prepare_grid(self, &mut ctx)?;
473        let legends = ctx.legends;
474        let legend_warnings = ctx.legend_warnings;
475
476        // Phase 2: page layout.
477        let full = Rect {
478            x: 0.0,
479            y: 0.0,
480            width: w as f64,
481            height: h as f64,
482        };
483        let mut page = SvgBackend::new(w, h, full.clone());
484        page.without_plot_attr();
485        let (rows, cols) = prepared.dims();
486        let data_grid_attr = ("data-grid".to_string(), format!("{rows} {cols}"));
487        page.set_root_attrs(vec![data_grid_attr.clone()]);
488        if let Some(fill) = theme
489            .plot_background
490            .fill
491            .filter(|_| theme.plot_background.visible)
492        {
493            page.draw_rect(
494                (0.0, 0.0),
495                (w as f64, h as f64),
496                &RectStyle {
497                    fill: Some(fill),
498                    stroke: None,
499                    stroke_width: 0.0,
500                    alpha: 1.0,
501                    clip: false,
502                    corner_radius: 0.0,
503                },
504            )
505            .map_err(GGError::Render)?;
506        }
507
508        let mut body = full;
509        if !legends.is_empty() {
510            let gap = theme.legend_spacing.max(0.0) * 2.0;
511            let pad = 8.0;
512            match legend_pos {
513                GridLegendPosition::Right => {
514                    let strip_w = legends.iter().map(|l| l.w).fold(0.0, f64::max) + 2.0 * pad;
515                    let strip_w = strip_w.min(body.width * 0.4);
516                    body.width -= strip_w;
517                    let total_h =
518                        legends.iter().map(|l| l.h).sum::<f64>() + gap * (legends.len() - 1) as f64;
519                    let mut y = (body.y + (body.height - total_h) / 2.0).max(body.y + pad);
520                    for l in &legends {
521                        place_legend(&mut page, l, body.x + body.width + pad, y);
522                        y += l.h + gap;
523                    }
524                }
525                GridLegendPosition::Bottom => {
526                    let strip_h = legends.iter().map(|l| l.h).fold(0.0, f64::max) + 2.0 * pad;
527                    let strip_h = strip_h.min(body.height * 0.4);
528                    body.height -= strip_h;
529                    let total_w =
530                        legends.iter().map(|l| l.w).sum::<f64>() + gap * (legends.len() - 1) as f64;
531                    let mut x = (body.x + (body.width - total_w) / 2.0).max(body.x + pad);
532                    for l in &legends {
533                        place_legend(&mut page, l, x, body.y + body.height + pad);
534                        x += l.w + gap;
535                    }
536                }
537            }
538        }
539
540        // Phase 3: render cells into their rects.
541        let mut warnings = legend_warnings;
542        render_prepared(prepared, &body, &mut page, &mut warnings)?;
543
544        let mut reserved = vec![data_grid_attr];
545        if svg_warnings_attr {
546            reserved.push(("data-warnings".to_string(), String::new()));
547        }
548        let extra = crate::render::svg_backend::validate_root_attrs(
549            &root_attrs,
550            &reserved,
551            "grid",
552            &mut warnings,
553        );
554        page.extend_root_attrs(extra);
555        if svg_warnings_attr {
556            page.extend_root_attrs(vec![(
557                "data-warnings".to_string(),
558                crate::render::svg_backend::warnings_json(&warnings),
559            )]);
560        }
561        Ok((page, warnings))
562    }
563}
564
565/// A collected legend: rendered markup (also its identity) and extent.
566struct Legend {
567    body: String,
568    x0: f64,
569    y0: f64,
570    w: f64,
571    h: f64,
572}
573
574fn place_legend(page: &mut SvgBackend, l: &Legend, x: f64, y: f64) {
575    let (tx, ty) = (x - l.x0, y - l.y0);
576    if tx.is_finite() && ty.is_finite() {
577        page.push_raw(&format!(
578            "<g class=\"legend\" transform=\"translate({tx:.2} {ty:.2})\">{}</g>",
579            l.body
580        ));
581    }
582}
583
584struct PrepCtx {
585    tags: Option<(TagLevels, String, String)>,
586    next_tag: usize,
587    next_index: usize,
588    collect: Option<GridLegendPosition>,
589    legends: Vec<Legend>,
590    /// The grid's overall page size (sipemu/ggplot-rs#155): a collected
591    /// legend's available width/height for its own B3-2 wrap/grid plan,
592    /// since a `PlotGrid`'s legend strip has no other natural bound —
593    /// it's sized by whatever the legend needs, so the legend instead
594    /// wraps to fit within the page itself.
595    page_w: f64,
596    page_h: f64,
597    /// Warnings `capture_legend`'s `plan_all_legends` call produces for a
598    /// collected legend (#170 / review #167 finding 6) — previously
599    /// discarded; merged into `render_page`'s own `warnings` so they
600    /// reach `render_svg_native_with_warnings` / `data-warnings` like
601    /// every other warning.
602    legend_warnings: Vec<String>,
603}
604
605/// A built sub-plot awaiting its cell size.
606struct PreparedPlot {
607    built: crate::build::BuiltPlot,
608    meta: RenderMeta,
609    panel: String,
610    /// The cell's own `GGPlot::svg_formatted_values` setting (review
611    /// PR#141 finding 6, LOW): `build_for_render` consumes the `GGPlot`
612    /// and discards this field (it only matters at render time, and
613    /// `PlotGrid` builds its cells independently of
614    /// `GGPlot::render_native`, the only place that previously read it),
615    /// so it has to be captured here and carried to the cell's own
616    /// backend in `render_prepared`.
617    svg_formatted_values: bool,
618    /// The cell's own `GGPlot::svg_attr`/`svg_attrs` (#208): same reason
619    /// as `svg_formatted_values` above — `build_for_render` discards
620    /// `GGPlot::root_attrs`, so it's captured here and applied in
621    /// `render_prepared`, on a `<g>` wrapping the cell's own content (the
622    /// cell's root `<svg>` carries `root_data_attrs` and `data-panel`
623    /// already; the grid's root carries the *grid's* own `svg_attr`s —
624    /// neither is this cell's to share).
625    root_attrs: Vec<(String, String)>,
626}
627
628enum Prepared {
629    Plot(Box<PreparedPlot>),
630    Grid(Box<PreparedGrid>),
631    Spacer,
632}
633
634struct PreparedGrid {
635    cells: Vec<Prepared>,
636    ncol: usize,
637    nrow: usize,
638    byrow: bool,
639    widths: Vec<f64>,
640    heights: Vec<f64>,
641    title: Option<String>,
642    subtitle: Option<String>,
643    caption: Option<String>,
644    spacing: f64,
645    theme: Theme,
646    axis_collect: AxisCollect,
647}
648
649impl Prepared {
650    fn dims(&self) -> (usize, usize) {
651        match self {
652            Prepared::Grid(g) => (g.nrow, g.ncol),
653            _ => (1, 1),
654        }
655    }
656}
657
658fn prepare_grid(grid: PlotGrid, ctx: &mut PrepCtx) -> Result<Prepared, GGError> {
659    let n = grid.cells.len();
660    let (ncol, nrow) = match (grid.ncol, grid.nrow, grid.op) {
661        (Some(c), Some(r), _) => {
662            // Grow rows if the cells don't fit.
663            (c, r.max(n.div_ceil(c)))
664        }
665        (Some(c), None, _) => (c, n.div_ceil(c).max(1)),
666        (None, Some(r), _) => (n.div_ceil(r).max(1), r),
667        (None, None, Some(Op::Row)) => (n.max(1), 1),
668        (None, None, Some(Op::Col)) => (1, n.max(1)),
669        (None, None, None) => {
670            let c = ((n as f64).sqrt().ceil() as usize).max(1);
671            (c, n.div_ceil(c).max(1))
672        }
673    };
674    let mut theme = grid.theme;
675    theme.resolve_inheritance();
676    let mut cells = Vec::with_capacity(n);
677    for cell in grid.cells {
678        cells.push(match cell {
679            GridCell::Spacer => Prepared::Spacer,
680            GridCell::Grid(g) => prepare_grid(*g, ctx)?,
681            GridCell::Plot(p) => Prepared::Plot(Box::new(prepare_plot(*p, ctx)?)),
682        });
683    }
684    Ok(Prepared::Grid(Box::new(PreparedGrid {
685        cells,
686        ncol,
687        nrow,
688        byrow: grid.byrow,
689        widths: grid.widths,
690        heights: grid.heights,
691        title: grid.title,
692        subtitle: grid.subtitle,
693        caption: grid.caption,
694        spacing: grid.spacing,
695        theme,
696        axis_collect: grid.axis_collect,
697    })))
698}
699
700fn prepare_plot(mut plot: GGPlot, ctx: &mut PrepCtx) -> Result<PreparedPlot, GGError> {
701    ctx.next_index += 1;
702    if let Some((levels, pre, suf)) = &ctx.tags {
703        plot.labels.tag = Some(format!("{pre}{}{suf}", levels.tag(ctx.next_tag)));
704        ctx.next_tag += 1;
705    }
706    let panel = plot
707        .labels
708        .tag
709        .clone()
710        .unwrap_or_else(|| ctx.next_index.to_string());
711
712    // Collect an outside legend: suppress it in the plot, draw it separately.
713    let original = plot.theme.legend_position.clone();
714    let collect = ctx.collect.filter(|_| {
715        matches!(
716            original,
717            LegendPosition::Right
718                | LegendPosition::Left
719                | LegendPosition::Top
720                | LegendPosition::Bottom
721        )
722    });
723    if collect.is_some() {
724        plot.theme.legend_position = LegendPosition::None;
725    }
726    let svg_formatted_values = plot.svg_formatted_values;
727    let root_attrs = plot.root_attrs.clone();
728    let (built, mut meta) = plot.build_for_render()?;
729    if let Some(pos) = collect {
730        meta.has_legend = false;
731        if let Some(l) = capture_legend(
732            &built,
733            pos,
734            ctx.page_w,
735            ctx.page_h,
736            &mut ctx.legend_warnings,
737        )
738        .map_err(GGError::Render)?
739        {
740            if !ctx.legends.iter().any(|o| o.body == l.body) {
741                ctx.legends.push(l);
742            }
743        }
744    }
745    Ok(PreparedPlot {
746        built,
747        meta,
748        panel,
749        svg_formatted_values,
750        root_attrs,
751    })
752}
753
754/// Draw a built plot's legend in isolation, measuring its extent.
755///
756/// `page_w`/`page_h` are the grid's overall page size (sipemu/
757/// ggplot-rs#155): a collected legend has no natural width/height bound
758/// of its own — the strip that holds it is sized by whatever the legend
759/// needs — so a discrete guide wraps/grids here against the page itself,
760/// the same way a single plot's legend wraps against its own canvas.
761fn capture_legend(
762    built: &crate::build::BuiltPlot,
763    pos: GridLegendPosition,
764    page_w: f64,
765    page_h: f64,
766    // Review #167 finding 6 (#170): the plan's own `guide_legend:
767    // nrow(0)/ncol(0) is invalid`-style warnings used to go into a
768    // `legend_warnings` local that nothing ever read — this path dropped
769    // them silently. The caller threads its own warnings vec through so
770    // they land in the grid's `render_svg_native_with_warnings` /
771    // `data-warnings`, the same place a single plot's own legend
772    // warnings go (`GGPlot::layout_built` → `built.warnings`).
773    warnings: &mut Vec<String>,
774) -> Result<Option<Legend>, RenderError> {
775    let mut theme = built.theme.clone();
776    let m = theme.legend_margin.clone();
777    // Fake a zero-size panel so the legend's origin lands at (0, 0).
778    let (pa, lp, is_horizontal) = match pos {
779        GridLegendPosition::Right => (
780            Rect {
781                x: -m.left,
782                y: -m.top,
783                width: 0.0,
784                height: 0.0,
785            },
786            LegendPosition::Right,
787            false,
788        ),
789        GridLegendPosition::Bottom => (
790            Rect {
791                x: -m.left,
792                y: -(m.top + 30.0),
793                width: 0.0,
794                height: 0.0,
795            },
796            LegendPosition::Bottom,
797            true,
798        ),
799    };
800    theme.legend_position = lp;
801    let mut svg = SvgBackend::new(1, 1, pa.clone());
802    let mut meas = Measure::new(&mut svg, pa.clone());
803    let avail_width = (page_w + m.left).max(0.0);
804    let avail_height = (page_h + m.top).max(0.0);
805    let legend_plans = legend::plan_all_legends(
806        &built.scales,
807        &built.guide_legend,
808        &theme,
809        &built.suppressed_aes,
810        avail_width,
811        avail_height,
812        is_horizontal,
813        warnings,
814    );
815    legend::draw_legend_planned(
816        &built.scales,
817        &theme,
818        &pa,
819        // Review #167 finding 1: step by the same `avail_width` share
820        // `plan_all_legends` just planned against, not `pa.width` (always
821        // 0.0 — `pa` is a fake zero-size panel so the legend's origin
822        // lands at (0, 0)). Using `pa.width` made every discrete guide
823        // after the first advance by zero, so two collected guides (e.g.
824        // `colour` and `shape`) were drawn on top of each other.
825        avail_width,
826        &mut meas,
827        &built.guide_legend,
828        &built.suppressed_aes,
829        &legend_plans,
830    )?;
831    let ext = meas.extent();
832    if svg.body().is_empty() {
833        return Ok(None);
834    }
835    let (x0, y0, x1, y1) = match ext {
836        Some(e) => e,
837        None => return Ok(None),
838    };
839    Ok(Some(Legend {
840        body: svg.body().to_string(),
841        x0,
842        y0,
843        w: (x1 - x0).max(0.0),
844        h: (y1 - y0).max(0.0),
845    }))
846}
847
848/// Normalised track sizes: `n` relative weights (recycled, invalid → 1).
849fn tracks(weights: &[f64], n: usize, total: f64, gap: f64) -> Vec<(f64, f64)> {
850    let ws: Vec<f64> = (0..n)
851        .map(|i| {
852            if weights.is_empty() {
853                1.0
854            } else {
855                let w = weights[i % weights.len()];
856                if w.is_finite() && w > 0.0 {
857                    w
858                } else {
859                    1.0
860                }
861            }
862        })
863        .collect();
864    let sum: f64 = ws.iter().sum();
865    let avail = (total - gap * n.saturating_sub(1) as f64).max(0.0);
866    let mut pos = 0.0;
867    ws.iter()
868        .map(|w| {
869            let size = avail * w / sum;
870            let t = (pos, size);
871            pos += size + gap;
872            t
873        })
874        .collect()
875}
876
877fn text_style(el: &crate::theme::elements::ElementText, anchor: TextAnchor) -> TextStyle {
878    TextStyle {
879        color: el.color,
880        size: el.size,
881        anchor,
882        angle: 0.0,
883        family: (!el.family.is_empty()).then(|| el.family.clone()),
884        face: el.face,
885        bg_colour: None,
886        bg_r: 0.0,
887    }
888}
889
890fn hjust_x(el: &crate::theme::elements::ElementText, x0: f64, x1: f64) -> (f64, TextAnchor) {
891    let hj = if el.hjust.is_finite() {
892        el.hjust.clamp(0.0, 1.0)
893    } else {
894        0.0
895    };
896    let anchor = if hj <= 0.02 {
897        TextAnchor::Start
898    } else if hj >= 0.98 {
899        TextAnchor::End
900    } else {
901        TextAnchor::Middle
902    };
903    (x0 + hj * (x1 - x0), anchor)
904}
905
906fn render_prepared(
907    prepared: Prepared,
908    area: &Rect,
909    page: &mut SvgBackend,
910    warnings: &mut Vec<String>,
911) -> Result<(), GGError> {
912    match prepared {
913        Prepared::Spacer => Ok(()),
914        Prepared::Plot(p) => {
915            let PreparedPlot {
916                mut built,
917                meta,
918                panel,
919                svg_formatted_values,
920                root_attrs,
921            } = *p;
922            let (cw, ch) = (
923                area.width.floor().max(1.0) as u32,
924                area.height.floor().max(1.0) as u32,
925            );
926            let layout = GGPlot::layout_built(&mut built, &meta, cw, ch);
927            let mut backend = SvgBackend::new(cw, ch, layout.plot_area.clone());
928            backend.set_formatted_values(svg_formatted_values);
929            let mut attrs = root_data_attrs(&built);
930            attrs.push(("data-panel".into(), panel.clone()));
931            backend.set_root_attrs(attrs);
932            PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
933            // #208: this cell's own `svg_attr`s go on a `<g>` wrapping its
934            // content, not the cell's root `<svg>` (that one is
935            // `root_data_attrs` + `data-panel`, ggplot-rs's own) nor the
936            // grid's root (that one is the *grid's* own `svg_attr`s) — so
937            // `existing` is empty: nothing built-in to collide with here,
938            // only a name reused across two `svg_attr` calls.
939            let mut attr_warnings = Vec::new();
940            let group_attrs = validate_root_attrs(&root_attrs, &[], "plot", &mut attr_warnings);
941            backend.wrap_body_in_group(&group_attrs);
942            warnings.extend(
943                built
944                    .warnings
945                    .iter()
946                    .cloned()
947                    .chain(backend.take_warnings())
948                    .chain(attr_warnings)
949                    .map(|w| format!("panel {panel}: {w}")),
950            );
951            page.push_raw(&backend.finish_fragment(area.x, area.y));
952            Ok(())
953        }
954        Prepared::Grid(g) => {
955            let mut g = *g;
956            let theme = &g.theme;
957            let m = &theme.plot_margin;
958            // Header / footer bands.
959            let mut top = area.y;
960            let (x0, x1) = (area.x + m.left, area.x + area.width - m.right);
961            if let Some(t) = &g.title {
962                top += m.top;
963                let (tx, anchor) = hjust_x(&theme.title, x0, x1);
964                page.draw_text(
965                    t,
966                    (tx, top + theme.title.size * 0.8),
967                    &text_style(&theme.title, anchor),
968                )
969                .map_err(GGError::Render)?;
970                top += theme.title.size * 1.6;
971            }
972            if let Some(s) = &g.subtitle {
973                if g.title.is_none() {
974                    top += m.top;
975                }
976                let (sx, anchor) = hjust_x(&theme.subtitle, x0, x1);
977                page.draw_text(
978                    s,
979                    (sx, top + theme.subtitle.size * 0.7),
980                    &text_style(&theme.subtitle, anchor),
981                )
982                .map_err(GGError::Render)?;
983                top += theme.subtitle.size * 1.5;
984            }
985            let mut bottom = area.y + area.height;
986            if let Some(c) = &g.caption {
987                let (cx, anchor) = hjust_x(&theme.caption, x0, x1);
988                bottom -= theme.caption.size * 1.8;
989                page.draw_text(
990                    c,
991                    (cx, bottom + theme.caption.size * 0.9),
992                    &text_style(&theme.caption, anchor),
993                )
994                .map_err(GGError::Render)?;
995            }
996            let body_h = (bottom - top).max(1.0);
997            let cols = tracks(&g.widths, g.ncol, area.width, g.spacing);
998            let rows = tracks(&g.heights, g.nrow, body_h, g.spacing);
999            if g.axis_collect != AxisCollect::Keep {
1000                align_axes(
1001                    &mut g.cells,
1002                    (g.ncol, g.nrow, g.byrow),
1003                    &cols,
1004                    &rows,
1005                    g.axis_collect,
1006                    warnings,
1007                );
1008            }
1009            for (k, cell) in g.cells.into_iter().enumerate() {
1010                let (r, c) = if g.byrow {
1011                    (k / g.ncol, k % g.ncol)
1012                } else {
1013                    (k % g.nrow, k / g.nrow)
1014                };
1015                if r >= g.nrow || c >= g.ncol {
1016                    // More cells than nrow × ncol: the rest do not fit.
1017                    warnings.push(format!(
1018                        "plot_grid: cell {} does not fit a {}×{} grid; skipped",
1019                        k + 1,
1020                        g.nrow,
1021                        g.ncol
1022                    ));
1023                    continue;
1024                }
1025                let rect = Rect {
1026                    x: area.x + cols[c].0,
1027                    y: top + rows[r].0,
1028                    width: cols[c].1,
1029                    height: rows[r].1,
1030                };
1031                render_prepared(cell, &rect, page, warnings)?;
1032            }
1033            Ok(())
1034        }
1035    }
1036}
1037
1038/// sipemu/ggplot-rs#175: align a grid's own direct cells' plot areas and/or
1039/// x domain, column by column ([`AxisCollect::Align`]/[`AxisCollect::CollectX`]).
1040/// `cols`/`rows` are this grid's own track sizes (same for every cell in a
1041/// column/row), already computed by the caller. Only `Prepared::Plot` cells
1042/// participate; a column with fewer than two of them is left untouched.
1043fn align_axes(
1044    cells: &mut [Prepared],
1045    // (ncol, nrow, byrow) — bundled so the function stays under clippy's
1046    // argument-count limit.
1047    (ncol, nrow, byrow): (usize, usize, bool),
1048    cols: &[(f64, f64)],
1049    rows: &[(f64, f64)],
1050    mode: AxisCollect,
1051    warnings: &mut Vec<String>,
1052) {
1053    let idx_of = |r: usize, c: usize| -> usize {
1054        if byrow {
1055            r * ncol + c
1056        } else {
1057            c * nrow + r
1058        }
1059    };
1060    for c in 0..ncol {
1061        let cw = cols.get(c).map_or(0.0, |t| t.1);
1062        if !cw.is_finite() || cw <= 0.0 {
1063            continue;
1064        }
1065        // (row, cell index) of every plot cell in this column, top to
1066        // bottom. A spacer or a nested grid is skipped — it keeps its own
1067        // layout and doesn't count toward "the bottom cell" either.
1068        let plot_cells: Vec<(usize, usize)> = (0..nrow)
1069            .filter_map(|r| {
1070                let k = idx_of(r, c);
1071                (k < cells.len() && matches!(cells[k], Prepared::Plot(_))).then_some((r, k))
1072            })
1073            .collect();
1074        if plot_cells.len() < 2 {
1075            continue; // nothing to align against in this column
1076        }
1077        let bottom_row = plot_cells.iter().map(|&(r, _)| r).max().unwrap();
1078
1079        // Switch every cell to `Shift` (so an overflowing outer label can
1080        // never grow its margins behind our back) and, under `CollectX`,
1081        // blank every non-bottom cell's x axis *before* measuring, so the
1082        // measurement already reflects what's actually drawn.
1083        for &(r, k) in &plot_cells {
1084            if let Prepared::Plot(p) = &mut cells[k] {
1085                p.built.theme.axis_text_x_fit = AxisLabelFit::Shift;
1086                if mode == AxisCollect::CollectX && r != bottom_row {
1087                    p.built.theme.axis_text_x = ElementText::blank();
1088                    p.built.theme.axis_title_x = ElementText::blank();
1089                    p.built.theme.axis_ticks_x = Some(ElementLine::blank());
1090                }
1091            }
1092        }
1093
1094        // Each cell's own plot-area rect at this column's width — pure
1095        // layout arithmetic (`GGPlot::layout_built`, the same computation
1096        // the real render pass makes), not a drawn-and-measured SVG, so
1097        // this whole pass costs one extra layout per cell, not a redraw.
1098        // `y`/`height` are kept too, for the thin-cell correction below —
1099        // changing a cell's left/right margin never moves them (only
1100        // top/bottom margins and the vertical bands do), so one layout
1101        // call per cell covers both passes.
1102        let mut natural: Vec<(f64, f64, f64, f64, f64)> = Vec::with_capacity(plot_cells.len());
1103        for &(r, k) in &plot_cells {
1104            let ch = rows.get(r).map_or(0.0, |t| t.1);
1105            match &mut cells[k] {
1106                Prepared::Plot(p) => {
1107                    let layout = GGPlot::layout_built(
1108                        &mut p.built,
1109                        &p.meta,
1110                        cw.floor().max(1.0) as u32,
1111                        ch.floor().max(1.0) as u32,
1112                    );
1113                    natural.push((
1114                        layout.plot_area.x,
1115                        layout.plot_area.x + layout.plot_area.width,
1116                        layout.plot_area.y,
1117                        layout.plot_area.height,
1118                        ch,
1119                    ));
1120                }
1121                _ => unreachable!("plot_cells only holds Prepared::Plot indices"),
1122            }
1123        }
1124
1125        // Equal left/right insets: every cell's left margin grows to the
1126        // widest left requirement in the column, and likewise for the
1127        // right (anofox-visualization's `track.rs` `left = max(...)`
1128        // fallback, generalised to both edges and computed once).
1129        let target_left = natural.iter().fold(f64::MIN, |m, &(l, ..)| m.max(l));
1130        let target_right_inset = natural
1131            .iter()
1132            .fold(f64::MIN, |m, &(_, r, ..)| m.max(cw - r));
1133        let width = cw - target_right_inset - target_left;
1134        if target_left.is_finite() && target_right_inset.is_finite() {
1135            for (&(_, k), &(nl, nr, ..)) in plot_cells.iter().zip(&natural) {
1136                if let Prepared::Plot(p) = &mut cells[k] {
1137                    p.built.theme.plot_margin.left += (target_left - nl).max(0.0);
1138                    p.built.theme.plot_margin.right += (target_right_inset - (cw - nr)).max(0.0);
1139                }
1140            }
1141        }
1142
1143        // A cell thinner than the plotting engine's 50px panel-height
1144        // floor (anofox-visualization's `::TRACK` strips, ~16-30px) would
1145        // otherwise overflow its own canvas: `layout_built` never shrinks
1146        // a panel below 50px on its own. Mirror `track.rs`'s `Fit::correct`
1147        // `aspect` trick — a centred `aspect_ratio` set so the panel comes
1148        // out exactly as tall as what's actually left after the margins —
1149        // but computed once from this same `layout_built` measurement
1150        // instead of track.rs's render-measure-render loop. A cell that
1151        // already fits (the common case — a normal chart cell) is
1152        // untouched.
1153        if width.is_finite() && width > 0.0 {
1154            for (&(_, k), &(_, _, y, h, ch)) in plot_cells.iter().zip(&natural) {
1155                if let Prepared::Plot(p) = &mut cells[k] {
1156                    let bottom_budget = ch - p.built.theme.plot_margin.bottom;
1157                    if y + h > bottom_budget + 0.5 {
1158                        let fits = (ch - y - p.built.theme.plot_margin.bottom).max(8.0);
1159                        p.built.theme.aspect_ratio = Some(fits / width);
1160                        p.built.theme.plot_margin.top -= (h - fits) / 2.0;
1161                    }
1162                }
1163            }
1164        }
1165
1166        if mode == AxisCollect::CollectX {
1167            collect_x_domain(cells, &plot_cells, warnings);
1168        }
1169    }
1170}
1171
1172/// Train one x domain across a column's cells — the union of every cell's
1173/// own trained domain — then pin every cell's x scale to it
1174/// ([`ScaleSet::set_limits`](crate::scale::ScaleSet::set_limits), the same
1175/// mechanism `coord_cartesian_zoom` uses). Each scale keeps its own
1176/// `expand`; since every cell now trains the same raw domain, identical
1177/// `expand` settings produce an identical expanded (drawn) domain too.
1178/// Skipped, with a warning, when any cell's x scale is discrete or
1179/// untrained — there's no well-defined union of levels or of nothing.
1180fn collect_x_domain(
1181    cells: &mut [Prepared],
1182    plot_cells: &[(usize, usize)],
1183    warnings: &mut Vec<String>,
1184) {
1185    let mut domains = Vec::with_capacity(plot_cells.len());
1186    for &(_, k) in plot_cells {
1187        let d = match &cells[k] {
1188            Prepared::Plot(p) => match p.built.scales.get(&Aesthetic::X) {
1189                Some(s) if !s.is_discrete() => s.domain(),
1190                _ => None,
1191            },
1192            _ => None,
1193        };
1194        match d {
1195            Some(d) => domains.push(d),
1196            None => {
1197                warnings.push(
1198                    "plot_grid: a column's x scale is discrete or untrained; x domain not \
1199                     collected"
1200                        .to_string(),
1201                );
1202                return;
1203            }
1204        }
1205    }
1206    let lo = domains.iter().map(|d| d.0).fold(f64::INFINITY, f64::min);
1207    let hi = domains
1208        .iter()
1209        .map(|d| d.1)
1210        .fold(f64::NEG_INFINITY, f64::max);
1211    if lo.is_finite() && hi.is_finite() && hi >= lo {
1212        for &(_, k) in plot_cells {
1213            if let Prepared::Plot(p) = &mut cells[k] {
1214                p.built.scales.set_limits(&Aesthetic::X, lo, hi);
1215            }
1216        }
1217    }
1218}
1219
1220/// A backend wrapper that records the bounding box of everything drawn.
1221struct Measure<'a> {
1222    inner: &'a mut SvgBackend,
1223    pa: Rect,
1224    bbox: Option<(f64, f64, f64, f64)>,
1225}
1226
1227impl<'a> Measure<'a> {
1228    fn new(inner: &'a mut SvgBackend, pa: Rect) -> Self {
1229        Measure {
1230            inner,
1231            pa,
1232            bbox: None,
1233        }
1234    }
1235
1236    fn grow(&mut self, x0: f64, y0: f64, x1: f64, y1: f64) {
1237        if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) {
1238            return;
1239        }
1240        self.bbox = Some(match self.bbox {
1241            None => (x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)),
1242            Some((a, b, c, d)) => (
1243                a.min(x0.min(x1)),
1244                b.min(y0.min(y1)),
1245                c.max(x0.max(x1)),
1246                d.max(y0.max(y1)),
1247            ),
1248        });
1249    }
1250
1251    fn extent(&self) -> Option<(f64, f64, f64, f64)> {
1252        self.bbox
1253    }
1254}
1255
1256impl DrawBackend for Measure<'_> {
1257    fn draw_circle(
1258        &mut self,
1259        c: (f64, f64),
1260        r: f64,
1261        style: &PointStyle,
1262    ) -> Result<(), RenderError> {
1263        self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
1264        self.inner.draw_circle(c, r, style)
1265    }
1266    fn draw_line(&mut self, pts: &[(f64, f64)], style: &LineStyle) -> Result<(), RenderError> {
1267        for p in pts {
1268            self.grow(p.0, p.1, p.0, p.1);
1269        }
1270        self.inner.draw_line(pts, style)
1271    }
1272    fn draw_quadratic(
1273        &mut self,
1274        p0: (f64, f64),
1275        ctrl: (f64, f64),
1276        p1: (f64, f64),
1277        style: &LineStyle,
1278    ) -> Result<(), RenderError> {
1279        self.grow(p0.0, p0.1, p0.0, p0.1);
1280        self.grow(ctrl.0, ctrl.1, ctrl.0, ctrl.1);
1281        self.grow(p1.0, p1.1, p1.0, p1.1);
1282        self.inner.draw_quadratic(p0, ctrl, p1, style)
1283    }
1284    fn draw_rect(
1285        &mut self,
1286        a: (f64, f64),
1287        b: (f64, f64),
1288        style: &RectStyle,
1289    ) -> Result<(), RenderError> {
1290        self.grow(a.0, a.1, b.0, b.1);
1291        self.inner.draw_rect(a, b, style)
1292    }
1293    fn draw_text(
1294        &mut self,
1295        text: &str,
1296        pos: (f64, f64),
1297        style: &TextStyle,
1298    ) -> Result<(), RenderError> {
1299        self.draw_text_with_title(text, pos, style, None)
1300    }
1301    fn draw_text_with_title(
1302        &mut self,
1303        text: &str,
1304        pos: (f64, f64),
1305        style: &TextStyle,
1306        title: Option<&str>,
1307    ) -> Result<(), RenderError> {
1308        // Review #167 finding 4 (#170): this wrapper must forward to
1309        // `inner.draw_text_with_title`, not `inner.draw_text` — the
1310        // latter is what `DrawBackend::draw_text_with_title`'s own
1311        // default impl calls, and relying on that default here would
1312        // silently drop a truncated legend label's `<title>` tooltip
1313        // (#159) whenever the label is measured through `Measure`
1314        // (`compose::capture_legend`'s collected-legend path).
1315        let w = text.chars().count() as f64 * style.size * 0.6;
1316        let (x0, x1) = match style.anchor {
1317            TextAnchor::Start => (pos.0, pos.0 + w),
1318            TextAnchor::Middle => (pos.0 - w / 2.0, pos.0 + w / 2.0),
1319            TextAnchor::End => (pos.0 - w, pos.0),
1320        };
1321        self.grow(x0, pos.1 - style.size / 2.0, x1, pos.1 + style.size / 2.0);
1322        self.inner.draw_text_with_title(text, pos, style, title)
1323    }
1324    fn draw_polygon(&mut self, pts: &[(f64, f64)], style: &RectStyle) -> Result<(), RenderError> {
1325        for p in pts {
1326            self.grow(p.0, p.1, p.0, p.1);
1327        }
1328        self.inner.draw_polygon(pts, style)
1329    }
1330    fn draw_shape(&mut self, c: (f64, f64), r: f64, style: &PointStyle) -> Result<(), RenderError> {
1331        self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
1332        self.inner.draw_shape(c, r, style)
1333    }
1334    fn plot_area(&self) -> Rect {
1335        self.pa.clone()
1336    }
1337    fn total_area(&self) -> Rect {
1338        self.inner.total_area()
1339    }
1340    fn set_tooltip(&mut self, t: Option<String>) {
1341        self.inner.set_tooltip(t)
1342    }
1343    fn set_mark_axis(&mut self, k: Option<String>) {
1344        self.inner.set_mark_axis(k)
1345    }
1346    fn set_mark_series(&mut self, s: Option<String>) {
1347        self.inner.set_mark_series(s)
1348    }
1349    fn set_mark_value(&mut self, v: Option<String>) {
1350        self.inner.set_mark_value(v)
1351    }
1352    fn warn(&mut self, m: String) {
1353        self.inner.warn(m)
1354    }
1355    fn set_mark_geom(&mut self, geom: Option<&str>) {
1356        self.inner.set_mark_geom(geom)
1357    }
1358    fn set_mark_part(&mut self, part: Option<&str>) {
1359        self.inner.set_mark_part(part)
1360    }
1361    fn set_mark_attrs(&mut self, attrs: Vec<(String, String)>) {
1362        self.inner.set_mark_attrs(attrs)
1363    }
1364
1365    fn set_mark_class(&mut self, class: Option<String>) {
1366        self.inner.set_mark_class(class)
1367    }
1368
1369    fn set_mark_group(&mut self, group: Option<(String, String)>) {
1370        self.inner.set_mark_group(group)
1371    }
1372
1373    fn set_layer_attrs(&mut self, attrs: Vec<(String, String)>) {
1374        self.inner.set_layer_attrs(attrs)
1375    }
1376    fn wants_formatted_values(&self) -> bool {
1377        self.inner.wants_formatted_values()
1378    }
1379    fn set_mark_fvalue(&mut self, value: Option<String>) {
1380        self.inner.set_mark_fvalue(value)
1381    }
1382    fn set_mark_fx(&mut self, value: Option<String>) {
1383        self.inner.set_mark_fx(value)
1384    }
1385}
1386
1387// ─── Operator sugar ─────────────────────────────────────────────────
1388
1389fn join(op: Op, a: GridCell, b: GridCell) -> PlotGrid {
1390    let flatten = |c: GridCell| -> Vec<GridCell> {
1391        match c {
1392            GridCell::Grid(g) if g.op == Some(op) && g.is_plain() => g.cells,
1393            other => vec![other],
1394        }
1395    };
1396    let mut cells = flatten(a);
1397    cells.extend(flatten(b));
1398    PlotGrid {
1399        cells,
1400        op: Some(op),
1401        ..PlotGrid::default()
1402    }
1403}
1404
1405impl PlotGrid {
1406    /// Built purely by an operator chain (no explicit layout/annotations), so
1407    /// it can be flattened into a longer chain of the same operator.
1408    fn is_plain(&self) -> bool {
1409        self.ncol.is_none()
1410            && self.nrow.is_none()
1411            && self.widths.is_empty()
1412            && self.heights.is_empty()
1413            && self.title.is_none()
1414            && self.subtitle.is_none()
1415            && self.caption.is_none()
1416            && self.tags.is_none()
1417            && !self.collect_legends
1418            && self.axis_collect == AxisCollect::Keep
1419    }
1420}
1421
1422macro_rules! grid_ops {
1423    ($lhs:ty, $rhs:ty) => {
1424        /// `a | b`: place side by side (patchwork).
1425        impl BitOr<$rhs> for $lhs {
1426            type Output = PlotGrid;
1427            fn bitor(self, rhs: $rhs) -> PlotGrid {
1428                join(Op::Row, self.into(), rhs.into())
1429            }
1430        }
1431        /// `a / b`: stack vertically (patchwork).
1432        impl Div<$rhs> for $lhs {
1433            type Output = PlotGrid;
1434            fn div(self, rhs: $rhs) -> PlotGrid {
1435                join(Op::Col, self.into(), rhs.into())
1436            }
1437        }
1438    };
1439}
1440
1441grid_ops!(GGPlot, GGPlot);
1442grid_ops!(GGPlot, PlotGrid);
1443grid_ops!(PlotGrid, GGPlot);
1444grid_ops!(PlotGrid, PlotGrid);
1445
1446#[cfg(test)]
1447mod tests {
1448    use super::*;
1449
1450    #[test]
1451    fn tag_sequences() {
1452        let l: Vec<String> = (0..28).map(|i| TagLevels::Lower.tag(i)).collect();
1453        assert_eq!(&l[..3], &["a", "b", "c"]);
1454        assert_eq!(l[25], "z");
1455        assert_eq!(l[26], "aa");
1456        assert_eq!(l[27], "ab");
1457        assert_eq!(TagLevels::Upper.tag(1), "B");
1458        assert_eq!(TagLevels::Numeric.tag(9), "10");
1459        assert_eq!(TagLevels::LowerRoman.tag(3), "iv");
1460        assert_eq!(TagLevels::UpperRoman.tag(13), "XIV");
1461        assert_eq!(TagLevels::Custom(vec!["x".into()]).tag(1), "2");
1462    }
1463
1464    #[test]
1465    fn tracks_are_relative_and_robust() {
1466        let t = tracks(&[2.0, 1.0], 2, 300.0, 0.0);
1467        assert_eq!(t, vec![(0.0, 200.0), (200.0, 100.0)]);
1468        let t = tracks(&[f64::NAN, -1.0], 2, 100.0, 10.0);
1469        assert_eq!(t, vec![(0.0, 45.0), (55.0, 45.0)]);
1470        let t = tracks(&[], 3, 30.0, 100.0);
1471        assert!(t.iter().all(|(p, s)| p.is_finite() && *s == 0.0));
1472    }
1473
1474    /// `Measure` (the legend bbox pre-pass) forwards every `DrawBackend`
1475    /// method to its inner backend and grows its tracked extent to include
1476    /// a quadratic curve's control points — not just straight lines/shapes.
1477    #[test]
1478    fn measure_forwards_draw_quadratic_and_mark_metadata_and_grows_its_extent() {
1479        let pa = Rect {
1480            x: 0.0,
1481            y: 0.0,
1482            width: 100.0,
1483            height: 100.0,
1484        };
1485        let mut backend = SvgBackend::new(100, 100, pa.clone());
1486        backend.set_formatted_values(true);
1487        let mut meas = Measure::new(&mut backend, pa);
1488
1489        assert!(meas.extent().is_none());
1490        // B2-4: Measure forwards the formatted-values query/setters too.
1491        assert!(meas.wants_formatted_values());
1492        meas.set_mark_geom(Some("line"));
1493        meas.set_mark_part(Some("arrow"));
1494        meas.set_mark_attrs(vec![("data-x".to_string(), "v".to_string())]);
1495        meas.set_mark_fvalue(Some("1,234.5".to_string()));
1496        meas.set_mark_fx(Some("2026-10-12".to_string()));
1497        meas.draw_quadratic(
1498            (10.0, 20.0),
1499            (90.0, 5.0),
1500            (50.0, 80.0),
1501            &LineStyle::default(),
1502        )
1503        .unwrap();
1504        meas.set_mark_geom(None);
1505        meas.set_mark_part(None);
1506        meas.set_mark_attrs(Vec::new());
1507        meas.set_mark_fvalue(None);
1508        meas.set_mark_fx(None);
1509
1510        let (x0, y0, x1, y1) = meas.extent().expect("extent after drawing");
1511        assert_eq!((x0, y0, x1, y1), (10.0, 5.0, 90.0, 80.0));
1512
1513        // The marks actually reached the inner SvgBackend (data-part, the
1514        // data_attr, the mark class and the formatted values all appear in
1515        // its output).
1516        let svg = backend.finish();
1517        assert!(svg.contains("data-part=\"arrow\""));
1518        assert!(svg.contains("data-x=\"v\""));
1519        assert!(svg.contains("gg-arrow"));
1520        assert!(svg.contains("data-fvalue=\"1,234.5\""));
1521        assert!(svg.contains("data-fx=\"2026-10-12\""));
1522    }
1523
1524    /// #170 / review #167 finding 4: `Measure::draw_text_with_title` must
1525    /// forward the `<title>` to its inner `SvgBackend`, not fall through
1526    /// to `DrawBackend::draw_text_with_title`'s default impl (which calls
1527    /// `self.draw_text`, and `Measure::draw_text` only ever calls
1528    /// `inner.draw_text` — dropping the title). This only matters once a
1529    /// `<title>` is actually passed through a `Measure`-wrapped backend
1530    /// (today that's `compose::capture_legend`'s collected-legend path, a
1531    /// `PlotGrid`'s B3-2 label truncation doesn't run yet, so the bug is
1532    /// latent rather than reachable from `PlotGrid`'s own public API —
1533    /// hence this unit test against `Measure` directly).
1534    #[test]
1535    fn measure_forwards_the_title_to_its_inner_backend() {
1536        let pa = Rect {
1537            x: 0.0,
1538            y: 0.0,
1539            width: 100.0,
1540            height: 100.0,
1541        };
1542        let mut backend = SvgBackend::new(100, 100, pa.clone());
1543        let mut meas = Measure::new(&mut backend, pa);
1544        meas.draw_text_with_title(
1545            "Grp…",
1546            (10.0, 20.0),
1547            &TextStyle {
1548                size: 12.0,
1549                anchor: TextAnchor::Start,
1550                ..Default::default()
1551            },
1552            Some("Group 01"),
1553        )
1554        .unwrap();
1555        let svg = backend.finish();
1556        assert!(
1557            svg.contains("<title>Group 01</title>"),
1558            "the full label should reach the inner backend's <title>: {svg}"
1559        );
1560    }
1561}