Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

cad_text_realization/
face_metrics.rs

1//! Face metrics that a sizing basis other than the em needs.
2
3/// The em of a text whose Windows font cell is `cell` tall, in the cell's
4/// units. The cell is the face's OS/2 usWinAscent + usWinDescent, with no
5/// hhea or typographic fallback (GFX `windows_cell_height`). `None` for bytes
6/// that are not a face, or a face without an OS/2 cell.
7pub fn windows_cell_em(font_bytes: &[u8], face_index: u32, cell: f64) -> Option<f64> {
8    let face = ttf_parser::Face::parse(font_bytes, face_index).ok()?;
9    let os2 = face.tables().os2?;
10    let win = f64::from(os2.windows_ascender()) - f64::from(os2.windows_descender());
11    (win > 0.0 && cell.is_finite()).then(|| cell * f64::from(face.units_per_em()) / win)
12}
13
14#[cfg(test)]
15mod tests {
16    use super::*;
17
18    const FONT: &[u8] = include_bytes!(concat!(
19        env!("CARGO_MANIFEST_DIR"),
20        "/tests/fixtures/stroke_font/kicad-stroke.ttf"
21    ));
22
23    #[test]
24    fn a_cell_height_is_scaled_by_units_per_em_over_the_os2_cell() {
25        let face = ttf_parser::Face::parse(FONT, 0).unwrap();
26        let os2 = face.tables().os2.unwrap();
27        let win = f64::from(os2.windows_ascender()) - f64::from(os2.windows_descender());
28        let em = windows_cell_em(FONT, 0, 2.0).unwrap();
29        assert_eq!(em, 2.0 * f64::from(face.units_per_em()) / win);
30        assert_eq!(windows_cell_em(b"not a face", 0, 2.0), None);
31    }
32}