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/// Estimated bounding box `[x0, y0, x1, y1]` of a label anchored at
56/// `(x, y)`, set at font `size`, rotated `angle` degrees (SVG convention,
57/// clockwise), with `anchor` in `0.0` (text starts at `x`) `..=1.0` (text
58/// ends at `x`) — `0.5` centres it, matching `TextAnchor::{Start,Middle,
59/// End}`. Ported from the consumer's `TickLabel::bbox`.
60pub(crate) fn label_bbox(
61 text: &str,
62 size: f64,
63 x: f64,
64 y: f64,
65 angle: f64,
66 anchor: f64,
67) -> [f64; 4] {
68 let w = text_width(text, size);
69 let h = size * 1.2;
70 let x0 = -w * anchor;
71 let (s, c) = angle.to_radians().sin_cos();
72 let mut b = [
73 f64::INFINITY,
74 f64::INFINITY,
75 f64::NEG_INFINITY,
76 f64::NEG_INFINITY,
77 ];
78 for (dx, dy) in [
79 (x0, -h / 2.0),
80 (x0 + w, -h / 2.0),
81 (x0, h / 2.0),
82 (x0 + w, h / 2.0),
83 ] {
84 let (px, py) = (x + dx * c - dy * s, y + dx * s + dy * c);
85 b = [b[0].min(px), b[1].min(py), b[2].max(px), b[3].max(py)];
86 }
87 b
88}
89
90/// For rotated bottom-axis tick labels, the extra vertical *rise* (above
91/// the un-rotated anchor point) and *fall* (below it) the rotated bounding
92/// boxes need, maxed over `labels` (sipemu/ggplot-rs#162). A label
93/// end-anchored at a point just below the panel and rotated toward the
94/// panel (e.g. the usual 45° "reads up-and-to-the-right" tilt) swings its
95/// far end — `rise` — back up by roughly `width · sin(angle)`; a label
96/// rotated away from the panel (e.g. 270°, hanging straight down) has no
97/// rise at all, only `fall`.
98///
99/// Both `GGPlot::layout_built` (to reserve enough panel-bottom margin that
100/// `fall` stays on-canvas) and `draw_x_axis` (to place the rotation anchor
101/// `rise` further from the axis line than the flat-label offset, so the
102/// rotated label never swings back over the panel) need the *same*
103/// numbers — this is their one shared source, so the two can never drift
104/// apart.
105pub(crate) fn rotated_label_rise_fall<'a>(
106 labels: impl Iterator<Item = &'a str>,
107 size: f64,
108 angle: f64,
109 anchor: f64,
110) -> (f64, f64) {
111 let mut rise = 0.0_f64;
112 let mut fall = 0.0_f64;
113 for label in labels {
114 let b = label_bbox(label, size, 0.0, 0.0, angle, anchor);
115 rise = rise.max(-b[1]);
116 fall = fall.max(b[3]);
117 }
118 (rise.max(0.0), fall.max(0.0))
119}
120
121/// Which end of a rotated axis-tick label should pin to the tick
122/// (sipemu/ggplot-rs#163): `1.0` (`TextAnchor::End`, the label's *last*
123/// character at the tick) or `0.0` (`TextAnchor::Start`, its *first*
124/// character at the tick) — whichever keeps the label's *far* end swinging
125/// away from the panel instead of into it.
126///
127/// `dir` is `draw_x_axis`'s own tick direction: `+1.0` for a bottom axis
128/// (the panel sits above the axis line), `-1.0` for a top axis (the panel
129/// sits below it). The right anchor depends on *both* the rotation's
130/// direction and which side the panel is on — not the angle alone: a
131/// counter-clockwise (SVG-negative) angle swings its far end away from the
132/// panel when its *last* character is pinned, when the panel is above
133/// (bottom axis); a clockwise (SVG-positive) angle needs the opposite —
134/// its *first* character pinned — for the same effect. Both flip for a top
135/// axis, where "away from the panel" points the other way. Concretely:
136/// `End` exactly when `dir * sin(angle) < 0`.
137///
138/// Picking the wrong one for a given sign pushes the whole label away from
139/// the tick instead (0.22.1's bug, on a bottom axis): the tick-anchored
140/// end stays near the tick but the free end swings into the previous
141/// category's space (or, with the direction only half-fixed, the anchor
142/// itself gets pushed far from the tick to clear the panel on a top axis)
143/// instead of the near-axis end simply staying at the tick either way.
144///
145/// Only meaningful when the caller already knows the label is rotated
146/// (`angle.abs() > 10.0`); the flat case uses `0.5` (`TextAnchor::Middle`)
147/// unconditionally, never this function.
148pub(crate) fn rotated_anchor_frac(angle: f64, dir: f64) -> f64 {
149 if dir * angle.to_radians().sin() < 0.0 {
150 1.0
151 } else {
152 0.0
153 }
154}
155
156/// ggplot2's `check.overlap` draw order (its internal `label_priority`):
157/// always keep the first and last breaks, then recursively bisect the
158/// remaining range (midpoint first, then its two halves), so thinning drops
159/// the *most crowded middle* first rather than every other label. R parity
160/// (ggplot2 4.0.3): `axis_label_priority(5)` is `1 5 3 2 4`;
161/// `axis_label_priority(10)` is `1 10 5 3 2 4 7 6 8 9` (1-indexed).
162pub(crate) fn axis_label_priority(n: usize) -> Vec<usize> {
163 if n == 0 {
164 return Vec::new();
165 }
166 if n == 1 {
167 return vec![1];
168 }
169 let mut out = vec![1, n];
170 bisect(2, n - 1, &mut out);
171 out
172}
173
174/// 1-indexed inclusive range `[lo, hi]`: midpoint first (floor division),
175/// then the left half, then the right half.
176fn bisect(lo: usize, hi: usize, out: &mut Vec<usize>) {
177 if lo > hi {
178 return;
179 }
180 let mid = (lo + hi) / 2;
181 out.push(mid);
182 if mid > lo {
183 bisect(lo, mid - 1, out);
184 }
185 bisect(mid + 1, hi, out);
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 #[test]
193 fn priority_matches_r_ggplot2_4_0_3() {
194 assert_eq!(axis_label_priority(5), vec![1, 5, 3, 2, 4]);
195 assert_eq!(axis_label_priority(10), vec![1, 10, 5, 3, 2, 4, 7, 6, 8, 9]);
196 }
197
198 #[test]
199 fn priority_edge_cases() {
200 assert_eq!(axis_label_priority(0), Vec::<usize>::new());
201 assert_eq!(axis_label_priority(1), vec![1]);
202 assert_eq!(axis_label_priority(2), vec![1, 2]);
203 }
204
205 #[test]
206 fn truncate_to_width_keeps_short_labels_untouched() {
207 assert_eq!(truncate_to_width("ab", 1000.0, 10.0), None);
208 }
209
210 #[test]
211 fn truncate_to_width_shortens_with_an_ellipsis() {
212 let full = "a very long legend label indeed";
213 let w = text_width(full, 10.0);
214 let truncated = truncate_to_width(full, w / 2.0, 10.0).expect("should truncate");
215 assert!(truncated.ends_with('…'));
216 assert!(text_width(&truncated, 10.0) <= w / 2.0);
217 assert!(truncated.chars().count() < full.chars().count());
218 }
219
220 #[test]
221 fn truncate_to_width_falls_back_to_a_bare_ellipsis() {
222 // Even "…" alone doesn't fit a near-zero width — still the best
223 // truncation can do, not an empty string.
224 assert_eq!(
225 truncate_to_width("hello", 0.01, 10.0),
226 Some("…".to_string())
227 );
228 }
229
230 #[test]
231 fn text_width_matches_consumer_em_table() {
232 assert_eq!(text_width("", 10.0), 0.0);
233 assert!((text_width("i", 10.0) - 2.7).abs() < 1e-9);
234 assert!((text_width("M", 10.0) - 8.6).abs() < 1e-9);
235 }
236
237 #[test]
238 fn label_bbox_unrotated_middle_anchor() {
239 let b = label_bbox("ab", 10.0, 100.0, 50.0, 0.0, 0.5);
240 let w = text_width("ab", 10.0);
241 assert!((b[0] - (100.0 - w / 2.0)).abs() < 1e-9);
242 assert!((b[2] - (100.0 + w / 2.0)).abs() < 1e-9);
243 assert!((b[1] - (50.0 - 6.0)).abs() < 1e-9);
244 assert!((b[3] - (50.0 + 6.0)).abs() < 1e-9);
245 }
246}