kuva 0.4.0

Scientific plotting library in Rust with various backends.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Real text measurement backed by the bundled DejaVu Sans metrics — horizontal
//! advance widths and per-style vertical metrics (ascent, descent, line height,
//! cap/x-height).
//!
//! kuva reserves space for every label, tick, legend entry, and title from a
//! width estimate computed at layout time. Historically that estimate was
//! `char_count * font_size * <some factor>`, a monospace approximation applied to
//! a proportional font; the factor was guessed (and re-guessed) per call site,
//! and non-ASCII labels measured by byte length were 2–3× off.
//!
//! This module replaces all of that with one function, [`measure_text_width`]
//! (and [`widest_text_width`] for "size to the widest of these labels"), that
//! sums the *real* horizontal advances of DejaVu Sans — the font kuva renders for
//! PNG/PDF, embeds under `embed_font`, and lists first in the default SVG cascade.
//! The advances live in generated, run-length-encoded tables ([`data`]) compiled
//! into every build (including the dependency-free SVG-only default build), so
//! layout never needs the font bytes or a parser at runtime. See
//! `examples/gen_text_metrics.rs` for regeneration.
//!
//! Each [`FontStyle`] is measured from its own face, so callers ask for the style
//! they will render and get correct widths even if the bundled font is swapped
//! for one whose italic or bold metrics differ from regular — a font change is a
//! regenerate, not a code change. (Across the full BMP the DejaVu faces really do
//! differ, so this matters.) The one exception: no bold-oblique face is bundled,
//! so [`FontStyle::BoldItalic`] is sourced from the Bold face until one is added.
//!
//! Accuracy by backend: exact for PNG/PDF and `embed_font` SVG (kuva controls the
//! font); a close, fails-safe prediction for bare SVG (the consumer picks the
//! font, but the cascade resolves to DejaVu or a near-metric-match like Verdana).

use std::sync::OnceLock;

mod data;

/// Advance assumed for a codepoint DejaVu Sans has no glyph for (CJK, emoji,
/// exotic scripts). One em deliberately over-reserves rather than clipping, and
/// such glyphs render in a substituted font of unknown metrics anyway.
const FALLBACK_ADVANCE_UNITS: u16 = data::UNITS_PER_EM;

/// Which face to measure against. Each variant has its own advance table; do not
/// assume any two share metrics (they do not, across the full character set).
///
/// `Italic`/`BoldItalic` (and [`FontStyle::from_flags`]) complete the API so
/// callers can measure italic text correctly — the faces genuinely differ — but
/// no current width site measures italic text, so they carry `allow(dead_code)`
/// until one does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum FontStyle {
    Regular,
    #[allow(dead_code)]
    Italic,
    Bold,
    #[allow(dead_code)]
    BoldItalic,
}

impl FontStyle {
    /// Builds a style from independent bold/italic flags (the common call-site shape).
    #[allow(dead_code)]
    pub(crate) fn from_flags(bold: bool, italic: bool) -> Self {
        match (bold, italic) {
            (false, false) => FontStyle::Regular,
            (false, true) => FontStyle::Italic,
            (true, false) => FontStyle::Bold,
            (true, true) => FontStyle::BoldItalic,
        }
    }
}

/// Per-style vertical metrics for the bundled face, in font units (scale to
/// pixels by `size / UNITS_PER_EM`). `descent` is stored as a positive depth
/// below the baseline. `cap_height`/`x_height` are measured from the `H`/`x`
/// glyph outlines (robust to faces whose OS/2 table omits them, as DejaVu does).
#[derive(Clone, Copy, Debug)]
struct VMetrics {
    ascent: i16,
    descent: i16,
    line_gap: i16,
    cap_height: i16,
    x_height: i16,
}

/// Vertical metrics (font units) for `style`.
fn vmetrics(style: FontStyle) -> VMetrics {
    match style {
        FontStyle::Regular => data::VMETRICS_REGULAR,
        FontStyle::Italic => data::VMETRICS_ITALIC,
        FontStyle::Bold => data::VMETRICS_BOLD,
        FontStyle::BoldItalic => data::VMETRICS_BOLD_ITALIC,
    }
}

/// Scales a font-unit vertical metric to pixels at `font_size`.
fn scale_units(units: impl Into<i32>, font_size: f64) -> f64 {
    f64::from(units.into()) / f64::from(data::UNITS_PER_EM) * font_size
}

/// Natural single-spaced line height (ascent + descent + line gap) in pixels —
/// the vertical advance between stacked lines and the minimum height a row or box
/// must reserve to hold one line of text without clipping. Replaces the zoo of
/// `font_size * {1.0..1.55}` and hardcoded-pixel line-height guesses.
pub(crate) fn line_height(font_size: f64, style: FontStyle) -> f64 {
    let m = vmetrics(style);
    scale_units(
        i32::from(m.ascent) + i32::from(m.descent) + i32::from(m.line_gap),
        font_size,
    )
}

