Skip to main content

ggplot_rs/guide/
legend.rs

1use crate::aes::Aesthetic;
2use crate::data::Value;
3use crate::guide::config::GuideLegend;
4use crate::render::backend::{
5    DrawBackend, LineStyle, Linetype, PointStyle, RectStyle, TextAnchor, TextStyle,
6};
7use crate::render::{Rect, RenderError};
8use crate::scale::ScaleSet;
9use crate::theme::{LegendPosition, Theme};
10
11/// Which aesthetics should generate legends.
12const LEGEND_AESTHETICS: &[Aesthetic] = &[
13    Aesthetic::Color,
14    Aesthetic::Fill,
15    Aesthetic::Shape,
16    Aesthetic::Linetype,
17    Aesthetic::Size,
18    Aesthetic::Alpha,
19    Aesthetic::Linewidth,
20];
21
22/// Whether `a` is one of [`LEGEND_AESTHETICS`] (#241: `has_legend_mapping`'s
23/// own `is_legend_aes` check, in `plot.rs`'s layout-building pass, had
24/// drifted into a second, incomplete copy of this list — missing
25/// `Linewidth`, so a plot mapping only `linewidth` reserved *no* legend
26/// space at all, and its legend then drew with nothing held back for it,
27/// running off the canvas). Delegating to this one list means the two
28/// checks — "should this aesthetic reserve layout space" and "should this
29/// aesthetic actually draw a legend" — can't drift apart again.
30pub(crate) fn is_legend_aesthetic(a: &Aesthetic) -> bool {
31    LEGEND_AESTHETICS.contains(a)
32}
33
34/// The aesthetics that would get a legend, in the same order and with the
35/// same color/fill de-duplication `draw_legend` and `draw_legend_planned`
36/// use. Shared with `layout_built` (B3-2), so the "is this the single
37/// discrete guide D7 requires" check is the same one the drawing code
38/// uses.
39pub(crate) fn legend_scales_for(
40    scales: &ScaleSet,
41    suppressed: &std::collections::HashSet<Aesthetic>,
42) -> Vec<Aesthetic> {
43    let mut legend_scales: Vec<Aesthetic> = Vec::new();
44    for aes in LEGEND_AESTHETICS {
45        if suppressed.contains(aes) {
46            continue;
47        }
48        if let Some(scale) = scales.get(aes) {
49            if !scale.breaks().is_empty() {
50                legend_scales.push(aes.clone());
51            }
52        }
53    }
54    legend_scales
55}
56
57/// Group `legend_scales` into mergeable sets (#239: ggplot2 merges `fill`
58/// and `colour` guides mapped to the same measure through the same scale
59/// spec into one legend with a combined key, rather than drawing one per
60/// aesthetic — and, conversely, draws *two* legends when they don't
61/// actually match, which an earlier, cruder rule here got wrong: it
62/// unconditionally dropped `Fill`'s own legend whenever `Color` was also
63/// mapped, even to an unrelated variable with a different title and
64/// breaks). Two aesthetics merge when their scales share the same
65/// effective title (`guide.title`, else `scale.name()`), the same
66/// discrete/continuous-ness, and *identical* `breaks()` (same positions
67/// and labels, in the same order) — the same practical "do these two
68/// guides look identical" test ggplot2 itself applies; a binned scale's
69/// breaks already carry its counts in their labels, so two binned scales
70/// with the same counts per bin merge too. Order preserved: each group
71/// keeps the position its first member had in `legend_scales`.
72pub(crate) fn group_mergeable_legends(
73    scales: &ScaleSet,
74    legend_scales: &[Aesthetic],
75    guide: &GuideLegend,
76) -> Vec<Vec<Aesthetic>> {
77    struct Key {
78        title: String,
79        discrete: bool,
80        breaks: Vec<(f64, String)>,
81    }
82    let mut groups: Vec<(Key, Vec<Aesthetic>)> = Vec::new();
83    for aes in legend_scales {
84        let Some(scale) = scales.get(aes) else {
85            continue;
86        };
87        let breaks = scale.breaks();
88        let title = guide
89            .title
90            .clone()
91            .unwrap_or_else(|| scale.name().to_string());
92        let discrete = scale.is_discrete();
93        match groups
94            .iter_mut()
95            .find(|(k, _)| k.title == title && k.discrete == discrete && k.breaks == breaks)
96        {
97            Some((_, members)) => members.push(aes.clone()),
98            None => groups.push((
99                Key {
100                    title,
101                    discrete,
102                    breaks,
103                },
104                vec![aes.clone()],
105            )),
106        }
107    }
108    groups.into_iter().map(|(_, members)| members).collect()
109}
110
111/// Draw all legends for the plot.
112///
113/// No longer called internally: `compose::capture_legend` (the only
114/// caller) was rerouted to `draw_legend_planned` in 0.23 so a `PlotGrid`'s
115/// collected legend gets the same B3-2 wrap/grid treatment a single
116/// plot's legend does (sipemu/ggplot-rs#155). `draw_legend_planned` is
117/// crate-internal (`pub(crate)`), so there is no direct public
118/// replacement — legend drawing is otherwise handled automatically by
119/// `GGPlot`'s own render methods, which is the supported way to draw a
120/// legend; this function was never meant to be called by consumers for
121/// that purpose and will be removed in a later minor release.
122#[deprecated(
123    since = "0.23.0",
124    note = "unused internally since 0.23 (superseded by the crate-internal draw_legend_planned, \
125             sipemu/ggplot-rs#155); no direct public replacement — legends are drawn automatically \
126             by GGPlot's render methods. Will be removed in a later minor release."
127)]
128pub fn draw_legend(
129    scales: &ScaleSet,
130    theme: &Theme,
131    plot_area: &Rect,
132    backend: &mut dyn DrawBackend,
133    guide: &GuideLegend,
134    suppressed: &std::collections::HashSet<Aesthetic>,
135) -> Result<(), RenderError> {
136    if matches!(theme.legend_position, LegendPosition::None) {
137        return Ok(());
138    }
139
140    // Collect all aesthetics that have a scale with breaks
141    let mut legend_scales: Vec<&Aesthetic> = Vec::new();
142    for aes in LEGEND_AESTHETICS {
143        // Skip suppressed aesthetics
144        if suppressed.contains(aes) {
145            continue;
146        }
147        if let Some(scale) = scales.get(aes) {
148            if !scale.breaks().is_empty() {
149                // Don't duplicate Color/Fill if both exist with same breaks
150                if *aes == Aesthetic::Fill && legend_scales.contains(&&Aesthetic::Color) {
151                    continue;
152                }
153                legend_scales.push(aes);
154            }
155        }
156    }
157
158    if legend_scales.is_empty() {
159        return Ok(());
160    }
161
162    // Compute legend origin based on position. This deprecated path never
163    // wraps a legend onto more than one row, so `legend_extra_rows` is
164    // always 0 — see `legend_position`'s doc comment. It also predates
165    // #225's `Inside` justification and keeps the old top-left anchor
166    // (`legend_size_hint: (0.0, 0.0)`) rather than estimate it, since
167    // it's unused internally and has no direct public replacement to
168    // keep behaviourally current.
169    let (legend_x, legend_y, mut is_horizontal) =
170        legend_position(theme, plot_area, 0, (0.0, 0.0), plot_area);
171    // legend.direction overrides the auto layout from the position.
172    if let Some(dir) = theme.legend_direction {
173        is_horizontal = matches!(dir, crate::theme::LegendDirection::Horizontal);
174    }
175
176    let mut offset_y = legend_y;
177    let mut offset_x = legend_x;
178
179    for aes in &legend_scales {
180        let scale = scales.get(aes).unwrap();
181
182        if scale.is_discrete() {
183            if is_horizontal {
184                let width = draw_discrete_legend_at(
185                    scales,
186                    &[((*aes).clone(), scale)],
187                    theme,
188                    offset_x,
189                    offset_y,
190                    backend,
191                    guide,
192                    true,
193                )?;
194                offset_x += width + theme.legend_spacing * 2.0;
195            } else {
196                let height = draw_discrete_legend_at(
197                    scales,
198                    &[((*aes).clone(), scale)],
199                    theme,
200                    offset_x,
201                    offset_y,
202                    backend,
203                    guide,
204                    false,
205                )?;
206                offset_y += height + theme.legend_spacing * 2.0;
207            }
208        } else {
209            // Continuous legend (colorbar) — only for color/fill
210            if matches!(aes, Aesthetic::Color | Aesthetic::Fill) {
211                let height = draw_continuous_legend_at(
212                    scale,
213                    theme,
214                    offset_x,
215                    offset_y,
216                    backend,
217                    guide,
218                    is_horizontal,
219                )?;
220                if is_horizontal {
221                    // #211: the bar is now drawn along x (wide, not
222                    // narrow) — step by its own length, not the old
223                    // vertical-bar width-plus-side-label estimate.
224                    let (bar_len, _) = continuous_bar_dims(theme, true);
225                    offset_x += bar_len + theme.legend_spacing * 2.0;
226                } else {
227                    offset_y += height + theme.legend_spacing * 2.0;
228                }
229            } else {
230                // Continuous size/alpha — draw as discrete-like with sampled breaks
231                let height = draw_discrete_legend_at(
232                    scales,
233                    &[((*aes).clone(), scale)],
234                    theme,
235                    offset_x,
236                    offset_y,
237                    backend,
238                    guide,
239                    is_horizontal,
240                )?;
241                if is_horizontal {
242                    offset_x += theme.legend_key_width
243                        + theme.legend_text.size * 6.0
244                        + theme.legend_spacing * 2.0;
245                } else {
246                    offset_y += height + theme.legend_spacing * 2.0;
247                }
248            }
249        }
250    }
251
252    Ok(())
253}
254
255/// How many rows beyond the first a horizontal legend wraps onto — `max`
256/// across guides sharing one row (several discrete guides side by side),
257/// `sum` for guides stacked vertically instead. Exactly `layout_built`'s
258/// own `extras.legend_extra_rows` computation, so anything derived from
259/// it here can't disagree with the `plot_area.y` that count already
260/// produced.
261fn legend_rows_beyond_first(
262    is_horizontal: bool,
263    legend_plans: &std::collections::HashMap<Aesthetic, LegendPlan>,
264) -> usize {
265    if is_horizontal {
266        legend_plans
267            .values()
268            .map(|p| p.rows.saturating_sub(1))
269            .max()
270            .unwrap_or(0)
271    } else {
272        legend_plans
273            .values()
274            .map(|p| p.rows.saturating_sub(1))
275            .sum()
276    }
277}
278
279/// A horizontal (`Top`/`Bottom`) legend's own band height —
280/// `legend_margin.top` plus `(1 + legend_extra_rows)` row-heights
281/// (`legend_key_height + legend_spacing` each) plus `legend_margin.bottom`
282/// — exactly what `PlotLayout::compute_with_extras` reserves for it
283/// (#233).
284pub(crate) fn legend_band_height(theme: &Theme, legend_extra_rows: usize) -> f64 {
285    theme.legend_margin.top
286        + (1.0 + legend_extra_rows as f64) * (theme.legend_key_height + theme.legend_spacing)
287        + theme.legend_margin.bottom
288}
289
290/// #233: how much `renderer.rs`'s title/subtitle drawing must additionally
291/// lift itself above `plot_area.y` so neither overlaps a `Top` legend —
292/// the same idea as its existing `x_axis_lift` (a top x-axis also
293/// reserves space above the panel). Zero when there's no legend to draw,
294/// or its position isn't `Top`: byte-identical to before in every other
295/// case.
296///
297/// #577: `legend_band_height` alone only covers the flat discrete-row
298/// case — a continuous, horizontally-drawn Color/Fill colourbar *with its
299/// own title* needs the same extra height `plot.rs` already reserves in
300/// `plot_area.y` via `continuous_horizontal_legend_extra_height` (#211).
301/// Without adding that extra here too, this lift undershot by exactly
302/// that amount, so the plot's own title/subtitle landed on top of the
303/// legend's title instead of above it. `guide` is the same
304/// [`GuideLegend`] `draw_legend_planned` draws with, so "does this guide
305/// have a title" can't disagree between the two.
306pub(crate) fn top_legend_lift(
307    theme: &Theme,
308    scales: &ScaleSet,
309    suppressed: &std::collections::HashSet<Aesthetic>,
310    legend_plans: &std::collections::HashMap<Aesthetic, LegendPlan>,
311    guide: &GuideLegend,
312) -> f64 {
313    if !matches!(theme.legend_position, LegendPosition::Top) {
314        return 0.0;
315    }
316    let legend_scales = legend_scales_for(scales, suppressed);
317    if legend_scales.is_empty() {
318        return 0.0;
319    }
320    let is_horizontal = match theme.legend_direction {
321        Some(dir) => matches!(dir, crate::theme::LegendDirection::Horizontal),
322        None => true, // Top is always the horizontal auto-position.
323    };
324    let base = legend_band_height(theme, legend_rows_beyond_first(is_horizontal, legend_plans));
325    let colorbar_extra = if is_horizontal {
326        legend_scales
327            .iter()
328            .find_map(|aes| {
329                if !matches!(aes, Aesthetic::Color | Aesthetic::Fill) {
330                    return None;
331                }
332                let scale = scales.get(aes)?;
333                if scale.is_discrete() {
334                    return None;
335                }
336                let title = guide.title.as_deref().unwrap_or_else(|| scale.name());
337                let bar_height = continuous_horizontal_bar_height(theme, !title.is_empty());
338                Some((bar_height - theme.legend_key_height).max(0.0))
339            })
340            .unwrap_or(0.0)
341    } else {
342        0.0
343    };
344    base + colorbar_extra
345}
346
347/// Estimate the on-canvas footprint `(width, height)` of every legend
348/// scale about to be drawn, stacked the same way `draw_legend_planned`
349/// stacks them (each one's own height summed, the widest width shared)
350/// — used only by `legend_position`'s `Inside` arm (#225) to place the
351/// *whole* legend block by justification instead of always anchoring
352/// its top-left corner there. Mirrors each draw function's own returned
353/// height/width formula exactly (`draw_continuous_legend_at`,
354/// `draw_discrete_legend_at`, `draw_discrete_legend_grid`) without
355/// drawing anything. A `legend_plans` entry (an explicit `nrow`/`ncol`
356/// grid — auto-wrap never applies to a non-horizontal legend like
357/// `Inside`) is honoured for an accurate multi-row/-column estimate;
358/// everything else uses the single-column formula.
359fn estimate_legend_box(
360    scales: &ScaleSet,
361    legend_scales: &[Aesthetic],
362    theme: &Theme,
363    guide: &GuideLegend,
364    legend_plans: &std::collections::HashMap<Aesthetic, LegendPlan>,
365) -> (f64, f64) {
366    let mut total_h = 0.0_f64;
367    let mut max_w = 0.0_f64;
368    for aes in legend_scales {
369        let Some(scale) = scales.get(aes) else {
370            continue;
371        };
372        let breaks = scale.breaks();
373        if breaks.is_empty() {
374            continue;
375        }
376        let title = guide.title.as_deref().unwrap_or_else(|| scale.name());
377        let title_offset = if !title.is_empty() {
378            theme.legend_title.size + 4.0
379        } else {
380            0.0
381        };
382        // #236: a size legend's key box (and the row height it sits in)
383        // grows to fit its largest key — see `size_key_diameter`.
384        let diameter = size_key_diameter(aes, scales, scale, &breaks);
385        let key_width = theme.legend_key_width.max(diameter);
386        let key_height = theme.legend_key_height.max(key_width);
387        let single_col_width = key_width + theme.legend_spacing + theme.legend_text.size * 6.0;
388        let is_continuous_bar =
389            matches!(aes, Aesthetic::Color | Aesthetic::Fill) && !scale.is_discrete();
390        let (w, h) = if is_continuous_bar {
391            (single_col_width, title_offset + key_height * 8.0)
392        } else if let Some(plan) = legend_plans.get(aes) {
393            let w = if plan.col_pitch > 0.0 {
394                plan.cols as f64 * plan.col_pitch
395            } else {
396                single_col_width
397            };
398            (w, title_offset + plan.rows as f64 * key_height)
399        } else {
400            (
401                single_col_width,
402                title_offset + breaks.len() as f64 * key_height,
403            )
404        };
405        total_h += h;
406        max_w = max_w.max(w);
407    }
408    (max_w, total_h)
409}
410
411/// Clamp a `[pos, pos + size]` span inside `[lo, hi]` — `pos` alone when
412/// `size` already overflows `[lo, hi]` (a legend taller/wider than the
413/// canvas: nothing to do but left/top-align it and let it overflow, same
414/// as #225's old unconditional top-left anchor did for every `Inside`
415/// legend).
416fn clamp_span(pos: f64, size: f64, lo: f64, hi: f64) -> f64 {
417    if size >= hi - lo {
418        lo
419    } else {
420        pos.clamp(lo, hi - size)
421    }
422}
423
424/// Compute legend origin based on position setting.
425///
426/// `legend_extra_rows` is #233's `LayoutExtras::legend_extra_rows` — a
427/// horizontal legend wrapped onto more than one row by `plan_legend`'s
428/// auto-wrap/explicit grid. Only `Top` reads it: `PlotLayout::
429/// compute_with_extras` reserves a `legend_band_height` row directly
430/// above `plot_area` (ending exactly at `plot_area.y`), so backing off
431/// `plot_area.y` by that same band content (everything but
432/// `legend_margin.top`, which is the gap *above* where drawing starts)
433/// lands the legend's first row exactly inside its reserved band — after
434/// the title/subtitle and the plot's own outer margin, rather than
435/// #233's bug (an absolute-from-canvas-origin `legend_margin.top`,
436/// overlapping both).
437///
438/// `legend_size_hint` (#225) is the legend's own estimated `(width,
439/// height)` — see `estimate_legend_box` — read only by `Inside`. ggplot2
440/// defaults `legend.justification.inside` to `legend.position.inside`:
441/// the legend's own fractional point `(fx, fy)` (measured from its own
442/// bottom-left, in the same `0..=1` convention `Inside`'s `(fx, fy)`
443/// already uses) lands exactly on the panel's point `(fx, fy)`, rather
444/// than always anchoring the legend's top-left corner there (#225's
445/// bug: a legend taller than roughly `(1 - fy) * plot_area.height` —
446/// trivially true for a tall continuous colourbar near `fy = 0`, "near
447/// the bottom" — ran off the canvas, and a discrete legend with enough
448/// levels did exactly the same). `canvas` is a last-resort clamp for a
449/// legend taller or wider than the *panel*: still on the canvas, even if
450/// that means spilling outside the panel itself.
451///
452/// Every other position ignores `legend_size_hint`; callers that don't
453/// have a real estimate in hand (the deprecated `draw_legend`, or where
454/// the returned `y` is unused) pass `(0.0, 0.0)` and `plot_area` itself
455/// as `canvas` — harmless, since neither matters there.
456///
457/// Returns (x, y, is_horizontal).
458pub(crate) fn legend_position(
459    theme: &Theme,
460    plot_area: &Rect,
461    legend_extra_rows: usize,
462    legend_size_hint: (f64, f64),
463    canvas: &Rect,
464) -> (f64, f64, bool) {
465    match theme.legend_position {
466        LegendPosition::Right => (
467            plot_area.x + plot_area.width + theme.legend_margin.left,
468            plot_area.y + theme.legend_margin.top,
469            false,
470        ),
471        LegendPosition::Left => (
472            theme.legend_margin.left,
473            plot_area.y + theme.legend_margin.top,
474            false,
475        ),
476        LegendPosition::Top => (
477            plot_area.x + theme.legend_margin.left,
478            plot_area.y - legend_band_height(theme, legend_extra_rows) + theme.legend_margin.top,
479            true,
480        ),
481        LegendPosition::Bottom => (
482            plot_area.x + theme.legend_margin.left,
483            // Below the x axis — at most the 30px it used to assume, so an
484            // axis-less theme (`theme_void`) keeps the legend inside the band
485            // the layout reserved rather than off the canvas (#341).
486            plot_area.y
487                + plot_area.height
488                + theme.legend_margin.top
489                + crate::render::layout::PlotLayout::x_axis_band(theme, None).min(30.0),
490            true,
491        ),
492        LegendPosition::None => (0.0, 0.0, false),
493        LegendPosition::Inside(fx, fy) => {
494            let (legend_w, legend_h) = legend_size_hint;
495            let raw_x = plot_area.x + fx * (plot_area.width - legend_w);
496            // fy = 1 is the panel's top in ggplot-rs's convention (y grows
497            // down in SVG space, same flip the old formula already had).
498            let raw_y = plot_area.y + (1.0 - fy) * (plot_area.height - legend_h);
499            let x = clamp_span(raw_x, legend_w, canvas.x, canvas.x + canvas.width);
500            let y = clamp_span(raw_y, legend_h, canvas.y, canvas.y + canvas.height);
501            (x, y, false)
502        }
503    }
504}
505
506/// For an `Aesthetic::Size` scale, the largest mapped key's diameter
507/// across `breaks` (#236: ggplot2 draws each size key at its break's own
508/// mapped size and grows the key box to fit the largest one, rather than
509/// clamping every key to the fixed default swatch size — which made
510/// every key past a certain size draw identically, the reported bug).
511/// `0.0` for every other aesthetic, or if every mapped size already fits
512/// the theme's default `legend_key_width`, so a caller can just `.max()`
513/// it into the usual fixed size with no special-casing and no change to
514/// existing output when nothing needs the extra room.
515pub(crate) fn size_key_diameter(
516    aes: &Aesthetic,
517    scales: &ScaleSet,
518    scale: &dyn crate::scale::Scale,
519    breaks: &[(f64, String)],
520) -> f64 {
521    if *aes != Aesthetic::Size {
522        return 0.0;
523    }
524    let max_r = breaks
525        .iter()
526        .map(|(pos, label)| {
527            scale
528                .map_fraction_to_size(*pos)
529                .or_else(|| scales.map_size(&Value::Str(label.clone())))
530                .unwrap_or(3.0)
531        })
532        .fold(0.0_f64, f64::max);
533    max_r * 2.0
534}
535
536/// Draw a discrete legend at a given position. Returns the height used.
537#[allow(clippy::too_many_arguments)]
538/// Draw one discrete legend — or, when `group` has more than one entry
539/// (#239: guide merging), one *combined* legend whose every key overlays
540/// each aesthetic's own glyph at the same position (e.g. a filled swatch
541/// with a mapped-colour outline), the way ggplot2 merges `fill` and
542/// `colour` guides mapped to the same measure through the same scale
543/// spec into one legend instead of two. `group[0]` is the representative
544/// scale for the title, breaks and labels — `group_mergeable_legends`
545/// only ever groups aesthetics whose `breaks()` (and so their shared
546/// title) are already identical, so any member would do.
547fn draw_discrete_legend_at(
548    scales: &ScaleSet,
549    group: &[(Aesthetic, &dyn crate::scale::Scale)],
550    theme: &Theme,
551    legend_x: f64,
552    legend_y: f64,
553    backend: &mut dyn DrawBackend,
554    guide: &GuideLegend,
555    is_horizontal: bool,
556) -> Result<f64, RenderError> {
557    let (_, scale) = &group[0];
558    let mut breaks = scale.breaks();
559    if breaks.is_empty() {
560        return Ok(0.0);
561    }
562
563    // Apply guide reverse
564    if guide.reverse {
565        breaks.reverse();
566    }
567
568    // #236: a size legend's key box (and the row height it sits in) grows
569    // to fit its largest key — see `size_key_diameter`. A no-op (both
570    // `.max()`s keep the theme defaults) for every other aesthetic, and
571    // for a size legend whose largest key already fits them. At most one
572    // `group` member is ever `Aesthetic::Size` (`LEGEND_AESTHETICS` has
573    // only one), so taking the max across the group is exactly the same
574    // as the single-aesthetic case when `group.len() == 1`.
575    let diameter = group
576        .iter()
577        .map(|(a, s)| size_key_diameter(a, scales, *s, &breaks))
578        .fold(0.0_f64, f64::max);
579    let swatch_size = theme.legend_key_width.max(diameter);
580    let item_height = theme.legend_key_height.max(swatch_size);
581
582    // Draw legend title (guide title overrides scale name)
583    let title = guide.title.as_deref().unwrap_or_else(|| scale.name());
584    let legend_family = if theme.legend_title.family.is_empty() {
585        None
586    } else {
587        Some(theme.legend_title.family.clone())
588    };
589    let title_offset = if !title.is_empty() {
590        backend.draw_text(
591            title,
592            (legend_x, legend_y),
593            &TextStyle {
594                color: theme.legend_title.color,
595                size: theme.legend_title.size,
596                anchor: TextAnchor::Start,
597                angle: 0.0,
598                family: legend_family,
599                face: theme.legend_title.face,
600                bg_colour: None,
601                bg_r: 0.0,
602            },
603        )?;
604        theme.legend_title.size + 4.0
605    } else {
606        0.0
607    };
608
609    let items_y = legend_y + title_offset;
610
611    // Draw legend background
612    if theme.legend_background.visible {
613        let total_height = breaks.len() as f64 * item_height;
614        let total_width = swatch_size + theme.legend_spacing + theme.legend_text.size * 6.0;
615        if let Some(fill) = theme.legend_background.fill {
616            backend.draw_rect(
617                (legend_x - 2.0, items_y - 2.0),
618                (legend_x + total_width + 2.0, items_y + total_height + 2.0),
619                &RectStyle {
620                    fill: Some(fill),
621                    stroke: theme.legend_background.color,
622                    stroke_width: theme.legend_background.width,
623                    alpha: 1.0,
624                    clip: false,
625                    corner_radius: 0.0,
626                },
627            )?;
628        }
629    }
630
631    // Horizontal legends lay keys left-to-right; vertical ones stack downward.
632    let mut cur_x = legend_x;
633    for (i, (pos, label)) in breaks.iter().enumerate() {
634        let x = if is_horizontal { cur_x } else { legend_x };
635        let y = if is_horizontal {
636            items_y
637        } else {
638            items_y + i as f64 * item_height
639        };
640        let center_x = x + swatch_size / 2.0;
641        let center_y = y + swatch_size / 2.0;
642
643        // Draw legend key background
644        if theme.legend_key.visible {
645            if let Some(fill) = theme.legend_key.fill {
646                backend.draw_rect(
647                    (x, y),
648                    (x + swatch_size, y + swatch_size),
649                    &RectStyle {
650                        fill: Some(fill),
651                        stroke: theme.legend_key.color,
652                        stroke_width: theme.legend_key.width,
653                        alpha: 1.0,
654                        clip: false,
655                        corner_radius: 0.0,
656                    },
657                )?;
658            }
659        }
660
661        // Draw every group member's own glyph, overlaid at the same
662        // position (#239) — a single swatch for the common, unmerged
663        // case (`group.len() == 1`).
664        for (member_aes, member_scale) in group {
665            draw_legend_swatch(
666                backend,
667                scales,
668                member_aes,
669                *member_scale,
670                theme,
671                label,
672                *pos,
673                x,
674                y,
675                center_x,
676                center_y,
677                swatch_size,
678            )?;
679        }
680
681        // Label
682        let label_family = if theme.legend_text.family.is_empty() {
683            None
684        } else {
685            Some(theme.legend_text.family.clone())
686        };
687        backend.draw_text(
688            label,
689            (x + swatch_size + theme.legend_spacing, center_y),
690            &TextStyle {
691                color: theme.legend_text.color,
692                size: theme.legend_text.size,
693                anchor: TextAnchor::Start,
694                angle: 0.0,
695                family: label_family,
696                face: theme.legend_text.face,
697                bg_colour: None,
698                bg_r: 0.0,
699            },
700        )?;
701        if is_horizontal {
702            // advance past swatch + spacing + estimated label width + gap
703            cur_x = x
704                + swatch_size
705                + theme.legend_spacing
706                + (label.chars().count() as f64) * theme.legend_text.size * 0.62
707                + theme.legend_spacing * 3.0;
708        }
709    }
710
711    if is_horizontal {
712        Ok(cur_x - legend_x) // width used
713    } else {
714        Ok(title_offset + breaks.len() as f64 * item_height)
715    }
716}
717
718/// #211: the bar's own `(length, thickness)` in pixels for a continuous
719/// colorbar — vertical keeps the original tall-and-narrow dims
720/// (`legend_key_width` thick, `legend_key_height * 8.0` long); horizontal
721/// swaps them (ggplot2's `guide_colourbar(direction = "horizontal")`),
722/// so the bar is wide-and-short instead. Shared by
723/// [`draw_continuous_legend_at`] (the real draw) and
724/// [`continuous_horizontal_bar_height`] (the layout-time estimate), so
725/// the two can't disagree.
726fn continuous_bar_dims(theme: &Theme, is_horizontal: bool) -> (f64, f64) {
727    if is_horizontal {
728        (theme.legend_key_height * 8.0, theme.legend_key_width)
729    } else {
730        (theme.legend_key_width, theme.legend_key_height * 8.0)
731    }
732}
733
734/// #211: the total height a *horizontal* continuous colorbar consumes —
735/// title line (if `has_title`) + bar thickness + its tick marks + one
736/// line of labels below. Used by `plot.rs` to reserve the Top/Bottom
737/// legend band's height before layout runs; mirrors
738/// [`draw_continuous_legend_at`]'s own math exactly so the reserved band
739/// and the actual draw can't disagree.
740pub(crate) fn continuous_horizontal_bar_height(theme: &Theme, has_title: bool) -> f64 {
741    let title_offset = if has_title {
742        theme.legend_title.size + 4.0
743    } else {
744        0.0
745    };
746    let (_, bar_thickness) = continuous_bar_dims(theme, true);
747    let tick_len = 3.0;
748    let label_line = theme.legend_text.size + 4.0;
749    title_offset + bar_thickness + tick_len + theme.legend_spacing + label_line
750}
751
752/// Draw a continuous colorbar legend at a given position. `is_horizontal`
753/// (#211) draws it wide × short — bar slices left to right from the
754/// scale's min to max, ticks/labels below the bar, matching ggplot2's
755/// `guide_colourbar(direction = "horizontal")` — instead of the default
756/// tall × narrow bar with ticks/labels to its right. Returns the height
757/// used.
758fn draw_continuous_legend_at(
759    scale: &dyn crate::scale::Scale,
760    theme: &Theme,
761    legend_x: f64,
762    legend_y: f64,
763    backend: &mut dyn DrawBackend,
764    guide: &GuideLegend,
765    is_horizontal: bool,
766) -> Result<f64, RenderError> {
767    let breaks = scale.breaks();
768    if breaks.is_empty() {
769        return Ok(0.0);
770    }
771
772    let (bar_width, bar_height) = continuous_bar_dims(theme, is_horizontal);
773
774    // Draw legend title (guide title overrides scale name)
775    let title = guide.title.as_deref().unwrap_or_else(|| scale.name());
776    let cont_family = if theme.legend_title.family.is_empty() {
777        None
778    } else {
779        Some(theme.legend_title.family.clone())
780    };
781    let title_offset = if !title.is_empty() {
782        backend.draw_text(
783            title,
784            (legend_x, legend_y),
785            &TextStyle {
786                color: theme.legend_title.color,
787                size: theme.legend_title.size,
788                anchor: TextAnchor::Start,
789                angle: 0.0,
790                family: cont_family,
791                face: theme.legend_title.face,
792                bg_colour: None,
793                bg_r: 0.0,
794            },
795        )?;
796        theme.legend_title.size + 4.0
797    } else {
798        0.0
799    };
800
801    let bar_top = legend_y + title_offset;
802
803    // Draw legend background
804    if theme.legend_background.visible {
805        let total_width = if is_horizontal {
806            bar_width
807        } else {
808            bar_width + theme.legend_spacing + theme.legend_text.size * 6.0
809        };
810        let total_height = if is_horizontal {
811            bar_height + theme.legend_spacing + theme.legend_text.size * 2.0
812        } else {
813            bar_height
814        };
815        if let Some(fill) = theme.legend_background.fill {
816            backend.draw_rect(
817                (legend_x - 2.0, bar_top - 2.0),
818                (legend_x + total_width + 2.0, bar_top + total_height + 2.0),
819                &RectStyle {
820                    fill: Some(fill),
821                    stroke: theme.legend_background.color,
822                    stroke_width: theme.legend_background.width,
823                    alpha: 1.0,
824                    clip: false,
825                    corner_radius: 0.0,
826                },
827            )?;
828        }
829    }
830
831    // Draw gradient bar as N thin slices — stacked top to bottom (max at
832    // the top) when vertical, side by side left to right (min on the
833    // left, like an x-axis) when horizontal.
834    // Use data-domain values to avoid double-normalization in map_to_color()
835    let (data_min, data_max) = scale.domain().unwrap_or((0.0, 1.0));
836    let n_slices = 50;
837    if is_horizontal {
838        let slice_width = bar_width / n_slices as f64;
839        for i in 0..n_slices {
840            let t = i as f64 / n_slices as f64;
841            let data_val = data_min + t * (data_max - data_min);
842            let color = scale
843                .map_to_color(&Value::Float(data_val))
844                .unwrap_or((127, 127, 127));
845            let sx = legend_x + i as f64 * slice_width;
846            backend.draw_rect(
847                (sx, bar_top),
848                (sx + slice_width + 0.5, bar_top + bar_height),
849                &RectStyle {
850                    fill: Some(color),
851                    stroke: None,
852                    stroke_width: 0.0,
853                    alpha: 1.0,
854                    clip: false,
855                    corner_radius: 0.0,
856                },
857            )?;
858        }
859    } else {
860        let slice_height = bar_height / n_slices as f64;
861        for i in 0..n_slices {
862            let t = 1.0 - i as f64 / n_slices as f64;
863            let data_val = data_min + t * (data_max - data_min);
864            let color = scale
865                .map_to_color(&Value::Float(data_val))
866                .unwrap_or((127, 127, 127));
867            let sy = bar_top + i as f64 * slice_height;
868            backend.draw_rect(
869                (legend_x, sy),
870                (legend_x + bar_width, sy + slice_height + 0.5),
871                &RectStyle {
872                    fill: Some(color),
873                    stroke: None,
874                    stroke_width: 0.0,
875                    alpha: 1.0,
876                    clip: false,
877                    corner_radius: 0.0,
878                },
879            )?;
880        }
881    }
882
883    // Draw border
884    // (Ticks reuse its colour and width even when the frame is hidden.)
885    let border = theme.legend_bar_border_line();
886    let border_style = LineStyle {
887        color: border.color,
888        width: border.width,
889        alpha: 1.0,
890        linetype: border.linetype,
891        ..Default::default()
892    };
893    if border.visible {
894        backend.draw_line(
895            &[
896                (legend_x, bar_top),
897                (legend_x + bar_width, bar_top),
898                (legend_x + bar_width, bar_top + bar_height),
899                (legend_x, bar_top + bar_height),
900                (legend_x, bar_top),
901            ],
902            &border_style,
903        )?;
904    }
905
906    // Draw tick marks and labels: to the bar's right (vertical, pos=1 at
907    // the top) or below it (horizontal, pos=0 on the left), matching the
908    // slice order drawn above.
909    let tick_len = 3.0;
910    let tick_family = if theme.legend_text.family.is_empty() {
911        None
912    } else {
913        Some(theme.legend_text.family.clone())
914    };
915    for (pos, label) in &breaks {
916        if is_horizontal {
917            let tick_x = legend_x + bar_width * pos;
918            backend.draw_line(
919                &[
920                    (tick_x, bar_top + bar_height),
921                    (tick_x, bar_top + bar_height + tick_len),
922                ],
923                &border_style,
924            )?;
925            backend.draw_text(
926                label,
927                (
928                    tick_x,
929                    bar_top + bar_height + tick_len + theme.legend_text.size,
930                ),
931                &TextStyle {
932                    color: theme.legend_text.color,
933                    size: theme.legend_text.size,
934                    anchor: TextAnchor::Middle,
935                    angle: 0.0,
936                    family: tick_family.clone(),
937                    face: theme.legend_text.face,
938                    bg_colour: None,
939                    bg_r: 0.0,
940                },
941            )?;
942        } else {
943            let tick_y = bar_top + bar_height * (1.0 - pos);
944            backend.draw_line(
945                &[
946                    (legend_x + bar_width, tick_y),
947                    (legend_x + bar_width + tick_len, tick_y),
948                ],
949                &border_style,
950            )?;
951            backend.draw_text(
952                label,
953                (
954                    legend_x + bar_width + tick_len + theme.legend_spacing,
955                    tick_y,
956                ),
957                &TextStyle {
958                    color: theme.legend_text.color,
959                    size: theme.legend_text.size,
960                    anchor: TextAnchor::Start,
961                    angle: 0.0,
962                    family: tick_family.clone(),
963                    face: theme.legend_text.face,
964                    bg_colour: None,
965                    bg_r: 0.0,
966                },
967            )?;
968        }
969    }
970
971    if is_horizontal {
972        Ok(continuous_horizontal_bar_height(theme, !title.is_empty()))
973    } else {
974        Ok(title_offset + bar_height)
975    }
976}
977
978/// Draw one legend key's swatch (not its label) for `aes`, at `(x, y)`
979/// (top-left) / `(center_x, center_y)` (centre), `swatch_size` square.
980/// Shared by the unchanged [`draw_discrete_legend_at`] and the B3-2
981/// planner-driven [`draw_legend_planned`], so both draw pixel-identical
982/// swatches.
983///
984/// A key with no aesthetic-mapped colour of its own (`Shape`, `Linetype`,
985/// `Size`, `Alpha`, `Linewidth` — `Color`/`Fill` always have one, from
986/// `scales.map_color`) falls back to `theme.geom.ink`, then
987/// `theme.legend_text.color` (#237: a *fixed* dark grey here was almost
988/// invisible on a dark panel in a theme that sets `legend_text.color`
989/// for readability but never thought to also set the less commonly used
990/// `geom.ink`) — the same two-tier fallback `GeomPoint`/`GeomText`'s own
991/// `apply_element_geom` effectively uses for an unmapped panel mark
992/// (`ink` if the theme sets it, otherwise its own default), extended one
993/// more tier since a key glyph has no mapped colour of its own to start
994/// from the way a panel mark's default colour does. **Visible default
995/// change:** the base theme's `legend_text.color` is pure black
996/// (`(0, 0, 0)`), not the old fallback's dark grey (`(50, 50, 50)`) — a
997/// small, intentional difference (documented in the CHANGELOG), not a
998/// behaviour-preserving refactor.
999#[allow(clippy::too_many_arguments)]
1000fn draw_legend_swatch(
1001    backend: &mut dyn DrawBackend,
1002    scales: &ScaleSet,
1003    aes: &Aesthetic,
1004    scale: &dyn crate::scale::Scale,
1005    theme: &Theme,
1006    label: &str,
1007    pos: f64,
1008    x: f64,
1009    y: f64,
1010    center_x: f64,
1011    center_y: f64,
1012    swatch_size: f64,
1013) -> Result<(), RenderError> {
1014    let value = Value::Str(label.to_string());
1015    match aes {
1016        Aesthetic::Color | Aesthetic::Fill => {
1017            let color = scales.map_color(aes, &value).unwrap_or((127, 127, 127));
1018            let style = RectStyle {
1019                fill: Some(color),
1020                stroke: None,
1021                stroke_width: 0.0,
1022                alpha: 1.0,
1023                clip: false,
1024                corner_radius: 0.0,
1025            };
1026            // #206: the "no data" key draws its scale's na_pattern
1027            // instead of a flat swatch, when set.
1028            if scale.is_na_break(label) {
1029                if let Some(p) = scale.na_fill_pattern() {
1030                    return backend.draw_rect_pattern(
1031                        (x, y),
1032                        (x + swatch_size, y + swatch_size),
1033                        &p,
1034                        &style,
1035                    );
1036                }
1037            }
1038            backend.draw_rect((x, y), (x + swatch_size, y + swatch_size), &style)?;
1039        }
1040        Aesthetic::Shape => {
1041            let shape = scales
1042                .map_shape(&value)
1043                .unwrap_or(crate::render::backend::PointShape::Circle);
1044            backend.draw_shape(
1045                (center_x, center_y),
1046                swatch_size / 3.0,
1047                &PointStyle {
1048                    color: theme.geom.ink.unwrap_or(theme.legend_text.color),
1049                    alpha: 1.0,
1050                    filled: true,
1051                    shape,
1052                },
1053            )?;
1054        }
1055        Aesthetic::Linetype => {
1056            let lt = scales.map_linetype(&value).unwrap_or(Linetype::Solid);
1057            backend.draw_line(
1058                &[(x + 2.0, center_y), (x + swatch_size - 2.0, center_y)],
1059                &LineStyle {
1060                    color: theme.geom.ink.unwrap_or(theme.legend_text.color),
1061                    width: 1.5,
1062                    alpha: 1.0,
1063                    linetype: lt,
1064                    ..Default::default()
1065                },
1066            )?;
1067        }
1068        Aesthetic::Size => {
1069            let size = scale
1070                .map_fraction_to_size(pos)
1071                .or_else(|| scales.map_size(&value))
1072                .unwrap_or(3.0);
1073            backend.draw_shape(
1074                (center_x, center_y),
1075                size.min(swatch_size / 2.0),
1076                &PointStyle {
1077                    color: theme.geom.ink.unwrap_or(theme.legend_text.color),
1078                    alpha: 1.0,
1079                    filled: true,
1080                    shape: crate::render::backend::PointShape::Circle,
1081                },
1082            )?;
1083        }
1084        Aesthetic::Alpha => {
1085            let alpha = scale
1086                .map_fraction_to_alpha(pos)
1087                .or_else(|| scales.map_alpha(&value))
1088                .unwrap_or(1.0);
1089            backend.draw_rect(
1090                (x, y),
1091                (x + swatch_size, y + swatch_size),
1092                &RectStyle {
1093                    fill: Some(theme.geom.ink.unwrap_or(theme.legend_text.color)),
1094                    stroke: None,
1095                    stroke_width: 0.0,
1096                    alpha,
1097                    clip: false,
1098                    corner_radius: 0.0,
1099                },
1100            )?;
1101        }
1102        Aesthetic::Linewidth => {
1103            let width = scale.map_fraction_to_size(pos).unwrap_or(1.0);
1104            backend.draw_line(
1105                &[(x + 2.0, center_y), (x + swatch_size - 2.0, center_y)],
1106                &LineStyle {
1107                    color: theme.geom.ink.unwrap_or(theme.legend_text.color),
1108                    width: width.min(swatch_size),
1109                    alpha: 1.0,
1110                    linetype: Linetype::Solid,
1111                    ..Default::default()
1112                },
1113            )?;
1114        }
1115        _ => {}
1116    }
1117    Ok(())
1118}
1119
1120// ─── B3-2: nrow/ncol/byrow, auto-wrap, "+N more" ───────────────────────────
1121
1122/// One legend key's grid placement, in the planner's own pixel space
1123/// (relative to the legend's own origin — `row` is 0-indexed top row,
1124/// `x_offset` is the horizontal pitch from the first column).
1125#[derive(Clone, Debug)]
1126pub(crate) struct LegendEntry {
1127    pub break_idx: usize,
1128    pub row: usize,
1129    pub x_offset: f64,
1130    /// A truncated-with-ellipsis display label (#159), set only when a
1131    /// vertical multi-column grid still doesn't fit the canvas after
1132    /// reducing its column count as far as it can go: the full label is
1133    /// still available (e.g. for a `<title>` tooltip) via the scale's own
1134    /// `breaks()[break_idx]`. `None` draws the break's label unchanged —
1135    /// the common, byte-identical case.
1136    pub label_override: Option<String>,
1137}
1138
1139/// A trailing "+{k} more" marker when the legend doesn't have room for
1140/// every key (D7). Not a mark (`draw_text` only — no swatch, no
1141/// `data-geom`/class).
1142#[derive(Clone, Debug)]
1143pub(crate) struct LegendOverflow {
1144    pub dropped: usize,
1145    pub row: usize,
1146    pub x_offset: f64,
1147    pub text: String,
1148}
1149
1150/// A non-default legend layout (B3-2): an explicit `nrow`/`ncol` grid, or
1151/// an auto-wrapped horizontal legend. `None` from [`plan_legend`] means
1152/// "nothing changes" — the caller keeps the 0.21 single-row/single-column
1153/// path verbatim, so a plot that doesn't need this is byte-identical.
1154#[derive(Clone, Debug)]
1155pub(crate) struct LegendPlan {
1156    pub rows: usize,
1157    pub entries: Vec<LegendEntry>,
1158    pub overflow: Option<LegendOverflow>,
1159    /// Columns in an explicit grid (always 1 for the horizontal auto-wrap
1160    /// path, which never adds columns). Review #158 finding 3: a vertical
1161    /// legend with `ncol > 1` needs `(cols − 1) · col_pitch` of extra
1162    /// width reserved, the same way extra rows are reserved for height.
1163    pub cols: usize,
1164    /// The per-column horizontal pitch an explicit grid uses (0 for the
1165    /// auto-wrap path, which doesn't have columns in this sense).
1166    pub col_pitch: f64,
1167}
1168
1169/// Per-key horizontal pitch (swatch + spacing + label + gap): the larger of
1170/// today's crude per-character advance (`draw_discrete_legend_at`'s
1171/// `cur_x` formula) and a `text_width`-based measurement, so a label that
1172/// ties under both estimates stays on the byte-identical single-row path.
1173fn legend_pitch(label: &str, theme: &Theme) -> f64 {
1174    let swatch = theme.legend_key_width;
1175    let spacing = theme.legend_spacing;
1176    let text_size = theme.legend_text.size;
1177    let legacy =
1178        swatch + spacing + (label.chars().count() as f64) * text_size * 0.62 + spacing * 3.0;
1179    let measured = swatch + spacing + crate::render::text::text_width(label, text_size) + 8.0;
1180    legacy.max(measured)
1181}
1182
1183/// Plan a non-default legend layout (B3-2, D7). `avail_width` is the
1184/// horizontal room for a horizontal legend's flow-pack / overflow check
1185/// (`plot_area.x + plot_area.width - legend_x`); `avail_height` only feeds
1186/// the default `max_rows` formula. Returns `None` when nothing changes:
1187/// no explicit `nrow`/`ncol`, and (for a horizontal legend) the one-line
1188/// layout already fits — or the legend is vertical, where auto-wrap never
1189/// applies (D7 is horizontal-only; `nrow`/`ncol` still work on either).
1190pub(crate) fn plan_legend(
1191    breaks: &[(f64, String)],
1192    guide: &GuideLegend,
1193    theme: &Theme,
1194    avail_width: f64,
1195    avail_height: f64,
1196    is_horizontal: bool,
1197) -> Option<LegendPlan> {
1198    let n = breaks.len();
1199    if n == 0 {
1200        return None;
1201    }
1202
1203    // Explicit grid: ggplot2's `nrow`/`ncol`, column-major unless `byrow`.
1204    if guide.nrow.is_some() || guide.ncol.is_some() {
1205        let (rows, cols) = match (guide.nrow, guide.ncol) {
1206            (Some(nrow), Some(ncol)) => (nrow, ncol),
1207            (Some(nrow), None) => (nrow.max(1), n.div_ceil(nrow.max(1))),
1208            (None, Some(ncol)) => (n.div_ceil(ncol.max(1)), ncol.max(1)),
1209            (None, None) => unreachable!("checked above"),
1210        };
1211        let rows = rows.max(1);
1212        let cols = cols.max(1);
1213        let col_pitch = breaks
1214            .iter()
1215            .map(|(_, l)| legend_pitch(l, theme))
1216            .fold(0.0_f64, f64::max);
1217        let entries = (0..n)
1218            .map(|i| {
1219                let (row, col) = if guide.byrow {
1220                    (i / cols, i % cols)
1221                } else {
1222                    (i % rows, i / rows)
1223                };
1224                LegendEntry {
1225                    break_idx: i,
1226                    row,
1227                    x_offset: col as f64 * col_pitch,
1228                    label_override: None,
1229                }
1230            })
1231            .collect();
1232        return Some(LegendPlan {
1233            rows,
1234            entries,
1235            overflow: None,
1236            cols,
1237            col_pitch,
1238        });
1239    }
1240
1241    // Auto mode: D7 scopes auto-wrap to horizontal legends only.
1242    if !is_horizontal {
1243        return None;
1244    }
1245
1246    let pitches: Vec<f64> = breaks.iter().map(|(_, l)| legend_pitch(l, theme)).collect();
1247    let total_width: f64 = pitches.iter().sum();
1248    if total_width <= avail_width.max(0.0) {
1249        return None; // fits on one line — byte-identical to 0.21.
1250    }
1251
1252    let item_height = theme.legend_key_height.max(1.0);
1253    let row_limit = guide
1254        .max_rows
1255        .unwrap_or_else(|| 1 + (avail_height / 3.0 / item_height).floor().max(0.0) as usize)
1256        .max(1);
1257
1258    let mut entries: Vec<LegendEntry> = Vec::with_capacity(n);
1259    let mut row = 0usize;
1260    let mut cur_x = 0.0_f64;
1261    for (i, &p) in pitches.iter().enumerate() {
1262        if cur_x > 0.0 && cur_x + p > avail_width {
1263            if row + 1 >= row_limit {
1264                break; // out of rows — the rest overflow into "+N more".
1265            }
1266            row += 1;
1267            cur_x = 0.0;
1268        }
1269        entries.push(LegendEntry {
1270            break_idx: i,
1271            row,
1272            x_offset: cur_x,
1273            label_override: None,
1274        });
1275        cur_x += p;
1276    }
1277
1278    if entries.len() >= n {
1279        return Some(LegendPlan {
1280            rows: row + 1,
1281            entries,
1282            overflow: None,
1283            cols: 1,
1284            col_pitch: 0.0,
1285        });
1286    }
1287
1288    // Overflow: make room for "+{k} more" on the last row, dropping
1289    // entries from its tail until it fits (or the row is empty).
1290    let mut dropped = n - entries.len();
1291    loop {
1292        let text = format!("+{dropped} more");
1293        let more_pitch = legend_pitch(&text, theme);
1294        let row_count = entries.iter().filter(|e| e.row == row).count();
1295        let last_x = entries
1296            .iter()
1297            .filter(|e| e.row == row)
1298            .map(|e| e.x_offset + pitches[e.break_idx])
1299            .fold(0.0_f64, f64::max);
1300        if last_x + more_pitch <= avail_width || row_count == 0 {
1301            return Some(LegendPlan {
1302                rows: row + 1,
1303                entries,
1304                overflow: Some(LegendOverflow {
1305                    dropped,
1306                    row,
1307                    x_offset: last_x,
1308                    text,
1309                }),
1310                cols: 1,
1311                col_pitch: 0.0,
1312            });
1313        }
1314        entries.pop();
1315        dropped += 1;
1316    }
1317}
1318
1319/// `Color`/`Fill` are the only aesthetics whose *continuous* legend draws
1320/// as an actual colourbar (`draw_continuous_legend_at`, fixed width). Every
1321/// other continuous legend (`Size`, `Linewidth`, `Alpha`, …) draws sampled
1322/// breaks the same way a discrete guide's keys do
1323/// (`draw_discrete_legend_at` / `draw_discrete_legend_grid`), so it needs
1324/// the same B3-2 wrap/grid planning a discrete guide gets rather than a
1325/// fixed-width reservation — sipemu/ggplot-rs#545: previously this wasn't
1326/// planned *at all*, so a `Size`/`Linewidth` legend with enough keys to
1327/// overflow a narrow `Top`/`Bottom` row just drew past the panel/canvas
1328/// edge with no wrap, shrink, or "+N more" to catch it.
1329pub(crate) fn is_colorbar_aesthetic(aes: &Aesthetic) -> bool {
1330    matches!(aes, Aesthetic::Color | Aesthetic::Fill)
1331}
1332
1333/// How many of a plot's legend scales get B3-2's wrap/grid planning — every
1334/// discrete guide, plus a continuous guide that isn't a colourbar (#545:
1335/// its sampled breaks wrap/shrink exactly like a discrete guide's keys do)
1336/// — used to split the available horizontal room among them when several
1337/// sit side by side (sipemu/ggplot-rs#155).
1338fn wrap_guide_count(scales: &ScaleSet, legend_scales: &[Aesthetic]) -> usize {
1339    legend_scales
1340        .iter()
1341        .filter(|aes| {
1342            let is_discrete = scales.get(aes).map(|s| s.is_discrete()).unwrap_or(false);
1343            is_discrete || !is_colorbar_aesthetic(aes)
1344        })
1345        .count()
1346        .max(1)
1347}
1348
1349/// How many of a plot's legend scales are a true colourbar (a continuous
1350/// `Color`/`Fill` scale) — each reserves its own fixed width share of a
1351/// horizontal row (#170 / review #167 finding 7: a bottom legend mixing a
1352/// colourbar with a discrete guide ignored the colourbar's share, so the
1353/// discrete guide's auto-wrap/grid was planned against the *whole* row and
1354/// could still run off the right edge).
1355fn colorbar_guide_count(scales: &ScaleSet, legend_scales: &[Aesthetic]) -> usize {
1356    legend_scales
1357        .iter()
1358        .filter(|aes| {
1359            is_colorbar_aesthetic(aes) && !scales.get(aes).map(|s| s.is_discrete()).unwrap_or(false)
1360        })
1361        .count()
1362}
1363
1364/// The fixed horizontal width one colourbar guide reserves in a
1365/// horizontal row — the same per-guide step `draw_legend_planned` already
1366/// advances `offset_x` by once it has drawn one (see its `is_horizontal`
1367/// arm for a colourbar).
1368fn colorbar_guide_width(theme: &Theme) -> f64 {
1369    // #211: only used where a colourbar guide shares a *horizontal* row
1370    // with another one — its footprint there is the horizontal bar's
1371    // own length (ticks/labels sit below it now, not to its side), the
1372    // same width `draw_legend_planned` steps `offset_x` by.
1373    let (bar_len, _) = continuous_bar_dims(theme, true);
1374    bar_len + theme.legend_spacing * 2.0
1375}
1376
1377/// Plan every wrap-eligible legend scale's B3-2 layout (explicit
1378/// `nrow`/`ncol` grid, or auto-wrap) independently (sipemu/ggplot-rs#155):
1379/// previously this only ran for the plot's single discrete guide, leaving
1380/// a second simultaneous discrete guide (e.g. both `colour` and `shape`
1381/// mapped to discrete variables) always on the unwrapped 0.21 path. A
1382/// guide is wrap-eligible when it's discrete, or continuous but not a
1383/// colourbar (#545: `Size`/`Linewidth`/… sampled breaks wrap/shrink the
1384/// same way a discrete guide's keys do — only a true continuous
1385/// `Color`/`Fill` colourbar is exempt). When several wrap-eligible guides
1386/// sit side by side (`is_horizontal`), the available width is split evenly
1387/// among them first, so each one wraps against its own share rather than
1388/// the whole row (which would let it claim more room than its neighbours
1389/// leave). Guides that stack vertically instead each get the full
1390/// `avail_width`, since they don't compete for it. Returns one entry per
1391/// wrap-eligible guide that needs anything beyond the single-row/single-
1392/// column path — a guide absent from the map is byte-identical to
1393/// 0.21/0.22.
1394#[allow(clippy::too_many_arguments)]
1395pub(crate) fn plan_all_legends(
1396    scales: &ScaleSet,
1397    guide: &GuideLegend,
1398    theme: &Theme,
1399    suppressed: &std::collections::HashSet<Aesthetic>,
1400    avail_width: f64,
1401    avail_height: f64,
1402    is_horizontal: bool,
1403    warnings: &mut Vec<String>,
1404) -> std::collections::HashMap<Aesthetic, LegendPlan> {
1405    let legend_scales = legend_scales_for(scales, suppressed);
1406    let n_wrap = wrap_guide_count(scales, &legend_scales);
1407    let per_guide_width = if is_horizontal {
1408        // #170: leave the wrap-planned guides only the width left over
1409        // after every colourbar guide's own fixed share (a continuous
1410        // Color/Fill legend sitting in the same row) — previously
1411        // `avail_width` was split among the discrete guides alone, so a
1412        // colourbar plus a discrete guide could together still overflow
1413        // the row. #545: a continuous, non-colourbar guide (e.g. `Size`/
1414        // `Linewidth`) is now one of the guides this width is split among
1415        // too, rather than drawing unconstrained.
1416        let n_colorbar = colorbar_guide_count(scales, &legend_scales);
1417        let colorbar_width = n_colorbar as f64 * colorbar_guide_width(theme);
1418        ((avail_width - colorbar_width) / n_wrap as f64).max(0.0)
1419    } else {
1420        avail_width
1421    };
1422
1423    let mut plans = std::collections::HashMap::new();
1424    for aes in &legend_scales {
1425        let Some(scale) = scales.get(aes) else {
1426            continue;
1427        };
1428        // #545: plan a continuous, non-colourbar guide (`Size`/
1429        // `Linewidth`/… sampled breaks) exactly like a discrete one —
1430        // only a true colourbar (continuous `Color`/`Fill`) is exempt
1431        // from B3-2's wrap/grid planning.
1432        if !scale.is_discrete() && is_colorbar_aesthetic(aes) {
1433            continue;
1434        }
1435        let breaks = scale.breaks();
1436        let validated_guide = guide.validated(breaks.len(), warnings);
1437        // #271: size against `breaks_for_layout()`, not `breaks` itself —
1438        // identical for every scale except `ScaleFillBinned` under
1439        // `count_reserve`, where it reserves width for the widest count
1440        // digit width so the resulting row count doesn't depend on which
1441        // frame's counts happen to be measured.
1442        let layout_breaks = scale.breaks_for_layout();
1443        if let Some(plan) = plan_legend(
1444            &layout_breaks,
1445            &validated_guide,
1446            theme,
1447            per_guide_width,
1448            avail_height,
1449            is_horizontal,
1450        ) {
1451            plans.insert(aes.clone(), plan);
1452        }
1453    }
1454    plans
1455}
1456
1457/// Draw all legends for the plot, honouring each discrete guide's B3-2
1458/// `plan_legend` layout (explicit `nrow`/`ncol`, or an overflowing
1459/// horizontal legend's auto-wrap) when it has one — several simultaneous
1460/// discrete guides each get their own independent plan
1461/// (sipemu/ggplot-rs#155). A guide missing from `legend_plans` falls back
1462/// to the unchanged [`draw_legend`] path — same calls, same order — which
1463/// keeps this byte-identical to 0.21/0.22 for every plot nothing in
1464/// `legend_plans` touches. Used by `renderer.rs` (single and faceted) and
1465/// `compose::capture_legend` (PlotGrid-collected legends).
1466/// An inside legend's own bounding box ([`LegendPosition::Inside`] only —
1467/// every other position reserves a dedicated band outside `plot_area`, so
1468/// it can never overlap panel-corner furniture living inside it), without
1469/// drawing anything (#273). `renderer.rs` calls this *before* any geom
1470/// draws, so a corner-furniture geom drawn first (`annotation_scale`/
1471/// `annotation_attribution`/`bivariate_legend`) can still stack clear of
1472/// where the legend — drawn last, see `draw_legend_planned` — will land.
1473/// Mirrors that function's own prefix (`legend_scales_for` →
1474/// `group_mergeable_legends` → `estimate_legend_box` → `legend_position`,
1475/// with `legend_extra_rows` fixed at `0` since `Inside` never reads it)
1476/// so this never disagrees with where the legend is actually drawn.
1477pub(crate) fn inside_legend_box(
1478    scales: &ScaleSet,
1479    theme: &Theme,
1480    plot_area: &Rect,
1481    canvas: &Rect,
1482    guide: &GuideLegend,
1483    suppressed: &std::collections::HashSet<Aesthetic>,
1484    legend_plans: &std::collections::HashMap<Aesthetic, LegendPlan>,
1485) -> Option<Rect> {
1486    if !matches!(theme.legend_position, LegendPosition::Inside(..)) {
1487        return None;
1488    }
1489    let legend_scales = legend_scales_for(scales, suppressed);
1490    if legend_scales.is_empty() {
1491        return None;
1492    }
1493    let groups = group_mergeable_legends(scales, &legend_scales, guide);
1494    let representatives: Vec<Aesthetic> = groups.iter().map(|g| g[0].clone()).collect();
1495    let legend_size_hint =
1496        estimate_legend_box(scales, &representatives, theme, guide, legend_plans);
1497    let (legend_x, legend_y, _) = legend_position(theme, plot_area, 0, legend_size_hint, canvas);
1498    Some(Rect {
1499        x: legend_x,
1500        y: legend_y,
1501        width: legend_size_hint.0,
1502        height: legend_size_hint.1,
1503    })
1504}
1505
1506#[allow(clippy::too_many_arguments)]
1507pub(crate) fn draw_legend_planned(
1508    scales: &ScaleSet,
1509    theme: &Theme,
1510    plot_area: &Rect,
1511    // Review #167 finding 1: the width share each discrete guide was
1512    // *planned* against (the same `avail_width` passed to
1513    // `plan_all_legends`), not `plot_area.width`. For a single plot these
1514    // are the same value in practice, but a PlotGrid's collected legend
1515    // (`compose::capture_legend`) measures itself against a fake
1516    // zero-width panel so its origin lands at (0, 0) — stepping by
1517    // `plot_area.width / n` there always advanced by zero, so the second
1518    // discrete guide (e.g. `shape` after `colour`) was drawn directly on
1519    // top of the first instead of beside it.
1520    legend_avail_width: f64,
1521    backend: &mut dyn DrawBackend,
1522    guide: &GuideLegend,
1523    suppressed: &std::collections::HashSet<Aesthetic>,
1524    // Review #158 finding 2: each discrete guide's plan, computed exactly
1525    // once in `layout_built` (`BuiltPlot::legend_plans`) — drawn verbatim
1526    // here rather than recomputed against this (possibly shorter, post-
1527    // row-reservation) `plot_area`, so the drawn "+N more" always matches
1528    // the warning that plan already produced.
1529    legend_plans: &std::collections::HashMap<Aesthetic, LegendPlan>,
1530) -> Result<(), RenderError> {
1531    if matches!(theme.legend_position, LegendPosition::None) {
1532        return Ok(());
1533    }
1534
1535    let legend_scales = legend_scales_for(scales, suppressed);
1536    if legend_scales.is_empty() {
1537        return Ok(());
1538    }
1539
1540    // #239: group aesthetics whose legend would be visually identical
1541    // (same title, breaks, discrete/continuous-ness) into one combined
1542    // guide, rather than drawing one per aesthetic. Everything below that
1543    // used to iterate `legend_scales` one aesthetic at a time now
1544    // iterates `groups` instead; a group's first member (`representatives`)
1545    // stands in for the whole group wherever only one scale's own
1546    // breaks/title/discreteness is needed (sizing, the B3-2 wrap plan
1547    // lookup, …) — `group_mergeable_legends` only ever groups scales
1548    // whose `breaks()` already match, so any member would do.
1549    let groups = group_mergeable_legends(scales, &legend_scales, guide);
1550    let representatives: Vec<Aesthetic> = groups.iter().map(|g| g[0].clone()).collect();
1551
1552    // #233: `legend_position`'s `Top` arm needs the same wrapped-row
1553    // count `layout_built` fed `PlotLayout::compute_with_extras` to
1554    // produce this `plot_area` in the first place — recomputed here from
1555    // `legend_plans` (the exact plans that count came from) the same way
1556    // `layout_built` did, so it can never disagree with the band
1557    // `plot_area.y` was actually reserved against. `is_horizontal`'s
1558    // auto value only depends on the position itself (`Top`/`Bottom`),
1559    // overridable by `legend_direction` same as below — computed first
1560    // since `legend_position` needs it to pick `max` (several guides
1561    // sharing a row) vs. `sum` (several guides stacked), the same
1562    // either/or `layout_built` used.
1563    let is_horizontal_hint = match theme.legend_direction {
1564        Some(dir) => matches!(dir, crate::theme::LegendDirection::Horizontal),
1565        None => matches!(
1566            theme.legend_position,
1567            LegendPosition::Top | LegendPosition::Bottom
1568        ),
1569    };
1570    let legend_extra_rows = legend_rows_beyond_first(is_horizontal_hint, legend_plans);
1571    // #225: `Inside`'s justification needs the legend's own estimated
1572    // footprint and the full canvas to clamp against — cheap to compute
1573    // unconditionally (ignored by every other position). Estimated from
1574    // `representatives`, not every raw aesthetic, so a merged group's
1575    // height is counted once, not once per aesthetic in it.
1576    let legend_size_hint =
1577        estimate_legend_box(scales, &representatives, theme, guide, legend_plans);
1578    let canvas = backend.total_area();
1579    let (legend_x, legend_y, mut is_horizontal) = legend_position(
1580        theme,
1581        plot_area,
1582        legend_extra_rows,
1583        legend_size_hint,
1584        &canvas,
1585    );
1586    if let Some(dir) = theme.legend_direction {
1587        is_horizontal = matches!(dir, crate::theme::LegendDirection::Horizontal);
1588    }
1589    let n_wrap = wrap_guide_count(scales, &representatives);
1590    // #170: match `plan_all_legends`'s share — a colourbar guide (a
1591    // continuous Color/Fill legend) sharing this row has already claimed
1592    // its own fixed width, so step the wrap-planned guides by what's
1593    // left, not the whole `legend_avail_width`. #545: a continuous,
1594    // non-colourbar guide (`Size`/`Linewidth`/…) is one of the
1595    // wrap-planned guides this is split among now, not an unconstrained
1596    // extra.
1597    let n_colorbar = colorbar_guide_count(scales, &representatives);
1598    let colorbar_width = n_colorbar as f64 * colorbar_guide_width(theme);
1599    let per_guide_width = ((legend_avail_width - colorbar_width) / n_wrap as f64).max(0.0);
1600
1601    let mut offset_y = legend_y;
1602    let mut offset_x = legend_x;
1603
1604    for group in &groups {
1605        let representative = &group[0];
1606        let rep_scale = scales.get(representative).unwrap();
1607        let scale_group: Vec<(Aesthetic, &dyn crate::scale::Scale)> = group
1608            .iter()
1609            .map(|a| (a.clone(), scales.get(a).unwrap()))
1610            .collect();
1611
1612        if !rep_scale.is_discrete() && is_colorbar_aesthetic(representative) {
1613            // A true colourbar (continuous Color/Fill) draws as a fixed-
1614            // width bar — not in scope for B3-2's wrap/grid planning.
1615            // Every other continuous legend (Size/Linewidth/… sampled
1616            // breaks, #545) falls through to the same wrap/grid-aware
1617            // path a discrete guide uses, below.
1618            //
1619            // #239: a merged continuous fill+colour pair draws one
1620            // bar — `group_mergeable_legends` only merges scales
1621            // whose breaks (so, in practice, colours) already match,
1622            // so the other member(s) would draw the identical bar
1623            // again.
1624            let height = draw_continuous_legend_at(
1625                rep_scale,
1626                theme,
1627                offset_x,
1628                offset_y,
1629                backend,
1630                guide,
1631                is_horizontal,
1632            )?;
1633            if is_horizontal {
1634                // #211: the bar is now drawn along x (wide, not
1635                // narrow) — step by its own length, not the old
1636                // vertical-bar width-plus-side-label estimate.
1637                let (bar_len, _) = continuous_bar_dims(theme, true);
1638                offset_x += bar_len + theme.legend_spacing * 2.0;
1639            } else {
1640                offset_y += height + theme.legend_spacing * 2.0;
1641            }
1642            continue;
1643        }
1644
1645        // A discrete guide, or a continuous non-colourbar guide (#545:
1646        // `Size`/`Linewidth`/… sampled breaks draw the same way a
1647        // discrete guide's keys do) — both get the same B3-2 wrap/grid
1648        // plan when `plan_all_legends` gave them one.
1649        match legend_plans.get(representative) {
1650            None => {
1651                if is_horizontal {
1652                    let width = draw_discrete_legend_at(
1653                        scales,
1654                        &scale_group,
1655                        theme,
1656                        offset_x,
1657                        offset_y,
1658                        backend,
1659                        guide,
1660                        true,
1661                    )?;
1662                    offset_x += width + theme.legend_spacing * 2.0;
1663                } else {
1664                    let height = draw_discrete_legend_at(
1665                        scales,
1666                        &scale_group,
1667                        theme,
1668                        offset_x,
1669                        offset_y,
1670                        backend,
1671                        guide,
1672                        false,
1673                    )?;
1674                    offset_y += height + theme.legend_spacing * 2.0;
1675                }
1676            }
1677            Some(plan) => {
1678                let height = draw_discrete_legend_grid(
1679                    scales,
1680                    &scale_group,
1681                    theme,
1682                    offset_x,
1683                    offset_y,
1684                    backend,
1685                    guide,
1686                    plan,
1687                )?;
1688                if is_horizontal {
1689                    // Each discrete guide gets an equal share of the row
1690                    // (sipemu/ggplot-rs#155) rather than the whole row,
1691                    // which only held for exactly one discrete guide.
1692                    offset_x += per_guide_width;
1693                } else {
1694                    offset_y += height + theme.legend_spacing * 2.0;
1695                }
1696            }
1697        }
1698    }
1699
1700    Ok(())
1701}
1702
1703/// Draw a discrete legend using a [`LegendPlan`] (explicit grid or
1704/// auto-wrap). Returns the total height used (including any "+N more"
1705/// row).
1706#[allow(clippy::too_many_arguments)]
1707/// Wrapped-grid counterpart of [`draw_discrete_legend_at`] — same `group`
1708/// merging (#239).
1709fn draw_discrete_legend_grid(
1710    scales: &ScaleSet,
1711    group: &[(Aesthetic, &dyn crate::scale::Scale)],
1712    theme: &Theme,
1713    legend_x: f64,
1714    legend_y: f64,
1715    backend: &mut dyn DrawBackend,
1716    guide: &GuideLegend,
1717    plan: &LegendPlan,
1718) -> Result<f64, RenderError> {
1719    let (_, scale) = &group[0];
1720    let mut breaks = scale.breaks();
1721    if breaks.is_empty() {
1722        return Ok(0.0);
1723    }
1724    if guide.reverse {
1725        breaks.reverse();
1726    }
1727
1728    // #236: same key-box growth as `draw_discrete_legend_at`.
1729    let diameter = group
1730        .iter()
1731        .map(|(a, s)| size_key_diameter(a, scales, *s, &breaks))
1732        .fold(0.0_f64, f64::max);
1733    let swatch_size = theme.legend_key_width.max(diameter);
1734    let item_height = theme.legend_key_height.max(swatch_size);
1735
1736    let title = guide.title.as_deref().unwrap_or_else(|| scale.name());
1737    let legend_family = if theme.legend_title.family.is_empty() {
1738        None
1739    } else {
1740        Some(theme.legend_title.family.clone())
1741    };
1742    let title_offset = if !title.is_empty() {
1743        backend.draw_text(
1744            title,
1745            (legend_x, legend_y),
1746            &TextStyle {
1747                color: theme.legend_title.color,
1748                size: theme.legend_title.size,
1749                anchor: TextAnchor::Start,
1750                angle: 0.0,
1751                family: legend_family,
1752                face: theme.legend_title.face,
1753                bg_colour: None,
1754                bg_r: 0.0,
1755            },
1756        )?;
1757        theme.legend_title.size + 4.0
1758    } else {
1759        0.0
1760    };
1761    let items_y = legend_y + title_offset;
1762
1763    for entry in &plan.entries {
1764        let (pos, label) = &breaks[entry.break_idx];
1765        let x = legend_x + entry.x_offset;
1766        let y = items_y + entry.row as f64 * item_height;
1767        let center_x = x + swatch_size / 2.0;
1768        let center_y = y + swatch_size / 2.0;
1769
1770        if theme.legend_key.visible {
1771            if let Some(fill) = theme.legend_key.fill {
1772                backend.draw_rect(
1773                    (x, y),
1774                    (x + swatch_size, y + swatch_size),
1775                    &RectStyle {
1776                        fill: Some(fill),
1777                        stroke: theme.legend_key.color,
1778                        stroke_width: theme.legend_key.width,
1779                        alpha: 1.0,
1780                        clip: false,
1781                        corner_radius: 0.0,
1782                    },
1783                )?;
1784            }
1785        }
1786
1787        for (member_aes, member_scale) in group {
1788            draw_legend_swatch(
1789                backend,
1790                scales,
1791                member_aes,
1792                *member_scale,
1793                theme,
1794                label,
1795                *pos,
1796                x,
1797                y,
1798                center_x,
1799                center_y,
1800                swatch_size,
1801            )?;
1802        }
1803
1804        let label_family = if theme.legend_text.family.is_empty() {
1805            None
1806        } else {
1807            Some(theme.legend_text.family.clone())
1808        };
1809        // #159: a label truncated to fit a vertical multi-column grid
1810        // still shows its full text via a `<title>` tooltip (backends
1811        // without tooltip support just render the truncated text).
1812        let display = entry.label_override.as_deref().unwrap_or(label.as_str());
1813        backend.draw_text_with_title(
1814            display,
1815            (x + swatch_size + theme.legend_spacing, center_y),
1816            &TextStyle {
1817                color: theme.legend_text.color,
1818                size: theme.legend_text.size,
1819                anchor: TextAnchor::Start,
1820                angle: 0.0,
1821                family: label_family,
1822                face: theme.legend_text.face,
1823                bg_colour: None,
1824                bg_r: 0.0,
1825            },
1826            entry.label_override.as_deref().map(|_| label.as_str()),
1827        )?;
1828    }
1829
1830    // The overflow marker is text only — not a mark, no swatch.
1831    if let Some(ov) = &plan.overflow {
1832        let x = legend_x + ov.x_offset;
1833        let y = items_y + ov.row as f64 * item_height + swatch_size / 2.0;
1834        let label_family = if theme.legend_text.family.is_empty() {
1835            None
1836        } else {
1837            Some(theme.legend_text.family.clone())
1838        };
1839        backend.draw_text(
1840            &ov.text,
1841            (x, y),
1842            &TextStyle {
1843                color: theme.legend_text.color,
1844                size: theme.legend_text.size,
1845                anchor: TextAnchor::Start,
1846                angle: 0.0,
1847                family: label_family,
1848                face: theme.legend_text.face,
1849                bg_colour: None,
1850                bg_r: 0.0,
1851            },
1852        )?;
1853    }
1854
1855    Ok(title_offset + plan.rows as f64 * item_height)
1856}
1857
1858#[cfg(test)]
1859mod group_mergeable_legends_tests {
1860    use super::*;
1861    use crate::scale::color::RGBAColor;
1862    use crate::scale::manual::ScaleManual;
1863
1864    #[test]
1865    fn an_aesthetic_with_no_attached_scale_is_skipped_not_grouped() {
1866        // #239: in the normal flow, `group_mergeable_legends` is only ever
1867        // handed `legend_scales_for`'s output, which already filters to
1868        // aesthetics present in `scales` — so the `let-else`'s `continue`
1869        // branch (an aesthetic that slipped through with no attached
1870        // scale) is otherwise unreachable from `draw_legend_planned`.
1871        // Exercise it directly: `Fill` is listed but has no scale.
1872        let mut scales = ScaleSet::new();
1873        scales.add(Box::new(ScaleManual::new(
1874            Aesthetic::Color,
1875            vec![("a", RGBAColor::new(200, 0, 0))],
1876        )));
1877        let legend_scales = vec![Aesthetic::Color, Aesthetic::Fill];
1878        let guide = GuideLegend::default();
1879        let groups = group_mergeable_legends(&scales, &legend_scales, &guide);
1880        assert_eq!(groups, vec![vec![Aesthetic::Color]]);
1881    }
1882}
1883
1884/// #211: direct unit coverage for the two private helpers
1885/// `draw_continuous_legend_at`'s vertical/horizontal split relies on —
1886/// exercised indirectly by every colourbar-drawing integration test
1887/// already, but called here directly too so their own branches/math
1888/// are pinned regardless of how the compiler happens to inline them.
1889#[cfg(test)]
1890mod continuous_bar_dims_tests {
1891    use super::*;
1892
1893    #[test]
1894    fn dims_swap_between_vertical_and_horizontal() {
1895        let theme = Theme::default();
1896        let (w, h) = continuous_bar_dims(&theme, false);
1897        assert_eq!(w, theme.legend_key_width);
1898        assert_eq!(h, theme.legend_key_height * 8.0);
1899
1900        let (w, h) = continuous_bar_dims(&theme, true);
1901        assert_eq!(w, theme.legend_key_height * 8.0);
1902        assert_eq!(h, theme.legend_key_width);
1903    }
1904
1905    #[test]
1906    fn horizontal_bar_height_adds_a_title_line_only_when_there_is_a_title() {
1907        let theme = Theme::default();
1908        let without_title = continuous_horizontal_bar_height(&theme, false);
1909        let with_title = continuous_horizontal_bar_height(&theme, true);
1910        assert!(with_title > without_title);
1911        assert!(((with_title - without_title) - (theme.legend_title.size + 4.0)).abs() < 1e-9);
1912
1913        // Matches `continuous_bar_dims`'s own horizontal thickness plus
1914        // the fixed tick/spacing/label overhead — not just a positive
1915        // number, the exact formula `draw_continuous_legend_at` relies
1916        // on to never disagree with what `plot.rs` reserves for it.
1917        let (_, thickness) = continuous_bar_dims(&theme, true);
1918        let tick_len = 3.0;
1919        let label_line = theme.legend_text.size + 4.0;
1920        assert!(
1921            (without_title - (thickness + tick_len + theme.legend_spacing + label_line)).abs()
1922                < 1e-9
1923        );
1924    }
1925}
1926
1927/// #273: `inside_legend_box` — the pre-draw measurement `renderer.rs` uses
1928/// to claim an inside legend's box before any corner-furniture geom draws.
1929#[cfg(test)]
1930mod inside_legend_box_tests {
1931    use super::*;
1932    use crate::scale::color::RGBAColor;
1933    use crate::scale::manual::ScaleManual;
1934
1935    fn scales_with_a_legend() -> ScaleSet {
1936        let mut scales = ScaleSet::new();
1937        scales.add(Box::new(ScaleManual::new(
1938            Aesthetic::Color,
1939            vec![
1940                ("a", RGBAColor::new(200, 0, 0)),
1941                ("b", RGBAColor::new(0, 0, 200)),
1942            ],
1943        )));
1944        scales
1945    }
1946
1947    fn areas() -> (Rect, Rect) {
1948        let plot_area = Rect {
1949            x: 10.0,
1950            y: 10.0,
1951            width: 200.0,
1952            height: 150.0,
1953        };
1954        let canvas = Rect {
1955            x: 0.0,
1956            y: 0.0,
1957            width: 220.0,
1958            height: 170.0,
1959        };
1960        (plot_area, canvas)
1961    }
1962
1963    #[test]
1964    fn non_inside_positions_claim_nothing() {
1965        let scales = scales_with_a_legend();
1966        let (plot_area, canvas) = areas();
1967        let guide = GuideLegend::default();
1968        let suppressed = std::collections::HashSet::new();
1969        let legend_plans = std::collections::HashMap::new();
1970        for pos in [
1971            LegendPosition::Right,
1972            LegendPosition::Left,
1973            LegendPosition::Top,
1974            LegendPosition::Bottom,
1975            LegendPosition::None,
1976        ] {
1977            let theme = Theme {
1978                legend_position: pos,
1979                ..Theme::default()
1980            };
1981            assert!(inside_legend_box(
1982                &scales,
1983                &theme,
1984                &plot_area,
1985                &canvas,
1986                &guide,
1987                &suppressed,
1988                &legend_plans
1989            )
1990            .is_none());
1991        }
1992    }
1993
1994    #[test]
1995    fn no_legend_scales_claims_nothing_even_when_inside() {
1996        let scales = ScaleSet::new(); // nothing mapped to a legend aesthetic
1997        let (plot_area, canvas) = areas();
1998        let theme = Theme {
1999            legend_position: LegendPosition::Inside(0.85, 0.85),
2000            ..Theme::default()
2001        };
2002        let guide = GuideLegend::default();
2003        let suppressed = std::collections::HashSet::new();
2004        let legend_plans = std::collections::HashMap::new();
2005        assert!(inside_legend_box(
2006            &scales,
2007            &theme,
2008            &plot_area,
2009            &canvas,
2010            &guide,
2011            &suppressed,
2012            &legend_plans
2013        )
2014        .is_none());
2015    }
2016
2017    #[test]
2018    fn inside_position_with_a_legend_claims_a_box_within_the_panel() {
2019        let scales = scales_with_a_legend();
2020        let (plot_area, canvas) = areas();
2021        let theme = Theme {
2022            legend_position: LegendPosition::Inside(0.85, 0.85),
2023            ..Theme::default()
2024        };
2025        let guide = GuideLegend::default();
2026        let suppressed = std::collections::HashSet::new();
2027        let legend_plans = std::collections::HashMap::new();
2028        let rect = inside_legend_box(
2029            &scales,
2030            &theme,
2031            &plot_area,
2032            &canvas,
2033            &guide,
2034            &suppressed,
2035            &legend_plans,
2036        )
2037        .expect("an Inside legend with a mapped scale claims a box");
2038        assert!(rect.width > 0.0 && rect.height > 0.0);
2039        assert!(rect.x >= canvas.x - 1e-6 && rect.x + rect.width <= canvas.x + canvas.width + 1e-6);
2040        assert!(
2041            rect.y >= canvas.y - 1e-6 && rect.y + rect.height <= canvas.y + canvas.height + 1e-6
2042        );
2043    }
2044
2045    #[test]
2046    fn matches_the_position_draw_legend_planned_itself_uses() {
2047        // Mirrors `draw_legend_planned`'s own prefix (`legend_scales_for`
2048        // → `group_mergeable_legends` → `estimate_legend_box` →
2049        // `legend_position`) — this must agree with it, or a geom drawn
2050        // before the legend could stack clear of the wrong spot.
2051        let scales = scales_with_a_legend();
2052        let (plot_area, canvas) = areas();
2053        let theme = Theme {
2054            legend_position: LegendPosition::Inside(0.85, 0.85),
2055            ..Theme::default()
2056        };
2057        let guide = GuideLegend::default();
2058        let suppressed = std::collections::HashSet::new();
2059        let legend_plans = std::collections::HashMap::new();
2060
2061        let rect = inside_legend_box(
2062            &scales,
2063            &theme,
2064            &plot_area,
2065            &canvas,
2066            &guide,
2067            &suppressed,
2068            &legend_plans,
2069        )
2070        .unwrap();
2071
2072        let legend_scales = legend_scales_for(&scales, &suppressed);
2073        let groups = group_mergeable_legends(&scales, &legend_scales, &guide);
2074        let representatives: Vec<Aesthetic> = groups.iter().map(|g| g[0].clone()).collect();
2075        let size_hint =
2076            estimate_legend_box(&scales, &representatives, &theme, &guide, &legend_plans);
2077        let (x, y, _) = legend_position(&theme, &plot_area, 0, size_hint, &canvas);
2078
2079        assert_eq!(
2080            (rect.x, rect.y, rect.width, rect.height),
2081            (x, y, size_hint.0, size_hint.1)
2082        );
2083    }
2084}