git clone https://garage44.eu/jeroen/pinnacle.git.. /ttf/src/lib.rs
//! Pinnacle's TrueType reader.
//!
//! It reads the tables a glyph needs (`cmap` formats 4 and 12, `head`,
//! `hhea`, `hmtx`, `maxp`, `loca`, `glyf`, simple and compound glyphs) and
//! traces a glyph's contours, as lines and quadratic Béziers scaled to
//! pixels, into a [`Pen`]; turning them into pixels is the vector
//! renderer's work. No hinting.
#![no_std]
extern crate alloc;
pub mod layout;
use alloc::vec::Vec;
/// What an outline is traced into, in pixels, y down.
pub trait Pen {
fn move_to(&mut self, x: f32, y: f32);
fn line_to(&mut self, x: f32, y: f32);
fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32);
fn close(&mut self);
}
fn be16(d: &[u8], at: usize) -> Option<u16> {
Some(u16::from_be_bytes(d.get(at..at + 2)?.try_into().ok()?))
}
fn bei16(d: &[u8], at: usize) -> Option<i16> {
Some(be16(d, at)? as i16)
}
fn be32(d: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(d.get(at..at + 4)?.try_into().ok()?))
}
fn floor(x: f32) -> f32 {
let i = x as i32 as f32;
if i > x { i - 1.0 } else { i }
}
fn ceil(x: f32) -> f32 {
let i = x as i32 as f32;
if i < x { i + 1.0 } else { i }
}
pub struct Font<'a> {
data: &'a [u8],
units_per_em: f32,
long_loca: bool,
glyphs: u16,
h_metrics: u16,
/// The character map's subtable, and its format: 0 when there is none.
cmap: usize,
cmap_format: u16,
/// The map is a symbol font's (3, 0), whose characters are at U+F000
/// and up.
symbol_only: bool,
hmtx: usize,
loca: usize,
glyf: usize,
pub ascender: i16,
pub descender: i16,
pub line_gap: i16,
}
/// A glyph's metrics at a size, in pixels: its bitmap's size and where the
/// bitmap's left edge and bottom edge sit from the pen (y up).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Metrics {
pub width: usize,
pub height: usize,
pub xmin: i32,
pub ymin: i32,
pub advance: f32,
}
#[derive(Clone, Copy, Debug)]
struct Point {
x: f32,
y: f32,
on: bool,
}
impl<'a> Font<'a> {
pub fn parse(data: &'a [u8]) -> Option<Font<'a>> {
let tables = be16(data, 4)?;
let table = |tag: &[u8; 4]| -> Option<usize> {
(0..usize::from(tables))
.map(|i| 12 + i * 16)
.find(|&at| data.get(at..at + 4) == Some(tag))
.and_then(|at| be32(data, at + 8).map(|o| o as usize))
};
let head = table(b"head")?;
let hhea = table(b"hhea")?;
let maxp = table(b"maxp")?;
// The best Unicode subtable: format 12 (full Unicode) over format 4,
// and a symbol font's (3, 0) when there is no other. A font with no
// `cmap` at all (a PDF's subset) is read too, by glyph only.
let mut best = None;
let mut symbol = None;
if let Some(cmap) = table(b"cmap") {
for i in 0..usize::from(be16(data, cmap + 2)?) {
let at = cmap + 4 + i * 8;
let (platform, encoding) = (be16(data, at)?, be16(data, at + 2)?);
let offset = cmap + be32(data, at + 4)? as usize;
let format = be16(data, offset)?;
let unicode = platform == 0 || (platform == 3 && (encoding == 1 || encoding == 10));
if unicode && (format == 12 || (format == 4 && best.is_none())) {
best = Some((offset, format));
}
if platform == 3 && encoding == 0 && format == 4 {
symbol = Some((offset, format));
}
}
}
let symbol_only = best.is_none() && symbol.is_some();
let (cmap, cmap_format) = best.or(symbol).unwrap_or((0, 0));
Some(Font {
data,
units_per_em: f32::from(be16(data, head + 18)?),
long_loca: be16(data, head + 50)? == 1,
glyphs: be16(data, maxp + 4)?,
h_metrics: be16(data, hhea + 34)?,
cmap,
cmap_format,
symbol_only,
hmtx: table(b"hmtx")?,
loca: table(b"loca")?,
glyf: table(b"glyf")?,
ascender: bei16(data, hhea + 4)?,
descender: bei16(data, hhea + 6)?,
line_gap: bei16(data, hhea + 8)?,
})
}
/// The glyph for a character, 0 (the missing glyph) when there is none.
pub fn glyph_index(&self, c: char) -> u16 {
let c = c as u32;
match self.lookup(c) {
Some(g) if g != 0 => g,
// A symbol font maps its characters at U+F000 and up too.
_ if self.symbol_only && c < 0x100 => self.lookup(0xf000 + c).unwrap_or(0),
_ => 0,
}
}
/// How many glyphs the font has: a glyph index is below it.
pub fn glyph_count(&self) -> u16 {
self.glyphs
}
/// The font's units to the em, which its tables' numbers are in.
pub fn units_per_em(&self) -> f32 {
self.units_per_em
}
/// The font's bytes, for the tables this reader leaves to others
/// ([`layout`]).
pub fn data(&self) -> &'a [u8] {
self.data
}
/// Where a table starts, if the font has it.
pub fn table(&self, tag: &[u8; 4]) -> Option<usize> {
let d = self.data;
(0..usize::from(be16(d, 4)?))
.map(|i| 12 + i * 16)
.find(|&at| d.get(at..at + 4) == Some(tag))
.and_then(|at| be32(d, at + 8).map(|o| o as usize))
}
fn lookup(&self, c: u32) -> Option<u16> {
let d = self.data;
let t = self.cmap;
if self.cmap_format == 0 {
return None;
}
if self.cmap_format == 12 {
let groups = be32(d, t + 12)? as usize;
let (mut low, mut high) = (0, groups);
while low < high {
let mid = (low + high) / 2;
let at = t + 16 + mid * 12;
let (start, end) = (be32(d, at)?, be32(d, at + 4)?);
if c < start {
high = mid;
} else if c > end {
low = mid + 1;
} else {
return Some((be32(d, at + 8)? + c - start) as u16);
}
}
return None;
}
if c > 0xffff {
return None;
}
let segments = usize::from(be16(d, t + 6)? / 2);
let ends = t + 14;
let starts = ends + segments * 2 + 2;
let deltas = starts + segments * 2;
let ranges = deltas + segments * 2;
for s in 0..segments {
let end = u32::from(be16(d, ends + s * 2)?);
if c > end {
continue;
}
let start = u32::from(be16(d, starts + s * 2)?);
if c < start {
return None;
}
let delta = be16(d, deltas + s * 2)?;
let range = usize::from(be16(d, ranges + s * 2)?);
if range == 0 {
return Some((c as u16).wrapping_add(delta));
}
let at = ranges + s * 2 + range + (c - start) as usize * 2;
let g = be16(d, at)?;
return Some(if g == 0 { 0 } else { g.wrapping_add(delta) });
}
None
}
fn advance_units(&self, glyph: u16) -> u16 {
let i = usize::from(glyph.min(self.h_metrics.saturating_sub(1)));
be16(self.data, self.hmtx + i * 4).unwrap_or(0)
}
fn glyph_data(&self, glyph: u16) -> Option<&'a [u8]> {
if glyph >= self.glyphs {
return None;
}
let g = usize::from(glyph);
let (start, end) = if self.long_loca {
(
be32(self.data, self.loca + g * 4)? as usize,
be32(self.data, self.loca + g * 4 + 4)? as usize,
)
} else {
(
usize::from(be16(self.data, self.loca + g * 2)?) * 2,
usize::from(be16(self.data, self.loca + g * 2 + 2)?) * 2,
)
};
(end > start)
.then(|| self.data.get(self.glyf + start..self.glyf + end))
.flatten()
}
/// A glyph's contours in font units, compound glyphs flattened.
fn contours(&self, glyph: u16, depth: u8) -> Vec<Vec<Point>> {
let Some(g) = self.glyph_data(glyph) else {
return Vec::new();
};
let contours = bei16(g, 0).unwrap_or(0);
if contours >= 0 {
return simple_glyph(g, contours as usize).unwrap_or_default();
}
// Compound: components, each moved (and maybe scaled).
let mut out = Vec::new();
let mut at = 10;
while let (Some(flags), Some(index)) = (be16(g, at), be16(g, at + 2)) {
at += 4;
let (dx, dy) = if flags & 1 != 0 {
let r = (bei16(g, at), bei16(g, at + 2));
at += 4;
(f32::from(r.0.unwrap_or(0)), f32::from(r.1.unwrap_or(0)))
} else {
let r = (g.get(at).map(|&b| b as i8), g.get(at + 1).map(|&b| b as i8));
at += 2;
(f32::from(r.0.unwrap_or(0)), f32::from(r.1.unwrap_or(0)))
};
let f2dot14 = |at: usize| f32::from(bei16(g, at).unwrap_or(0)) / 16384.0;
let (mut a, mut b, mut c, mut d) = (1.0, 0.0, 0.0, 1.0);
if flags & 0x08 != 0 {
a = f2dot14(at);
d = a;
at += 2;
} else if flags & 0x40 != 0 {
a = f2dot14(at);
d = f2dot14(at + 2);
at += 4;
} else if flags & 0x80 != 0 {
a = f2dot14(at);
b = f2dot14(at + 2);
c = f2dot14(at + 4);
d = f2dot14(at + 6);
at += 8;
}
if depth < 8 {
for contour in self.contours(index, depth + 1) {
out.push(
contour
.into_iter()
.map(|p| Point {
x: a * p.x + c * p.y + dx,
y: b * p.x + d * p.y + dy,
on: p.on,
})
.collect(),
);
}
}
if flags & 0x20 == 0 {
break;
}
}
out
}
/// Traces `c` at `px` pixels to the em into `pen`, in pixels from the
/// top-left of its box (y down), and returns the box's metrics: the
/// outline fits a `width` × `height` mask.
pub fn outline(&self, c: char, px: f32, pen: &mut impl Pen) -> Metrics {
self.outline_glyph(self.glyph_index(c), px, pen)
}
/// A glyph's advance at `px` pixels to the em.
pub fn glyph_advance(&self, glyph: u16, px: f32) -> f32 {
f32::from(self.advance_units(glyph)) * px / self.units_per_em
}
/// Traces glyph `glyph` as [`Font::outline`] traces a character's: by
/// index, as a shaper's output or a PDF's text names glyphs.
pub fn outline_glyph(&self, glyph: u16, px: f32, pen: &mut impl Pen) -> Metrics {
let scale = px / self.units_per_em;
let advance = f32::from(self.advance_units(glyph)) * scale;
let contours = self.contours(glyph, 0);
let points = contours.iter().flatten();
let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
for p in points {
x0 = x0.min(p.x);
y0 = y0.min(p.y);
x1 = x1.max(p.x);
y1 = y1.max(p.y);
}
if contours.is_empty() || x1 <= x0 || y1 <= y0 {
return Metrics {
advance,
..Default::default()
};
}
let (left, bottom) = (floor(x0 * scale), floor(y0 * scale));
let (right, top) = (ceil(x1 * scale), ceil(y1 * scale));
let to_px = |p: &Point| (p.x * scale - left, top - p.y * scale);
for contour in &contours {
let segments = segments(contour);
let Some((start, _)) = segments.first() else {
continue;
};
let (x, y) = to_px(start);
pen.move_to(x, y);
for (_, segment) in &segments {
match segment {
Segment::Line(p) => {
let (x, y) = to_px(p);
pen.line_to(x, y);
}
Segment::Quad(ctrl, p) => {
let ((cx, cy), (x, y)) = (to_px(ctrl), to_px(p));
pen.quad_to(cx, cy, x, y);
}
}
}
pen.close();
}
Metrics {
width: (right - left) as usize,
height: (top - bottom) as usize,
xmin: left as i32,
ymin: bottom as i32,
advance,
}
}
/// The line's ascent, descent (negative) and gap, in pixels at `px`.
pub fn line_metrics(&self, px: f32) -> (f32, f32, f32) {
let s = px / self.units_per_em;
(
f32::from(self.ascender) * s,
f32::from(self.descender) * s,
f32::from(self.line_gap) * s,
)
}
}
/// A simple glyph's contours: end points, instructions (skipped), flags,
/// then x and y as deltas.
fn simple_glyph(g: &[u8], contours: usize) -> Option<Vec<Vec<Point>>> {
let ends: Vec<usize> = (0..contours)
.map(|i| be16(g, 10 + i * 2).map(usize::from))
.collect::<Option<_>>()?;
let count = ends.last().map_or(0, |e| e + 1);
let mut at = 10 + contours * 2;
at += 2 + usize::from(be16(g, at)?);
let mut flags = Vec::with_capacity(count);
while flags.len() < count {
let f = *g.get(at)?;
at += 1;
flags.push(f);
if f & 8 != 0 {
let repeat = *g.get(at)?;
at += 1;
for _ in 0..repeat {
flags.push(f);
}
}
}
let mut coords = |short: u8, same: u8| -> Option<Vec<f32>> {
let mut v = 0i32;
let mut out = Vec::with_capacity(count);
for &f in &flags[..count] {
if f & short != 0 {
let d = i32::from(*g.get(at)?);
at += 1;
v += if f & same != 0 { d } else { -d };
} else if f & same == 0 {
v += i32::from(bei16(g, at)?);
at += 2;
}
out.push(v as f32);
}
Some(out)
};
let xs = coords(0x02, 0x10)?;
let ys = coords(0x04, 0x20)?;
let mut out = Vec::with_capacity(contours);
let mut start = 0;
for end in ends {
out.push(
(start..=end)
.map(|i| Point {
x: xs[i],
y: ys[i],
on: flags[i] & 1 != 0,
})
.collect(),
);
start = end + 1;
}
Some(out)
}
enum Segment {
Line(Point),
Quad(Point, Point),
}
/// A contour as segments from point to point, with the on-curve points
/// TrueType leaves implied between two off-curve ones.
fn segments(contour: &[Point]) -> Vec<(Point, Segment)> {
let n = contour.len();
if n < 2 {
return Vec::new();
}
let mid = |a: &Point, b: &Point| Point {
x: (a.x + b.x) / 2.0,
y: (a.y + b.y) / 2.0,
on: true,
};
// Start on an on-curve point (or between two off-curve ones).
let first = match contour.iter().position(|p| p.on) {
Some(i) => contour[i],
None => mid(&contour[0], &contour[1]),
};
let start = contour.iter().position(|p| p.on).unwrap_or(0);
let mut out = Vec::new();
let mut current = first;
let mut control: Option<Point> = None;
for k in 1..=n {
let p = contour[(start + k) % n];
let p = if k == n { first } else { p };
match (p.on, control) {
(true, None) => {
out.push((current, Segment::Line(p)));
current = p;
}
(true, Some(c)) => {
out.push((current, Segment::Quad(c, p)));
current = p;
control = None;
}
(false, None) => control = Some(p),
(false, Some(c)) => {
let m = mid(&c, &p);
out.push((current, Segment::Quad(c, m)));
current = m;
control = Some(p);
}
}
}
if let Some(c) = control {
out.push((current, Segment::Quad(c, first)));
}
out
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
/// Counts what an outline draws, and where its points fall.
#[derive(Default)]
struct Tally {
contours: usize,
segments: usize,
bounds: (f32, f32, f32, f32),
}
impl Tally {
fn see(&mut self, x: f32, y: f32) {
let b = &mut self.bounds;
*b = (b.0.min(x), b.1.min(y), b.2.max(x), b.3.max(y));
}
}
impl Pen for Tally {
fn move_to(&mut self, x: f32, y: f32) {
self.contours += 1;
self.see(x, y);
}
fn line_to(&mut self, x: f32, y: f32) {
self.segments += 1;
self.see(x, y);
}
fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
self.segments += 1;
self.see(cx, cy);
self.see(x, y);
}
fn close(&mut self) {}
}
#[test]
fn the_system_font_reads() {
let data = std::fs::read(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../fonts/AdwaitaSans-Regular.ttf"
))
.unwrap();
let font = Font::parse(&data).expect("a TrueType font");
assert_ne!(font.glyph_index('A'), 0);
let mut tally = Tally::default();
let m = font.outline('O', 40.0, &mut tally);
assert!(m.width > 10 && m.height > 20, "{m:?}");
assert!(m.advance > 15.0);
assert_eq!(tally.contours, 2, "an O is two contours");
assert!(tally.segments >= 8);
// The outline stays inside the box it reports.
let (x0, y0, x1, y1) = tally.bounds;
assert!(
x0 >= 0.0 && y0 >= 0.0 && x1 <= m.width as f32 && y1 <= m.height as f32,
"{:?} {m:?}",
tally.bounds
);
}
}