/// Distance from the baseline up to the top of the font's ascenders, in pixels.
/// Use to top-anchor text in a reserved band (baseline = top + ascent).
pub(crate) fn ascent(font_size: f64, style: FontStyle) -> f64 {
    scale_units(vmetrics(style).ascent, font_size)
}

/// Distance from the baseline down to the bottom of descenders (positive), in px.
pub(crate) fn descent(font_size: f64, style: FontStyle) -> f64 {
    scale_units(vmetrics(style).descent, font_size)
}

/// Height of the em box glyphs actually occupy (ascent + descent), without line
/// leading — the measure to test text against a fixed height (cell, band, ring).
pub(crate) fn text_height(font_size: f64, style: FontStyle) -> f64 {
    let m = vmetrics(style);
    scale_units(i32::from(m.ascent) + i32::from(m.descent), font_size)
}

/// Cap height (top of uppercase letters above the baseline), in pixels.
#[allow(dead_code)]
pub(crate) fn cap_height(font_size: f64, style: FontStyle) -> f64 {
    scale_units(vmetrics(style).cap_height, font_size)
}

/// x-height (top of lowercase letters above the baseline), in pixels.
#[allow(dead_code)]
pub(crate) fn x_height(font_size: f64, style: FontStyle) -> f64 {
    scale_units(vmetrics(style).x_height, font_size)
}

/// Baseline offset that vertically centers a line of uppercase/digit text on a
/// target y: draw the baseline at `target_y + center_offset(size, style)` so the
/// cap-height midpoint lands on `target_y`. The real-metric replacement for the
/// ubiquitous `font_size * 0.35` centering guess (`0.35 ≈ cap_height/2` for
/// DejaVu, but this tracks the actual font instead of assuming it).
pub(crate) fn center_offset(font_size: f64, style: FontStyle) -> f64 {
    scale_units(vmetrics(style).cap_height, font_size) / 2.0
}

/// Estimated rendered width of a single line of `text` at `font_size` pixels,
/// using real DejaVu Sans advance widths for `style`.
///
/// Counts Unicode scalar values (not UTF-8 bytes), so multi-byte labels are
/// measured correctly. Newlines are not interpreted — callers wrap first.
pub(crate) fn measure_text_width(text: &str, font_size: f64, style: FontStyle) -> f64 {
    let table = advance_table(style);
    let total_units: u64 = text
        .chars()
        .map(|c| {
            let cp = c as u32;
            let units = if cp <= 0xFFFF { table[cp as usize] } else { 0 };
            u64::from(if units == 0 {
                FALLBACK_ADVANCE_UNITS
            } else {
                units
            })
        })
        .sum();
    total_units as f64 / f64::from(data::UNITS_PER_EM) * font_size
}

/// Width of the widest of `labels` at `font_size` — the correct way to size a box
/// to fit any of a set of strings. Returns `0.0` for an empty set.
///
/// Prefer this over picking the longest-by-`len()` label and measuring it: more
/// characters does not mean more width (`"iiiii"` is narrower than `"MMM"`), and
/// `len()` counts bytes, not glyphs.
pub(crate) fn widest_text_width<'a>(
    labels: impl IntoIterator<Item = &'a str>,
    font_size: f64,
    style: FontStyle,
) -> f64 {
    labels
        .into_iter()
        .map(|s| measure_text_width(s, font_size, style))
        .fold(0.0, f64::max)
}

/// Mean rendered width of one character at `font_size`, for the few sites that
/// invert the relationship (fitting a character *budget* into an available
/// width) and so have no concrete string to measure.
pub(crate) fn mean_char_width(font_size: f64) -> f64 {
    font_size * data::MEAN_ADVANCE_EM
}

/// Returns the lazily-decoded dense advance table (font units, indexed by BMP
/// codepoint; 0 = no glyph) for `style`.
fn advance_table(style: FontStyle) -> &'static [u16; 0x10000] {
    static REGULAR: OnceLock<Box<[u16; 0x10000]>> = OnceLock::new();
    static ITALIC: OnceLock<Box<[u16; 0x10000]>> = OnceLock::new();
    static BOLD: OnceLock<Box<[u16; 0x10000]>> = OnceLock::new();
    static BOLD_ITALIC: OnceLock<Box<[u16; 0x10000]>> = OnceLock::new();
    match style {
        FontStyle::Regular => REGULAR.get_or_init(|| decode_rle(data::ADVANCE_RLE_REGULAR)),
        FontStyle::Italic => ITALIC.get_or_init(|| decode_rle(data::ADVANCE_RLE_ITALIC)),
        FontStyle::Bold => BOLD.get_or_init(|| decode_rle(data::ADVANCE_RLE_BOLD)),
        FontStyle::BoldItalic => {
            BOLD_ITALIC.get_or_init(|| decode_rle(data::ADVANCE_RLE_BOLD_ITALIC))
        }
    }
}

