Skip to main content

ggplot_rs/render/
text.rs

1//! Text-metric helpers for axis-label fit (B3-1): ggplot-rs owns the
2//! outer-label-overflow and `check.overlap` logic centrally, instead of a
3//! downstream consumer post-processing rendered SVG (the old approach had
4//! to re-parse `<text>` elements out of the markup).
5//!
6//! Ported verbatim from the consumer's `ticks.rs` em table and
7//! `TickLabel::bbox`, which is the only reason the measurements match what
8//! callers previously saw.
9
10/// Estimated width (px) of `text` set at font size `size`, in the house sans
11/// (Hanken Grotesk, or the system UI font it falls back to). This is a
12/// heuristic per-character average-width table, not real font metrics —
13/// good enough for layout decisions (fit, overlap, auto-wrap), not for
14/// pixel-perfect text extents.
15pub fn text_width(text: &str, size: f64) -> f64 {
16    let em: f64 = text
17        .chars()
18        .map(|ch| match ch {
19            ' ' => 0.27,
20            '.' | ',' | ':' | ';' | '\'' | '|' | '!' | 'i' | 'j' | 'l' | 'I' => 0.27,
21            'f' | 't' | 'r' | '(' | ')' | '[' | ']' | '-' | '/' => 0.36,
22            '0'..='9' | '$' | '€' | '£' | '+' | '=' | '<' | '>' | '#' | '*' | '?' => 0.57,
23            'm' | 'w' => 0.8,
24            'M' | 'W' | '%' | '@' => 0.86,
25            'a'..='z' => 0.53,
26            'A'..='Z' | '&' => 0.66,
27            _ => 0.62,
28        })
29        .sum();
30    em * size
31}
32
33/// Shorten `label` with a trailing ellipsis ("…") until it (plus the
34/// ellipsis) fits within `max_width` px at font `size` (#159: a vertical
35/// multi-column legend grid that still overflows after exhausting column
36/// reduction falls back to truncating its labels). `None` means `label`
37/// already fits — no truncation needed, so the caller keeps the
38/// byte-identical untruncated path. A `max_width` too narrow for even a
39/// bare "…" still returns `Some("…")` — the best any truncation can do —
40/// rather than an empty string.
41pub fn truncate_to_width(label: &str, max_width: f64, size: f64) -> Option<String> {
42    if text_width(label, size) <= max_width {
43        return None;
44    }
45    let chars: Vec<char> = label.chars().collect();
46    for keep in (0..chars.len()).rev() {
47        let candidate: String = chars[..keep].iter().collect::<String>() + "…";
48        if text_width(&candidate, size) <= max_width {
49            return Some(candidate);
50        }
51    }
52    Some("…".to_string())
53}
54
55/// Characters after which a hard break in [`wrap_text`] is preferred over a
56/// blind character-count cut — the separators a URL or path is built from
57/// (sipemu/ggplot-rs#264: a bare URL has no whitespace at all, so without
58/// this it fell back to slicing mid-word, e.g. `"eodatenzentr"` / `"um.de"`).
59const WRAP_HARD_BREAK_AFTER: [char; 7] = ['/', '.', '_', '-', '?', '&', '='];
60
61/// Word-wraps `text` to lines no wider than `max_width` px at font `size`,
62/// measured with [`text_width`] (ggtext / `str_wrap` behaviour: break at
63/// whitespace; a single word wider than `max_width` on its own is hard-split
64/// so it never overflows the box). Returns `vec![String::new()]` for empty
65/// input and otherwise always at least one line, so a caller can take
66/// `lines.len()` as the wrapped block's line count without a special case.
67///
68/// `max_width <= 0.0` (or non-finite) disables wrapping — each word still
69/// splits only when it alone would overflow a *positive* width, so a
70/// degenerate width never panics or infinite-loops; it returns `text`
71/// unsplit as a single line (matching "no wrap requested").
72pub fn wrap_text(text: &str, max_width: f64, size: f64) -> Vec<String> {
73    if text.is_empty() {
74        return vec![String::new()];
75    }
76    if !max_width.is_finite() || max_width <= 0.0 {
77        return vec![text.to_string()];
78    }
79    let mut lines: Vec<String> = Vec::new();
80    let mut cur = String::new();
81    for word in text.split_whitespace() {
82        let mut word = word.to_string();
83        // A single word that alone overflows max_width: hard-break it by
84        // character rather than let it overflow the box.
85        while text_width(&word, size) > max_width {
86            let chars: Vec<char> = word.chars().collect();
87            if chars.len() <= 1 {
88                break;
89            }
90            let mut cut = chars.len() - 1;
91            while cut > 1 && text_width(&chars[..cut].iter().collect::<String>(), size) > max_width
92            {
93                cut -= 1;
94            }
95            // Prefer breaking right after the last `/ . _ - ? & =` that
96            // still fits, rather than wherever the width-based cut above
97            // landed — but only when that leaves a non-trivial chunk (at
98            // least a third of what fits), so a separator near the very
99            // start of the fitting prefix doesn't produce a near-empty
100            // line (#264).
101            if let Some(break_at) = chars[..cut]
102                .iter()
103                .rposition(|c| WRAP_HARD_BREAK_AFTER.contains(c))
104            {
105                let candidate = break_at + 1;
106                if candidate > 0 && (candidate as f64) >= (cut as f64) / 3.0 {
107                    cut = candidate;
108                }
109            }
110            if !cur.is_empty() {
111                lines.push(std::mem::take(&mut cur));
112            }
113            lines.push(chars[..cut].iter().collect());
114            word = chars[cut..].iter().collect();
115        }
116        if cur.is_empty() {
117            cur = word;
118        } else {
119            let candidate = format!("{cur} {word}");
120            if text_width(&candidate, size) <= max_width {
121                cur = candidate;
122            } else {
123                lines.push(std::mem::replace(&mut cur, word));
124            }
125        }
126    }
127    if !cur.is_empty() || lines.is_empty() {
128        lines.push(cur);
129    }
130    lines
131}
132
133/// The widest wrapped line's width (px) at font `size` — the natural width
134/// of a wrapped text block, e.g. for a [`GeomLabel`](crate::geom::text::GeomLabel)
135/// background box sized to fit its wrapped text.
136pub fn wrapped_block_width(lines: &[String], size: f64) -> f64 {
137    lines
138        .iter()
139        .map(|l| text_width(l, size))
140        .fold(0.0, f64::max)
141}
142
143/// Estimated bounding box `[x0, y0, x1, y1]` of a label anchored at
144/// `(x, y)`, set at font `size`, rotated `angle` degrees (SVG convention,
145/// clockwise), with `anchor` in `0.0` (text starts at `x`) `..=1.0` (text
146/// ends at `x`) — `0.5` centres it, matching `TextAnchor::{Start,Middle,
147/// End}`. Ported from the consumer's `TickLabel::bbox`.
148pub(crate) fn label_bbox(
149    text: &str,
150    size: f64,
151    x: f64,
152    y: f64,
153    angle: f64,
154    anchor: f64,
155) -> [f64; 4] {
156    let w = text_width(text, size);
157    let h = size * 1.2;
158    let x0 = -w * anchor;
159    let (s, c) = angle.to_radians().sin_cos();
160    let mut b = [
161        f64::INFINITY,
162        f64::INFINITY,
163        f64::NEG_INFINITY,
164        f64::NEG_INFINITY,
165    ];
166    for (dx, dy) in [
167        (x0, -h / 2.0),
168        (x0 + w, -h / 2.0),
169        (x0, h / 2.0),
170        (x0 + w, h / 2.0),
171    ] {
172        let (px, py) = (x + dx * c - dy * s, y + dx * s + dy * c);
173        b = [b[0].min(px), b[1].min(py), b[2].max(px), b[3].max(py)];
174    }
175    b
176}
177
178/// For rotated bottom-axis tick labels, the extra vertical *rise* (above
179/// the un-rotated anchor point) and *fall* (below it) the rotated bounding
180/// boxes need, maxed over `labels` (sipemu/ggplot-rs#162). A label
181/// end-anchored at a point just below the panel and rotated toward the
182/// panel (e.g. the usual 45° "reads up-and-to-the-right" tilt) swings its
183/// far end — `rise` — back up by roughly `width · sin(angle)`; a label
184/// rotated away from the panel (e.g. 270°, hanging straight down) has no
185/// rise at all, only `fall`.
186///
187/// Both `GGPlot::layout_built` (to reserve enough panel-bottom margin that
188/// `fall` stays on-canvas) and `draw_x_axis` (to place the rotation anchor
189/// `rise` further from the axis line than the flat-label offset, so the
190/// rotated label never swings back over the panel) need the *same*
191/// numbers — this is their one shared source, so the two can never drift
192/// apart.
193pub(crate) fn rotated_label_rise_fall<'a>(
194    labels: impl Iterator<Item = &'a str>,
195    size: f64,
196    angle: f64,
197    anchor: f64,
198) -> (f64, f64) {
199    let mut rise = 0.0_f64;
200    let mut fall = 0.0_f64;
201    for label in labels {
202        let b = label_bbox(label, size, 0.0, 0.0, angle, anchor);
203        rise = rise.max(-b[1]);
204        fall = fall.max(b[3]);
205    }
206    (rise.max(0.0), fall.max(0.0))
207}
208
209/// Which end of a rotated axis-tick label should pin to the tick
210/// (sipemu/ggplot-rs#163): `1.0` (`TextAnchor::End`, the label's *last*
211/// character at the tick) or `0.0` (`TextAnchor::Start`, its *first*
212/// character at the tick) — whichever keeps the label's *far* end swinging
213/// away from the panel instead of into it.
214///
215/// `dir` is `draw_x_axis`'s own tick direction: `+1.0` for a bottom axis
216/// (the panel sits above the axis line), `-1.0` for a top axis (the panel
217/// sits below it). The right anchor depends on *both* the rotation's
218/// direction and which side the panel is on — not the angle alone: a
219/// counter-clockwise (SVG-negative) angle swings its far end away from the
220/// panel when its *last* character is pinned, when the panel is above
221/// (bottom axis); a clockwise (SVG-positive) angle needs the opposite —
222/// its *first* character pinned — for the same effect. Both flip for a top
223/// axis, where "away from the panel" points the other way. Concretely:
224/// `End` exactly when `dir * sin(angle) < 0`.
225///
226/// Picking the wrong one for a given sign pushes the whole label away from
227/// the tick instead (0.22.1's bug, on a bottom axis): the tick-anchored
228/// end stays near the tick but the free end swings into the previous
229/// category's space (or, with the direction only half-fixed, the anchor
230/// itself gets pushed far from the tick to clear the panel on a top axis)
231/// instead of the near-axis end simply staying at the tick either way.
232///
233/// Only meaningful when the caller already knows the label is rotated
234/// (`angle.abs() > 10.0`); the flat case uses `0.5` (`TextAnchor::Middle`)
235/// unconditionally, never this function.
236pub(crate) fn rotated_anchor_frac(angle: f64, dir: f64) -> f64 {
237    if dir * angle.to_radians().sin() < 0.0 {
238        1.0
239    } else {
240        0.0
241    }
242}
243
244/// ggplot2's `check.overlap` draw order (its internal `label_priority`):
245/// always keep the first and last breaks, then recursively bisect the
246/// remaining range (midpoint first, then its two halves), so thinning drops
247/// the *most crowded middle* first rather than every other label. R parity
248/// (ggplot2 4.0.3): `axis_label_priority(5)` is `1 5 3 2 4`;
249/// `axis_label_priority(10)` is `1 10 5 3 2 4 7 6 8 9` (1-indexed).
250pub(crate) fn axis_label_priority(n: usize) -> Vec<usize> {
251    if n == 0 {
252        return Vec::new();
253    }
254    if n == 1 {
255        return vec![1];
256    }
257    let mut out = vec![1, n];
258    bisect(2, n - 1, &mut out);
259    out
260}
261
262/// 1-indexed inclusive range `[lo, hi]`: midpoint first (floor division),
263/// then the left half, then the right half.
264fn bisect(lo: usize, hi: usize, out: &mut Vec<usize>) {
265    if lo > hi {
266        return;
267    }
268    let mid = (lo + hi) / 2;
269    out.push(mid);
270    if mid > lo {
271        bisect(lo, mid - 1, out);
272    }
273    bisect(mid + 1, hi, out);
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    fn priority_matches_r_ggplot2_4_0_3() {
282        assert_eq!(axis_label_priority(5), vec![1, 5, 3, 2, 4]);
283        assert_eq!(axis_label_priority(10), vec![1, 10, 5, 3, 2, 4, 7, 6, 8, 9]);
284    }
285
286    #[test]
287    fn priority_edge_cases() {
288        assert_eq!(axis_label_priority(0), Vec::<usize>::new());
289        assert_eq!(axis_label_priority(1), vec![1]);
290        assert_eq!(axis_label_priority(2), vec![1, 2]);
291    }
292
293    #[test]
294    fn truncate_to_width_keeps_short_labels_untouched() {
295        assert_eq!(truncate_to_width("ab", 1000.0, 10.0), None);
296    }
297
298    #[test]
299    fn truncate_to_width_shortens_with_an_ellipsis() {
300        let full = "a very long legend label indeed";
301        let w = text_width(full, 10.0);
302        let truncated = truncate_to_width(full, w / 2.0, 10.0).expect("should truncate");
303        assert!(truncated.ends_with('…'));
304        assert!(text_width(&truncated, 10.0) <= w / 2.0);
305        assert!(truncated.chars().count() < full.chars().count());
306    }
307
308    #[test]
309    fn truncate_to_width_falls_back_to_a_bare_ellipsis() {
310        // Even "…" alone doesn't fit a near-zero width — still the best
311        // truncation can do, not an empty string.
312        assert_eq!(
313            truncate_to_width("hello", 0.01, 10.0),
314            Some("…".to_string())
315        );
316    }
317
318    #[test]
319    fn text_width_matches_consumer_em_table() {
320        assert_eq!(text_width("", 10.0), 0.0);
321        assert!((text_width("i", 10.0) - 2.7).abs() < 1e-9);
322        assert!((text_width("M", 10.0) - 8.6).abs() < 1e-9);
323    }
324
325    #[test]
326    fn wrap_text_breaks_at_whitespace_within_width() {
327        let lines = wrap_text("alpha beta gamma delta", 1000.0, 10.0);
328        assert_eq!(lines, vec!["alpha beta gamma delta".to_string()]);
329    }
330
331    #[test]
332    fn wrap_text_wraps_to_multiple_lines_when_narrow() {
333        let w = text_width("alpha beta", 10.0);
334        let lines = wrap_text("alpha beta gamma delta", w + 1.0, 10.0);
335        assert!(lines.len() >= 2, "expected wrapping, got {lines:?}");
336        for l in &lines {
337            assert!(
338                text_width(l, 10.0) <= w + 1.0 + 1e-6,
339                "line {l:?} overflows width"
340            );
341        }
342        assert_eq!(lines.join(" "), "alpha beta gamma delta");
343    }
344
345    #[test]
346    fn wrap_text_hard_breaks_a_single_overlong_word() {
347        let lines = wrap_text("supercalifragilisticexpialidocious", 40.0, 10.0);
348        assert!(lines.len() > 1);
349        assert_eq!(lines.concat(), "supercalifragilisticexpialidocious");
350        for l in &lines {
351            assert!(text_width(l, 10.0) <= 40.0 + 1e-6);
352        }
353    }
354
355    #[test]
356    fn wrap_text_hard_break_flushes_a_pending_line_first() {
357        // "ab" fits its own line (`cur` is non-empty) before the second
358        // word triggers a hard break — the hard-break path must flush
359        // `cur` as its own line rather than lose or merge it.
360        let lines = wrap_text("ab supercalifragilisticexpialidocious", 40.0, 10.0);
361        assert_eq!(lines[0], "ab");
362        assert!(lines.len() > 2, "{lines:?}");
363        assert_eq!(lines[1..].concat(), "supercalifragilisticexpialidocious");
364        for l in &lines {
365            assert!(text_width(l, 10.0) <= 40.0 + 1e-6);
366        }
367    }
368
369    #[test]
370    fn wrap_text_prefers_url_separators_over_a_blind_char_cut() {
371        // A bare URL (no whitespace at all, #264's repro) should break
372        // after `/ . _ - ? & =`, not wherever a raw character-count cut
373        // happens to land.
374        let url =
375            "https://sgx.geodatenzentrum.de/web_public/gdz/datenquellen/datenquellen_vg_nuts.pdf";
376        let lines = wrap_text(url, 80.0, 7.0);
377        assert!(lines.len() > 1, "expected wrapping, got {lines:?}");
378        assert_eq!(lines.concat(), url);
379        for l in &lines {
380            assert!(
381                text_width(l, 7.0) <= 80.0 + 1e-6,
382                "line {l:?} overflows width"
383            );
384        }
385        // Every line but the last should end right after one of the
386        // preferred separators, not mid-token.
387        for l in &lines[..lines.len() - 1] {
388            let last = l.chars().last().unwrap();
389            assert!(
390                WRAP_HARD_BREAK_AFTER.contains(&last),
391                "line {l:?} did not break after a preferred separator"
392            );
393        }
394    }
395
396    #[test]
397    fn wrap_text_still_hard_breaks_when_no_separator_exists() {
398        // No `/ . _ - ? & =` anywhere: falls back to the plain
399        // character-count cut, same as before #264.
400        let lines = wrap_text("supercalifragilisticexpialidocious", 40.0, 10.0);
401        assert!(lines.len() > 1);
402        assert_eq!(lines.concat(), "supercalifragilisticexpialidocious");
403    }
404
405    #[test]
406    fn wrap_text_ignores_a_separator_too_close_to_the_start() {
407        // A single `-` right after the first character shouldn't force a
408        // one-character line; the width-based cut should stand instead.
409        let lines = wrap_text("a-supercalifragilisticexpialidocious", 40.0, 10.0);
410        assert_ne!(lines[0], "a-", "separator too close to start was used");
411        assert_eq!(lines.concat(), "a-supercalifragilisticexpialidocious");
412    }
413
414    #[test]
415    fn wrap_text_width_too_narrow_for_even_one_character_still_terminates() {
416        // A width narrower than any single character: hard-breaking can't
417        // cut further (`chars.len() <= 1`), so it gives up and keeps that
418        // one character whole rather than looping forever.
419        let lines = wrap_text("i", 0.5, 10.0);
420        assert_eq!(lines, vec!["i".to_string()]);
421    }
422
423    #[test]
424    fn wrap_text_empty_input_is_one_empty_line() {
425        assert_eq!(wrap_text("", 100.0, 10.0), vec![String::new()]);
426    }
427
428    #[test]
429    fn wrap_text_non_positive_width_disables_wrapping() {
430        assert_eq!(
431            wrap_text("alpha beta gamma", 0.0, 10.0),
432            vec!["alpha beta gamma".to_string()]
433        );
434        assert_eq!(
435            wrap_text("alpha beta gamma", -5.0, 10.0),
436            vec!["alpha beta gamma".to_string()]
437        );
438    }
439
440    #[test]
441    fn wrapped_block_width_is_the_widest_line() {
442        let lines = vec!["short".to_string(), "a longer line here".to_string()];
443        let w = wrapped_block_width(&lines, 10.0);
444        assert_eq!(w, text_width("a longer line here", 10.0));
445    }
446
447    #[test]
448    fn label_bbox_unrotated_middle_anchor() {
449        let b = label_bbox("ab", 10.0, 100.0, 50.0, 0.0, 0.5);
450        let w = text_width("ab", 10.0);
451        assert!((b[0] - (100.0 - w / 2.0)).abs() < 1e-9);
452        assert!((b[2] - (100.0 + w / 2.0)).abs() < 1e-9);
453        assert!((b[1] - (50.0 - 6.0)).abs() < 1e-9);
454        assert!((b[3] - (50.0 + 6.0)).abs() < 1e-9);
455    }
456}