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