/// Expands a run-length-encoded advance table into a dense BMP array.
fn decode_rle(rle: &[(u16, u16)]) -> Box<[u16; 0x10000]> {
    let mut values: Vec<u16> = Vec::with_capacity(0x10000);
    for &(advance, len) in rle {
        values.resize(values.len() + len as usize, advance);
    }
    values
        .into_boxed_slice()
        .try_into()
        .expect("advance RLE must cover exactly the 65536 BMP codepoints")
}

#[cfg(test)]
mod tests {
    use super::*;

    const SIZE: f64 = 12.0;

    #[test]
    fn empty_string_has_zero_width() {
        assert_eq!(measure_text_width("", SIZE, FontStyle::Regular), 0.0);
    }

    #[test]
    fn wide_glyphs_measure_wider_than_narrow_ones() {
        let wide = measure_text_width("MMMM", SIZE, FontStyle::Regular);
        let narrow = measure_text_width("iiii", SIZE, FontStyle::Regular);
        assert!(
            wide > narrow,
            "M should be wider than i ({wide} vs {narrow})"
        );
    }

    #[test]
    fn digits_are_tabular() {
        // DejaVu digits share one advance, so any two equal-length digit strings
        // measure identically.
        let a = measure_text_width("100000", SIZE, FontStyle::Regular);
        let b = measure_text_width("888888", SIZE, FontStyle::Regular);
        assert_eq!(a, b);
    }

    #[test]
    fn bold_is_wider_than_regular() {
        let bold = measure_text_width("Frequency", SIZE, FontStyle::Bold);
        let regular = measure_text_width("Frequency", SIZE, FontStyle::Regular);
        assert!(bold > regular, "bold should be wider ({bold} vs {regular})");
    }

    #[test]
    fn width_scales_linearly_with_font_size() {
        let small = measure_text_width("Sample", 10.0, FontStyle::Regular);
        let big = measure_text_width("Sample", 20.0, FontStyle::Regular);
        assert!((big - 2.0 * small).abs() < 1e-9);
    }

    #[test]
    fn widest_picks_the_widest_not_the_longest() {
        // "WWW" (3 wide glyphs) is wider than "iiiiiiii" (8 narrow ones), so a
        // count-based heuristic would pick the wrong string.
        let labels = ["iiiiiiii", "WWW", "ab"];
        let widest = widest_text_width(labels, SIZE, FontStyle::Regular);
        let www = measure_text_width("WWW", SIZE, FontStyle::Regular);
        assert_eq!(widest, www);
    }

    #[test]
    fn widest_of_empty_is_zero() {
        let none: [&str; 0] = [];
        assert_eq!(widest_text_width(none, SIZE, FontStyle::Regular), 0.0);
    }

    #[test]
    fn non_ascii_measured_by_glyph_not_byte_length() {
        // A superscript two is a single narrow glyph; measured by chars it is far
        // narrower than the 2-byte UTF-8 length would suggest, and narrower than
        // a normal digit.
        let sup = measure_text_width("\u{00B2}", SIZE, FontStyle::Regular);
        let two = measure_text_width("2", SIZE, FontStyle::Regular);
        assert!(
            sup > 0.0 && sup < two,
            "superscript should be narrow ({sup} vs {two})"
        );
    }

    #[test]
    fn unknown_glyph_falls_back_to_one_em() {
        // An astral-plane codepoint (no DejaVu glyph) reserves one em.
        let emoji = measure_text_width("\u{1F600}", SIZE, FontStyle::Regular);
        assert!((emoji - SIZE).abs() < 1e-9);
    }

    /// Drift guard: every committed table must reproduce the advances of the face
    /// it was generated from. Regenerate `data.rs` if this fails after a font swap.
    #[test]
    fn committed_table_matches_font() {
        // (style, primary face file, fallback when the primary is not bundled) —
        // mirrors examples/gen_text_metrics.rs.
        let cases = [
            (FontStyle::Regular, "DejaVuSans.ttf", None),
            (FontStyle::Italic, "DejaVuSans-Oblique.ttf", None),
            (FontStyle::Bold, "DejaVuSans-Bold.ttf", None),
            (
                FontStyle::BoldItalic,
                "DejaVuSans-BoldOblique.ttf",
                Some("DejaVuSans-Bold.ttf"),
            ),
        ];
        for (style, primary, fallback) in cases {
            let dir = format!("{}/assets/fonts", env!("CARGO_MANIFEST_DIR"));
            let primary_path = format!("{dir}/{primary}");
            let path = match (std::path::Path::new(&primary_path).exists(), fallback) {
                (true, _) => primary_path,
                (false, Some(fb)) => format!("{dir}/{fb}"),
                (false, None) => primary_path,
            };
            let bytes = std::fs::read(&path).expect("read bundled font");
            let face = ttf_parser::Face::parse(&bytes, 0).expect("parse font");
            assert_eq!(u16::from(face.units_per_em()), data::UNITS_PER_EM);

            let table = advance_table(style);
            for cp in 0u32..=0xFFFF {
                let expected = char::from_u32(cp)
                    .and_then(|c| face.glyph_index(c))
                    .and_then(|g| face.glyph_hor_advance(g))
                    .unwrap_or(0);
                assert_eq!(
                    table[cp as usize], expected,
                    "{style:?} mismatch at U+{cp:04X}"
                );
            }
        }
    }

