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