    /// Drift guard for the vertical metrics: every committed `VMetrics` must
    /// reproduce the face it was generated from (hhea ascent/descent/line-gap and
    /// the 'H'/'x' outline tops). Mirrors `vmetrics()` in gen_text_metrics.rs.
    #[test]
    fn committed_vmetrics_match_font() {
        let cases = [
            (FontStyle::Regular, "DejaVuSans.ttf", None),
            (FontStyle::Italic, "DejaVuSans-Oblique.ttf", None),
            (FontStyle::Bold, "DejaVuSans-Bold.ttf", None),
            (
                FontStyle::BoldItalic,
                "DejaVuSans-BoldOblique.ttf",
                Some("DejaVuSans-Bold.ttf"),
            ),
        ];
        for (style, primary, fallback) in cases {
            let dir = format!("{}/assets/fonts", env!("CARGO_MANIFEST_DIR"));
            let primary_path = format!("{dir}/{primary}");
            let path = match (std::path::Path::new(&primary_path).exists(), fallback) {
                (true, _) => primary_path,
                (false, Some(fb)) => format!("{dir}/{fb}"),
                (false, None) => primary_path,
            };
            let bytes = std::fs::read(&path).expect("read bundled font");
            let face = ttf_parser::Face::parse(&bytes, 0).expect("parse font");
            let glyph_top = |ch: char| {
                face.glyph_index(ch)
                    .and_then(|g| face.glyph_bounding_box(g))
                    .map(|bb| bb.y_max)
            };
            let cap = glyph_top('H')
                .or_else(|| face.capital_height())
                .unwrap_or(face.ascender());
            let x = glyph_top('x')
                .or_else(|| face.x_height())
                .unwrap_or((f32::from(cap) * 0.72) as i16);

            let m = vmetrics(style);
            assert_eq!(m.ascent, face.ascender(), "{style:?} ascent");
            assert_eq!(m.descent, -face.descender(), "{style:?} descent");
            assert_eq!(m.line_gap, face.line_gap(), "{style:?} line_gap");
            assert_eq!(m.cap_height, cap, "{style:?} cap_height");
            assert_eq!(m.x_height, x, "{style:?} x_height");
        }
    }

    #[test]
    fn line_height_covers_ascent_and_descent() {
        // A row shorter than ascent+descent would clip; line_height must cover it
        // (equals it exactly for DejaVu, whose line_gap is 0).
        let lh = line_height(SIZE, FontStyle::Regular);
        let box_h = ascent(SIZE, FontStyle::Regular) + descent(SIZE, FontStyle::Regular);
        assert!(
            lh >= box_h - 1e-9,
            "line_height {lh} < ascent+descent {box_h}"
        );
    }

    #[test]
    fn line_height_exceeds_cap_height() {
        // Sizing a row to cap height alone (a common bug) clips descenders.
        assert!(line_height(SIZE, FontStyle::Regular) > cap_height(SIZE, FontStyle::Regular));
    }

    #[test]
    fn center_offset_is_half_cap_height() {
        let co = center_offset(SIZE, FontStyle::Regular);
        assert!((co - cap_height(SIZE, FontStyle::Regular) / 2.0).abs() < 1e-9);
    }

    #[test]
    fn x_height_below_cap_below_ascent() {
        let s = FontStyle::Regular;
        assert!(x_height(SIZE, s) < cap_height(SIZE, s));
        assert!(cap_height(SIZE, s) < ascent(SIZE, s));
    }

    #[test]
    fn vertical_metrics_scale_linearly_with_size() {
        let a = line_height(10.0, FontStyle::Regular);
        let b = line_height(20.0, FontStyle::Regular);
        assert!((b - 2.0 * a).abs() < 1e-9);
    }
}

#[cfg(test)]
mod probe_scratch2 {
    use super::*;
    #[test]
    fn probe_digit_widths() {
        for d in "0123456789".chars() {
            println!(
                "{d}: {:.3}",
                measure_text_width(&d.to_string(), 12.0, FontStyle::Regular)
            );
        }
    }
}