zztaeha

Rust types

141 structs, enums, traits and aliases in daegun 2.0.0, as the compiler exports them, filed by area. Each lists its fields or variants with what they hold, the traits it implements, and an example that was compiled and run against 2.0.0.

The examples assume font, an open Font, inside a function that returns daegun::Result. A type marked #[non_exhaustive] may gain fields or variants in a later release: build it with its constructor or Default, and match it with a _ arm.

Base

What everything else is built on: errors and their kinds, tags, glyph ids, boxes and orientation. These live at the root of the crate.

Bounds
pub struct Bounds {
    pub x_min: f64,
    pub y_min: f64,
    pub x_max: f64,
    pub y_max: f64,
}

A box with y up, from its lower left corner (x_min, y_min) to its upper right (x_max, y_max).

Font::glyph_bounds returns one for a glyph's outline, Font::bounds the box the font itself states around all of its glyphs, Font::colr_clip_box the clip box of a color glyph, and Path::bounds the box of a path you hold. Each answers in an Option, for its own reason. Font::glyph_bounds gives None for a glyph that draws nothing, which has no box, and that is not the same as a box of zero size. Font::bounds gives None only where the font's head table is too short to hold the box.

From the three calls on a font the edges are f64 in the units of the font, and a glyph's box is measured from the origin of the glyph on its baseline. Y grows upward, so y_min is the bottom edge, and it is negative for a glyph that reaches below the baseline. A size in pixels is (x_max - x_min) * px / f64::from(font.units_per_em()). Path::bounds answers in the units the path was drawn in, so the box of a path that Font::prepared_outline filled is in pixels.

It is a plain value whose public fields are all it is: build one with a literal, and Bounds::default() is all zeros.

use daegun::{Bounds, GlyphId, Location};

let glyph = font.glyph_id('A').unwrap_or(GlyphId::NOTDEF);
if let Some(Bounds { x_min, y_min, x_max, y_max }) = font.glyph_bounds(glyph, &Location::default()) {
    let (width, height) = (x_max - x_min, y_max - y_min);
    // Inter's A is 1309 units wide and 1490 tall, and its bottom edge is on the baseline.
}
x_min: f64
The left edge.
y_min: f64
The bottom edge. Negative where the box reaches below the baseline.
x_max: f64
The right edge.
y_max: f64
The top edge.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
Error
pub struct Error {
    /* private fields */
}

Why a call failed: a kind for code to act on, and a message for people to read.

Every call in daegun that can fail returns a Result with this as its error. The one exception is converting a GlyphId to a u16, which fails with the standard library's TryFromIntError. Error::kind gives the ErrorKind, which is what code should branch on, and Error::message gives the text, which is for a log or an error dialog.

You can't build one yourself: its fields are private and nothing public constructs it. Nearly every message is a static string, and an error with one of those allocates nothing. It is Clone, Send and Sync, and two errors are equal, and hash alike, when their kind and their message's text match.

use daegun::{Error, ErrorKind, Font};

let error: Error = Font::from_bytes(b"not a font").unwrap_err();
// The kind is for code, the message for people.
assert_eq!(error.kind(), ErrorKind::Malformed);
assert_eq!(error.message(), "TTF/OTF: file too short");
assert_eq!(error.to_string(), error.message());

// Where a function returns std::io::Result, `?` makes this conversion.
let io: std::io::Error = error.into();
assert_eq!(io.kind(), std::io::ErrorKind::InvalidData);
impl Display
Writes the message, the same text Error::message returns.
impl Error
The standard error trait, which is what lets ? turn a daegun error into a Box<dyn std::error::Error>. It reports no source.
impl From<Error> for Error
Turns a daegun error into a std::io::Error, so a loader that returns std::io::Result can use ? both on reading the file and on opening the font. Its kind is InvalidInput for ErrorKind::InvalidArgument and InvalidData for every other kind. The daegun error is kept inside, where get_ref() finds it. It needs the std feature, which is on by default.
  • Implements: Clone, Debug, Display, Eq, Error, From<Error> for Error, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
ErrorKind
#[non_exhaustive]
pub enum ErrorKind {
    Malformed,
    Unsupported,
    Missing,
    InvalidArgument,
    LimitExceeded,
    NoOutline,
    Overflow,
}

What kind of failure an Error is, so code can decide what to do about it.

Error::kind returns one. Each kind calls for its own reaction: a malformed or unsupported font is one to turn away, a missing table means the font lacks what the call reads, an invalid argument is yours to fix, and a glyph with no outline is one to draw another way or to skip.

It is #[non_exhaustive]: a later release may add a kind, so a match on it needs a _ arm.

use daegun::outline::Path;
use daegun::{ErrorKind, GlyphId, Location};

// Noto Color Emoji holds bitmaps and no outlines, so asking it for one fails.
let glyph = font.glyph_id('😀').unwrap_or(GlyphId::NOTDEF);
let mut path = Path::default();
if let Err(error) = font.outline(glyph, &Location::default(), &mut path) {
    match error.kind() {
        ErrorKind::NoOutline => { /* draw its bitmap instead, if the font has one */ }
        ErrorKind::Malformed | ErrorKind::LimitExceeded => { /* give up on this font */ }
        // The enum may grow, so a match on it needs this arm.
        _ => { /* report error.message() */ }
    }
}
Malformed
Font data the call needs is broken: cut short, out of range or inconsistent with itself.
Unsupported
The data is in a format or version daegun doesn't read.
Missing
A table or record the call needs isn't in the font.
InvalidArgument
An argument is out of range or not a number, or text handed to parse is not what the type reads.
LimitExceeded
The font asks for more work or memory than daegun allows one font, as a hostile font can.
NoOutline
There is no outline to draw for the glyph: the font has no outlines at all, as a font of bitmaps alone has none, or the glyph id is past the font's last glyph. Font::quads also answers it for a glyph that draws nothing, such as a space, where Font::outline succeeds and draws nothing.
Overflow
A value outgrows what its type can hold once scaled, such as an outline point past the range of f32.
impl Display
Writes a short lowercase description of the kind: malformed font data, unsupported format or version, missing table or record, invalid argument, limit exceeded, no outline or overflow.
  • Implements: Clone, Copy, Debug, Display, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
GlyphId
pub struct GlyphId(

A glyph's index in its font.

A font numbers its glyphs from 0, and the calls that name a glyph take or return one of these. An id means something only in the font it came from: glyph 2 of one font and glyph 2 of another are unrelated. Glyph 0 is .notdef, the glyph a font draws for a character it has none for, and GlyphId::NOTDEF names it.

Font::glyph_id gives the glyph for a character, and shaping gives the glyphs of a run in ShapedRun::glyphs. It is a plain wrapper around a u32 with a public field, so GlyphId(7) builds one and .0 reads the number. The number is 32 bits wide because a font may hold more than 65,535 glyphs.

use daegun::GlyphId;

let glyph = font.glyph_id('A').unwrap_or(GlyphId::NOTDEF);
// Inter keeps its A at index 2.
assert_eq!(glyph, GlyphId(2));
assert_eq!(glyph.0, 2);
assert_eq!(glyph.to_string(), "2");

// To plain numbers and back.
let index: u32 = glyph.into();
let narrow = u16::try_from(glyph).expect("Inter has fewer than 65,536 glyphs");
assert_eq!(GlyphId::from(narrow), GlyphId::from(index));
assert!(u16::try_from(GlyphId(70_000)).is_err());
u32
The index. 0 is the font's .notdef glyph.
impl Display
Writes the index as a plain number, so GlyphId(7) prints as 7.
impl From<GlyphId> for u32
The index as a u32.
impl From<u16>
The glyph with this index, from the 16-bit id that most font tables store.
impl From<u32>
The glyph with this index.
impl TryFrom<GlyphId> for u16
The index as a u16, for a table that stores 16-bit ids. An index above 65,535 is an error. The error is the standard library's TryFromIntError, not daegun's Error, so ? does not carry it out of a function that returns daegun::Result: map it, or test the index first.
  • Implements: Clone, Copy, Debug, Default, Display, Eq, From<GlyphId> for u32, From<u16>, From<u32>, Hash, Ord, PartialEq, PartialOrd, TryFrom<GlyphId> for u16.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
Orientation
pub enum Orientation {
    Horizontal,
    Vertical,
}

Whether a measurement runs along a horizontal line of text or a vertical one.

Calls that measure along the line take one, Font::advance, Font::advances, Font::ligature_carets, Font::caret_positions and Font::line_metrics among them. It picks which way the call measures: across the page or down it.

It has two variants and will not gain a third, so a match on it needs no _ arm. The default is Horizontal.

use daegun::{GlyphId, Location, Orientation};

let glyph = font.glyph_id('A').unwrap_or(GlyphId::NOTDEF);
let across = font.advance(glyph, &Location::default(), Orientation::Horizontal);
let down = font.advance(glyph, &Location::default(), Orientation::Vertical);
// Inter's A moves the pen 1413 units along a horizontal line, and 2478 down a vertical one.
assert_eq!((across, down), (1413.0, 2478.0));
assert_eq!(Orientation::default(), Orientation::Horizontal);
Horizontal
Along a horizontal line, whether it reads left to right or right to left. Advances are widths. The default.
Vertical
Down a vertical line, top to bottom. Advances are heights.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
Result
pub type Result<T, E = Error> = core::result::Result<T, E>;

The standard Result with daegun's Error as its error type.

Every call that can fail returns it, so a function of yours that calls daegun can return daegun::Result<T> and use ?.

The error type is a default, not fixed. Result<T, E> with two arguments still names the standard type, so importing this alias does not get in the way of your other results.

use daegun::{Font, Result};

fn glyph_count(bytes: &[u8]) -> Result<u32> {
    let font = Font::from_bytes(bytes)?;
    Ok(font.glyph_count())
}

// `inter` holds the bytes of Inter's font file.
assert_eq!(glyph_count(&inter)?, 2937);
assert!(glyph_count(b"not a font").is_err());
Tag
pub struct Tag(/* private */);

A four-byte OpenType tag: the name of a table, script, language, feature or variation axis.

Fonts name their parts with four characters: wght is the weight axis, liga the feature for ligatures, GSUB a table. A tag holds those four bytes. Tag::new(b"wght") builds one at compile time, and parsing a string builds one at run time.

A name shorter than four characters is padded with spaces, as fonts store it: the Lao script is lao and a space. Parsing adds the padding for you. Tag::new takes exactly four bytes, so there you write the space yourself.

Tags compare and sort as the big-endian number their bytes spell, which is the order fonts sort them in. That puts capitals before lowercase, so GSUB sorts before cmap.

Tag::new and the From conversions take any bytes, since a font may hold a tag that is not printable. Only parsing is strict.

use daegun::Tag;

// The weight axis, to ask a variable font for a bold instance.
let weight = Tag::new(b"wght");
let bold = font.location(&[(weight, 700.0)]);

// From text, where a short tag gets its padding.
let lao: Tag = "lao".parse()?;
assert_eq!(lao, Tag::new(b"lao "));
assert_eq!(weight.to_string(), "wght");

// As the number its bytes spell, and back.
assert_eq!(u32::from(weight), 0x7767_6874);
assert_eq!(Tag::from(0x7767_6874), weight);
assert!(Tag::new(b"GSUB") < Tag::new(b"cmap"));
impl Display
Writes the four bytes as four characters, padding included, so Tag::new(b"lao ") prints as lao and a space. Each byte is written as the character with that number and nothing is escaped: a byte above 0x7F becomes a character of two bytes, and a control byte is written as it is. To print a tag read from a font you do not trust, use {:?}, which escapes them. A width or alignment in the format string is ignored.
impl From<Tag> for u32
The big-endian number the four bytes spell: 0x77676874 for wght. The C API holds a tag in this form.
impl From<[u8; 4]>
The tag these four bytes spell, as Tag::new gives it.
impl From<u32>
The tag whose bytes spell this big-endian number, which is how OpenType stores a tag and how the C API passes one.
impl FromStr
Reads one to four printable ASCII characters, with any spaces after them, and pads the tag to four bytes with spaces: "lao" and "lao " give the same tag. Anything else is an error of kind ErrorKind::InvalidArgument: an empty string, more than four characters, a space at the start or in the middle, or a character outside printable ASCII.
  • Implements: Clone, Copy, Debug, Display, Eq, From<Tag> for u32, From<[u8; 4]>, From<u32>, FromStr, Hash, Ord, PartialEq, PartialOrd.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Fonts

Opening a font and asking what it is: its names, its tables, its variation axes and the locations they make, and the caches that keep its work. Font, Location and their kin live at the root of the crate.

Axis
#[non_exhaustive]
pub struct Axis {
    pub tag: Tag,
    pub min: f64,
    pub default: f64,
    pub max: f64,
    pub name_id: NameId,
    pub hidden: bool,
}

One axis of a variable font, as its fvar table describes it: a tag, a range and a default.

Font::axes returns one for each axis. The values are user coordinates, the scale you pass to Font::location. For the registered axes that is a weight from 1 to 1000 (wght), a width in percent of normal (wdth), an optical size in points (opsz), a slant in degrees (slnt) and 0 or 1 for italic (ital). A font may define axes of its own.

It is #[non_exhaustive], so you read its fields and can't build one by literal.

use daegun::{Axis, Location};

for Axis { tag, min, default, max, name_id, hidden, .. } in font.axes() {
    let label = font.name(name_id, &Location::default()).unwrap_or_else(|| tag.to_string());
    // A slider for the axis: its label, from min to max, starting at default.
}
// Inter's two are "Optical size" from 14 to 32 and "Weight" from 100 to 900.
tag: Tag
The axis's four-letter tag, such as wght. Font::location matches a value to its axis by this.
min: f64
The lowest value the axis takes.
default: f64
The value at the font's default instance, where an axis you don't set stays.
max: f64
The highest value the axis takes.
name_id: NameId
The ID of the axis's name in the name table, such as Weight, for a user interface. Read it with Font::name.
hidden: bool
True when the font asks for the axis to be kept out of user interfaces: one for software to set, not for a person to pick.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
Cache
#[non_exhaustive]
pub enum Cache {
    Shape,
    Instance,
    Outline,
    Raster,
}

Names one of a font's four caches, for the calls that set its budget, read what it holds or empty it.

A font keeps four caches, each with a budget in bytes of its own. Pass a Cache to Font::set_cache_budget, Font::cache_stats, Font::clear_cache or Font::set_cache_pool to say which one you mean.

The shape and instance caches fill by themselves as the font is used. The outline cache holds only what Font::prewarm puts in it, and the raster cache is off until it is given a budget. No cache changes a result: it only saves doing the work again.

It is #[non_exhaustive], so a match on it needs a _ arm: a later release may add a cache.

use daegun::{Cache, CacheStats};

// What the font holds in memory, cache by cache.
for cache in [Cache::Shape, Cache::Instance, Cache::Outline, Cache::Raster] {
    let CacheStats { entries, bytes, .. } = font.cache_stats(cache);
    // Log the two numbers. A font that has done nothing yet holds nothing.
    assert_eq!((entries, bytes), (0, 0));
}
Shape
Shaped runs, so that text shaped again is a lookup. Shaping and layout fill it, with the requests ShapeOptions says are kept. Its budget starts at 8 MiB.
Instance
What each location of a variable font has built: the tables it varies, what shaping, drawing and subsetting need there, and the file Font::instance made. That file, and what subsetting reads, are kept here at the default location too, and for a static font. One entry for each location, the least recently used out first, and the location used last always stays. Its budget starts at 64 MiB.
Outline
Outlines that Font::prewarm drew ahead, replayed when the glyph is drawn again. Its budget starts at 4 MiB.
Raster
Images of glyphs that a Rasterizer drew, lent again in place of being drawn. Its budget is 0 until you set one, so it starts off.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
CachePool
pub struct CachePool(/* private */);

One budget in bytes that the caches of several fonts share.

Each font has budgets of its own, which add up as you open more fonts. A pool caps the total instead. Every cache that joins draws on the one budget, and when the pool is over it, the least recently used entry across all of them goes first, whichever font it belongs to. So the fonts in use keep their entries, and the fonts lying idle give theirs up.

Make one with CachePool::new and add a cache to it with Font::set_cache_pool. Caches of different kinds may share a pool, shaped runs beside outlines. The budget is a ceiling the caches grow toward, never memory set aside.

A cache in a pool keeps to its own budget as well. A font that is dropped gives back what it held. Dropping the CachePool does not take its caches out: they go on sharing its budget until each leaves through Font::set_cache_pool or its font is dropped.

Without the threading feature a pool is neither Send nor Sync, like the fonts in it. With the feature it can be shared across threads, as a font can.

use daegun::shape::ShapeOptions;
use daegun::{Cache, CachePool, Font, Location};

// A megabyte for the shaped runs of both fonts together.
let pool = CachePool::new(1 << 20);
let fonts = [Font::from_bytes(&bytes("inter"))?, Font::from_bytes(&bytes("garamond"))?];
for font in &fonts {
    font.set_cache_pool(Cache::Shape, Some(&pool));
    let _ = font.shape("Shared", &Location::default(), &ShapeOptions::DEFAULT);
}
// Both runs are counted in the one pool, under the one budget.
assert_eq!(pool.stats().entries, 2);
assert!(pool.stats().bytes <= 1 << 20);
  • Implements: Debug.
  • Auto traits: Unpin, and with the threading feature RefUnwindSafe, Send, Sync, UnwindSafe.
CacheStats
#[non_exhaustive]
pub struct CacheStats {
    pub entries: usize,
    pub bytes: usize,
}

What a cache holds: how many entries, and how many bytes they count for.

Font::cache_stats returns one for a single cache, and CachePool::stats for a whole pool. Both numbers are as of the call.

It is #[non_exhaustive], so read its fields or destructure it with ... CacheStats::default() is an empty cache, to compare against.

use daegun::shape::ShapeOptions;
use daegun::{Cache, CacheStats, Location};

let _ = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT);
let CacheStats { entries, bytes, .. } = font.cache_stats(Cache::Shape);
assert_eq!(entries, 1);
assert!(bytes > 0);

font.clear_cache(Cache::Shape);
assert_eq!(font.cache_stats(Cache::Shape), CacheStats::default());
entries: usize
How many entries are held: runs, locations, outlines or images, depending on the cache.
bytes: usize
What those entries cost in bytes, as the cache counts them: the number a budget is held against. For the instance cache Font::cache_stats adds a little that is outside the budget, as its entry tells.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
Font
pub struct Font {
    /* private fields */
}

An open font: one face of a font file, read lazily, with the caches that make repeated calls cheap.

A Font is one face: a TrueType or OpenType font file, or one of the fonts inside a collection (a .ttc file). Opening one checks the table directory, the units per em and the glyph count. The rest of the font is read as calls need it.

Font::from_bytes opens a font from a slice and copies it. Font::from_vec keeps a Vec you hand over, and Font::from_static reads bytes that live as long as the program where they lie. Font::from_collection opens one face of a collection, and Font::face_count says how many it has. An open font borrows nothing from you: it holds its own copy of the bytes or the Vec itself, or reads bytes that are 'static.

Every method takes &self. Behind it the font keeps caches: of shaped runs, of what each location of a variable font has built, of outlines drawn ahead and of rasterized images. Cache names them, and Font::set_cache_budget sets how many bytes each may hold. A Font is not Clone: share one by reference, or in an Rc or Arc.

A variable font is one file that holds a whole range of designs, such as every weight from thin to black. Font::location turns axis values into a Location, and every call that depends on the instance takes one by reference. &Location::default() is the default instance, and is what you pass for a font that is not variable.

Metrics, advances and outlines come back in the font's own units. Font::units_per_em is how many make one em, so a value in pixels is value * px / f64::from(font.units_per_em()).

Threads. The threading feature decides whether a font may cross threads. Without it a Font is neither Send nor Sync and stays on the thread that opened it, and a catch_unwind over one needs AssertUnwindSafe. With it a Font is Send + Sync and unwind safe, so one font in an Arc serves every thread, caches and all. The results of shaping, layout and drawing, such as a ShapedRun or a Path, cross threads in both builds.

In a build with std, a thread keeps a little between calls: the locations it last read at and, under threading, what it last hinted with and its recent runs. That can keep a dropped font's bytes alive until the thread reads at locations of other fonts or hints with them, ends or calls release_thread.

use daegun::shape::ShapeOptions;
use daegun::{Font, Location, Tag};

let font = Font::from_bytes(&bytes("inter"))?;
// Inter Variable: 2048 units to the em, 2937 glyphs.
assert_eq!(font.units_per_em(), 2048);
assert_eq!(font.glyph_count(), 2937);

// The default instance, then the same text at a weight of 700.
let regular = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT);
let bold = font.location(&[(Tag::new(b"wght"), 700.0)]);
let heavy = font.shape("Wave", &bold, &ShapeOptions::DEFAULT);
// The bold letters are wider: 5572 units against 5339.
assert_eq!((regular.width(), heavy.width()), (5339.0, 5572.0));
  • Implements: Debug.
  • Auto traits: Unpin, and with the threading feature RefUnwindSafe, Send, Sync, UnwindSafe.
FontStyle
#[non_exhaustive]
pub enum FontStyle {
    Normal,
    Italic,
    Oblique,
}

Whether a font's glyphs stand upright or lean: normal, italic or oblique.

Font::style returns it, from the flags the font sets in its OS/2 and head tables. It is what a font matcher compares with the font-style a page asks for.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::{FontStyle, Location};

let css = match font.style(&Location::default()) {
    FontStyle::Italic => "italic",
    FontStyle::Oblique => "oblique",
    _ => "normal",
};
assert_eq!(css, "normal");
Normal
Upright: the font sets neither the italic nor the oblique flag.
Italic
Italic: the italic bit is set in the OS/2 table's fsSelection or in the head table's macStyle, and the oblique bit is not.
Oblique
Oblique, a slanted form of the upright design: the oblique bit is set in fsSelection. A font may set the italic bit beside it, and the answer is still oblique, the order CSS font matching reads the two in.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
LocalizedName
#[non_exhaustive]
pub struct LocalizedName {
    pub language: String,
    pub name: String,
}

A name from the name table in one language: the language tag and the string.

Font::localized_names returns one for each language a name is recorded in.

It is #[non_exhaustive], so you read its fields. LocalizedName::default() gives an empty one where a test needs it.

use daegun::{Font, LocalizedName, Location, NameId};

let font = Font::from_bytes(&bytes("cjk"))?;
let names: Vec<LocalizedName> = font.localized_names(NameId::FAMILY_NAME, &Location::default());

// Show the family in the user's language, with English to fall back on.
let pick = |language: &str| names.iter().find(|n| n.language == language).map(|n| n.name.as_str());
let shown = pick("ja").or_else(|| pick("en"));
assert_eq!(shown, Some("源ノ角ゴシック JP VF"));
language: String
The language as a BCP 47 tag, such as en, ja or zh-TW. It is und, for undetermined, where the record names no language daegun knows.
name: String
The name in that language, with NULs and white space around it trimmed off.
  • Implements: Clone, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
Location
pub struct Location {
    /* private fields */
}

A point in a variable font's design space: the axis values that pick one instance of it.

A variable font holds a range of designs, and a Location says which one a call should use: so much weight, so much width. Make one with Font::location from pairs of axis tag and value, and pass it by reference to every call that depends on the instance, such as shaping, metrics, outlines and names.

Location::default() is the default instance, the design the font shows when nothing is set. It works with any font, variable or not.

Making a location resolves it against the font once: the values are clamped to their axes and turned into the normalized coordinates the font's tables use. Calls then start from that resolved form, so make a location once and reuse it. Cloning one is cheap.

A location also remembers the values it was asked for. Hand it to another font and that font resolves those values against its own axes, so one location means the same request to every font.

Two locations are equal, and hash alike, when they were asked for the same values, in any order, whichever font made them. Equality is about the request, not where it lands. On Inter a weight of 2000 is clamped to 900 and still differs from a location asked for 900, and a location asked for the default weight of 400 differs from Location::default(). To ask whether two of one font's locations are the same place, compare what Location::coords returns.

Without the threading feature a location is neither Send nor Sync, like the font that made it. With the feature it is both.

use daegun::shape::ShapeOptions;
use daegun::{Location, Tag};

let regular = Location::default();
let bold = font.location(&[(Tag::new(b"wght"), 700.0)]);

// One location, handed to every call at that weight.
let run = font.shape("Wave", &bold, &ShapeOptions::DEFAULT);
let family = font.family_name(&bold);

// Equal when asked for the same values, so a location can key a map of your own.
assert_eq!(bold, font.location(&[(Tag::new(b"wght"), 700.0)]));
assert_ne!(bold, regular);
  • Implements: Clone, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Unpin, UnwindSafe, and with the threading feature Send, Sync.
NamedInstance
#[non_exhaustive]
pub struct NamedInstance {
    pub name: Option<String>,
    pub postscript_name: Option<String>,
    pub coords: Vec<(Tag, f64)>,
}

One of the instances a variable font names, such as Bold: a point in its design space with a name of its own.

Font::named_instances returns them. They are the styles the designer picked out of the font's range, and what a font menu lists. To use one, pass its coords to Font::location.

It is #[non_exhaustive], so you read its fields.

use daegun::shape::ShapeOptions;
use daegun::NamedInstance;

// A style menu: each instance by name, with the text set in it.
let instances: Vec<NamedInstance> = font.named_instances();
for instance in &instances {
    let location = font.location(&instance.coords);
    let run = font.shape("Wave", &location, &ShapeOptions::DEFAULT);
    let label = instance.name.as_deref().unwrap_or("Unnamed");
    // Draw the label beside the run.
}
// Inter's seventh is Bold, with the PostScript name InterVariable-Bold.
assert_eq!(instances[6].name.as_deref(), Some("Bold"));
assert_eq!(instances[6].postscript_name.as_deref(), Some("InterVariable-Bold"));
name: Option<String>
The instance's style name, such as Bold Condensed, from the name table. None where the table has no name under the ID the instance gives, or the name lies past the limit Font::names describes.
postscript_name: Option<String>
The instance's PostScript name, such as InterVariable-Bold. None where the font gives the instance none, the name table lacks it, or it lies past the limit Font::names describes.
coords: Vec<(Tag, f64)>
The instance's value on every axis, in the order of Font::axes, in the form Font::location takes.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
NameId
pub struct NameId(

A name ID: the number the name table files a string under.

A font's name table is a list of strings, each filed under a number. The numbers below 256 have meanings the OpenType specification fixes, and the 25 constants here are the ones it defines: NameId::FAMILY_NAME is 1, NameId::VERSION_STRING is 5, and so on.

IDs from 256 up are the font's own. Other tables point at them to name their axes, axis values and color palettes: an Axis carries the ID of its name in name_id.

It is a plain wrapper around the u16, so any ID can be written as NameId(256). Pass one to Font::name or Font::localized_names, or look it up in the map Font::names returns.

use daegun::{Location, NameId};

let location = Location::default();
// A name the specification defines, and one of the font's own.
assert_eq!(font.name(NameId::FAMILY_NAME, &location).as_deref(), Some("Inter Variable"));
assert_eq!(font.name(NameId(257), &location).as_deref(), Some("Weight"));

assert_eq!(NameId::FAMILY_NAME, NameId(1));
assert_eq!(NameId::from(4), NameId::FULL_NAME);
assert_eq!(u16::from(NameId::FULL_NAME), 4);
assert_eq!(NameId::POSTSCRIPT_NAME.to_string(), "6");
u16
The ID as the name table stores it.
impl Display
Writes the ID as a number, so NameId::FAMILY_NAME prints as 1.
impl From<u16>
The name ID with that number, the same as writing NameId(n).
impl From<NameId> for u16
The ID as a number, the same as reading the field 0.
  • Implements: Clone, Copy, Debug, Default, Display, Eq, From<NameId> for u16, From<u16>, Hash, Ord, PartialEq, PartialOrd.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Metrics

A font's metrics in font units, y up: line spacing, the OS/2 and post tables, STAT, tracking and the flags a PDF writer needs. The calls are on Font, and their types are in daegun::metrics.

metrics::DecorationLine
#[non_exhaustive]
pub struct DecorationLine {
    pub position: f64,
    pub thickness: f64,
}

A line drawn under or through text: where it sits from the baseline and how thick it is, in font units.

TypographicMetrics holds two: underline, from the post table, and strikeout, from OS/2. Both are the numbers as the font stores them.

OpenType defines the position of each as the top edge of the stroke. So the line covers from position down to position - thickness, and runs the width of the text, which ShapedRun::width gives.

It is #[non_exhaustive], so read its fields rather than building one by literal. DecorationLine::default() gives one of zeros where a test needs it.

use daegun::metrics::DecorationLine;
use daegun::shape::ShapeOptions;
use daegun::Location;

let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT);
let metrics = font.typographic_metrics(&Location::default());
if let Some(DecorationLine { position, thickness, .. }) = metrics.underline {
    // A rectangle under the run, in font units: x from 0 to run.width(), y from top down to bottom.
    let (top, bottom) = (position, position - thickness);
    // Inter: from 348 to 488 units below the baseline, 5339 units long.
    assert_eq!((top, bottom, run.width()), (-348.0, -488.0, 5339.0));
}
position: f64
The y of the top edge of the line, measured from the baseline. Negative below the baseline, where an underline goes, and positive above it, where a strikeout goes.
thickness: f64
How thick to draw the line.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
metrics::LineMetrics
#[non_exhaustive]
pub struct LineMetrics {
    pub ascent: f64,
    pub descent: f64,
    pub line_gap: f64,
}

A font's line spacing in font units: how far a line reaches above and below its baseline, and the gap the font asks for between lines.

Font::line_metrics returns the one to set text with, and Os2::typo_metrics holds the typographic trio of OS/2 in the same shape.

Y is up, so descent is a negative number for a font that reaches below the baseline. Subtract it from the ascent for the height of a line, or call LineMetrics::line_height, which adds the gap too. For pixels, multiply any of them by px / f64::from(font.units_per_em()).

It is #[non_exhaustive], so read its fields rather than building one by literal. LineMetrics::default() is all zeros, and a test can start from it and set the fields.

use daegun::metrics::LineMetrics;
use daegun::{Location, Orientation};

let line: LineMetrics = font.line_metrics(&Location::default(), Orientation::Horizontal);
let scale = 16.0 / f64::from(font.units_per_em());

// The baselines of three lines at 16 px, measured down from the top of the first line.
let first = line.ascent * scale;
let baselines: Vec<f64> = (0..3).map(|i| first + f64::from(i) * line.line_height() * scale).collect();
// Inter: 15.5 px down to the first baseline, then 19.359375 px from each to the next.
assert_eq!(baselines, [15.5, 34.859375, 54.21875]);

// One of your own, for a test.
let mut made = LineMetrics::default();
made.ascent = 800.0;
made.descent = -200.0;
assert_eq!(made.line_height(), 1000.0);
ascent: f64
How far the line reaches above the baseline.
descent: f64
How far the line reaches below the baseline, as a y coordinate: negative for a font that descends below it.
line_gap: f64
Extra room the font asks for between the bottom of one line and the top of the next. 0 where it asks for none.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
metrics::Os2
#[non_exhaustive]
pub struct Os2 {
    pub version: u16,
    pub weight_class: Option<u16>,
    pub width_class: Option<u16>,
    pub fs_type: Option<u16>,
    pub family_class: Option<u16>,
    pub selection: Option<u16>,
    pub win_metrics: Option<WinMetrics>,
    pub typo_metrics: Option<LineMetrics>,
}

What a font's OS/2 table says of its style and vertical metrics.

Font::os2 returns one. The fields are the numbers of the table, each None where the table stops before it, and the methods read the style bits of selection for you. The metrics are in font units.

Read at a location of a variable font, it describes the instance there: see Font::os2 for what changes.

It is #[non_exhaustive], so read its fields rather than building one by literal. Os2::default() gives an empty one where a test needs it.

use daegun::metrics::Os2;
use daegun::Location;

let os2: Os2 = font.os2(&Location::default()).expect("Inter has an OS/2 table");
// Weight 400 and the normal width.
assert_eq!((os2.weight_class, os2.width_class), (Some(400), Some(5)));

// May the font go into a document? Inter's 0 puts no limit on it.
let restricted = os2.fs_type.is_some_and(|bits| bits & 0x2 != 0);
assert!(!restricted);

// The two sets of vertical metrics. The Windows descent is a distance, so it is positive.
if let (Some(typo), Some(win)) = (os2.typo_metrics, os2.win_metrics) {
    assert_eq!((typo.ascent, typo.descent), (1984.0, -494.0));
    assert_eq!((win.ascent, win.descent), (1984.0, 494.0));
}
version: u16
The version of the table, which tells you what a font could hold: the x-height and cap height arrived with version 2. The oblique and USE_TYPO_METRICS bits of selection belong to version 4, but daegun reads them in any version, since fonts set them in older tables.
weight_class: Option<u16>
How heavy the face is, usWeightClass, from 1 to 1000 on the scale CSS uses for font-weight: 400 is regular and 700 is bold. At a location of a font with a wght axis it is the value of that axis there, rounded. None where the table stops before the field.
width_class: Option<u16>
How wide the face is, usWidthClass, from 1 for ultra-condensed to 9 for ultra-expanded, with 5 for normal. At a location of a font with a wdth axis it is the class nearest the value of that axis there. None where the table stops before the field.
fs_type: Option<u16>
What embedding the font's license allows, fsType. 0 means it may be installed and embedded freely. Otherwise test the bits: 0x2 restricted, 0x4 embedding for preview and print, 0x8 embedding for editing, 0x100 no subsetting, 0x200 bitmaps only. None where the table stops before the field.
family_class: Option<u16>
The font's class in the IBM classification that OpenType uses, sFamilyClass: the class in the high byte and the subclass in the low one, with 0 for none. Font::pdf_flags reads serif and script faces from it. None where the table is too short to hold it.
selection: Option<u16>
The style bits, fsSelection. Os2::is_italic, Os2::is_bold, Os2::is_regular, Os2::is_oblique and Os2::uses_typo_metrics each read one, and the rest are yours to test on the number. None where the table is too short to hold it, and then all five methods answer false.
win_metrics: Option<WinMetrics>
The Windows metrics, usWinAscent and usWinDescent, as a WinMetrics: how far above and below the baseline Windows lets the font draw. None where the table stops before them.
typo_metrics: Option<LineMetrics>
The typographic line spacing, sTypoAscender, sTypoDescender and sTypoLineGap, as a LineMetrics whose descent is negative. Font::line_metrics takes it ahead of hhea when Os2::uses_typo_metrics is true. None where the table stops before them.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
metrics::PdfFlags
pub struct PdfFlags(/* private */);

A set of the flags a PDF font descriptor carries, each bit where PDF puts it.

Font::pdf_flags returns the set for a font. Test it with PdfFlags::contains, and write PdfFlags::bits as the Flags entry of the descriptor.

The six constants are the flags daegun works out. Join sets with | and take what two share with &. PdfFlags::default() is the empty set, the same as PdfFlags::empty. There is no way to make a set from a raw integer: build one from the constants.

It is a Copy value the size of a u32, and it is Eq and Hash, so it can key a map.

use daegun::metrics::PdfFlags;
use daegun::Location;

let flags = font.pdf_flags(&Location::default());
// STIX Two Math: a serif face that maps characters beyond the standard Latin set.
assert_eq!(flags, PdfFlags::SERIF | PdfFlags::SYMBOLIC);

if flags.contains(PdfFlags::SERIF) {
    // Pick a serif face to stand in for it.
}

// The integer for the /Flags entry, and the same bits in base 2.
assert_eq!(flags.bits(), 6);
assert_eq!(format!("{flags:b}"), "110");
impl BitOr
a | b is the set of every flag that either holds.
impl BitOrAssign
a |= b adds the flags of b to a.
impl BitAnd
a & b is the set of flags that both hold, which is empty where they share none.
impl BitAndAssign
a &= b keeps in a only the flags that b holds too.
impl Binary
Writes the integer PdfFlags::bits returns in base 2, so {:b} gives 110 for a serif, symbolic font. {:#b} adds the 0b prefix, and a width pads as it does for a u32.
impl Octal
Writes the same integer in base 8 with {:o}, or with a 0o prefix with {:#o}.
impl LowerHex
Writes the same integer in base 16 with lowercase digits. The set of ITALIC, NONSYMBOLIC, SCRIPT and SERIF gives 6a with {:x} and 0x6a with {:#x}.
impl UpperHex
Writes the same integer in base 16 with uppercase digits. The set of ITALIC, NONSYMBOLIC, SCRIPT and SERIF gives 6A with {:X}.
  • Implements: Binary, BitAnd, BitAndAssign, BitOr, BitOrAssign, Clone, Copy, Debug, Default, Eq, Hash, LowerHex, Octal, PartialEq, UpperHex.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
metrics::ScriptMetrics
#[non_exhaustive]
pub struct ScriptMetrics {
    pub x_size: f64,
    pub y_size: f64,
    pub x_offset: f64,
    pub y_offset: f64,
}

The size and placement a font suggests for subscripts or superscripts, from its OS/2 table.

TypographicMetrics holds one for each, in font units. They are for a subscript or superscript made by shrinking and moving ordinary glyphs, where the font has no smaller glyphs of its own to offer.

The sizes are the em to set the smaller glyphs in. Divide y_size by Font::units_per_em for the font size to use, as a fraction of the size of the text around it.

The numbers are the ones the font stores, and OS/2 counts both vertical offsets as positive: a subscript moves down by its y_offset and a superscript moves up by its own. So for a subscript this one field runs against the y-up rule of the other metrics.

It is #[non_exhaustive], so read its fields rather than building one by literal. ScriptMetrics::default() gives one of zeros where a test needs it.

use daegun::metrics::ScriptMetrics;
use daegun::Location;

let metrics = font.typographic_metrics(&Location::default());
let upem = f64::from(font.units_per_em());
if let Some(ScriptMetrics { y_size, y_offset, .. }) = metrics.subscript {
    // Set a subscript at `scale` times the size of the text, with its baseline `drop` ems lower.
    let (scale, drop) = (y_size / upem, y_offset / upem);
    // Inter: 60% of the size, and 7.5% of an em down.
}
x_size: f64
The width of the em to set the smaller glyphs in. Over the units per em, it is their horizontal scale.
y_size: f64
The height of the em to set the smaller glyphs in. Over the units per em, it is their font size as a fraction of the text around them.
x_offset: f64
How far to move the glyphs sideways, positive to the right. Inter has 0. The italic of Irianis ADF moves a subscript 17 units left and a superscript 81 right, to follow its slant.
y_offset: f64
How far to move the glyphs off the baseline, as a positive number either way: down for a subscript, up for a superscript.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
metrics::Stat
#[non_exhaustive]
pub struct Stat {
    pub axes: Vec<StatAxis>,
    pub values: Vec<StatAxisValue>,
    pub elided_fallback_name: Option<String>,
}

A font's STAT table: its design axes and the names it gives to values on them, for putting style names together.

Font::stat returns one. The usual use is to build the name of a style from its parts. Take the values that describe the instance, sort them by the ordering of their axes, drop the ones marked elidable and join the names that are left. If nothing is left, the name is elided_fallback_name.

Read at a location other than the default, values already holds only the values that describe that instance, one for each axis it varies. At the default location it holds every value the font names, and picking the ones that apply is up to you.

Every name is a String of its own, so the result does not borrow from the font. It is #[non_exhaustive] and has no constructor: you get one from Font::stat and read its fields.

use daegun::metrics::{Stat, StatAxisValue};
use daegun::Tag;

let bold = font.location(&[(Tag::new(b"wght"), 700.0)]);
let stat: Stat = font.stat(&bold).expect("EB Garamond has a STAT table");

// The style name of this instance: the name of each value, in the order of the axes, without
// the ones marked elidable.
let mut parts: Vec<(u16, &str)> = Vec::new();
for value in &stat.values {
    let (axis, name, elidable) = match value {
        StatAxisValue::Single { axis_index, name, elidable, .. }
        | StatAxisValue::Range { axis_index, name, elidable, .. }
        | StatAxisValue::Linked { axis_index, name, elidable, .. } => (*axis_index, name, *elidable),
        _ => continue,
    };
    if let (Some(name), false) = (name, elidable) {
        parts.push((stat.axes[usize::from(axis)].ordering, name.as_str()));
    }
}
parts.sort();
let words: Vec<&str> = parts.iter().map(|&(_, name)| name).collect();
let style = match words.is_empty() {
    true => stat.elided_fallback_name.clone().unwrap_or_default(),
    false => words.join(" "),
};
// "Bold" from the weight axis. The "Roman" of the italic axis is elidable and drops out.
assert_eq!(style, "Bold");
axes: Vec<StatAxis>
The design axes the table describes, in the order it stores them. The axis_index of a value counts into this list.
values: Vec<StatAxisValue>
The named values, in the order the table stores them.
elided_fallback_name: Option<String>
The style name to use when every name that applies is elidable and nothing would be left, such as Regular. None where the font has no name for it, or where the table's names add up to more text than daegun hands out, which only a hostile font reaches, or, at the default location, where the table is version 1.0, which has no such field. At another location a version 1.0 table falls back on name ID 2, the subfamily.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
metrics::StatAxis
#[non_exhaustive]
pub struct StatAxis {
    pub tag: Tag,
    pub name: Option<String>,
    pub ordering: u16,
}

One design axis of a STAT table: its tag, its name and its place in a style name.

Stat::axes lists them. The table may describe an axis the font does not vary. Inter has no ital axis to move along, yet its table lists one and names the place this file has on it, Roman.

It is #[non_exhaustive] and has no constructor: read its fields.

use daegun::metrics::StatAxis;
use daegun::{Location, Tag};

let stat = font.stat(&Location::default()).expect("Inter has a STAT table");
let mut axes: Vec<&StatAxis> = stat.axes.iter().collect();
axes.sort_by_key(|axis| axis.ordering);

let names: Vec<&str> = axes.iter().filter_map(|axis| axis.name.as_deref()).collect();
// The order a style name is put together in: optical size, then weight, then italic.
assert_eq!(names, ["Optical Size", "Weight", "Italic"]);
// Inter varies the first two. The italic axis is described and no more.
assert_eq!(axes[2].tag, Tag::new(b"ital"));
assert!(font.axes().iter().all(|axis| axis.tag != Tag::new(b"ital")));
tag: Tag
The four-letter tag of the axis, such as wght: the same tag the axis has in fvar, where the font varies it.
name: Option<String>
The name of the axis for people, such as Weight, from the name table. None where the name table has no record under the axis's name ID, or where the table's names add up to more text than daegun hands out, which only a hostile font reaches.
ordering: u16
Where the part for this axis falls when a style name is put together from value names: lowest first. Sort by it, not by the order of the list.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
metrics::StatAxisValue
#[non_exhaustive]
pub enum StatAxisValue {
    Single {
        axis_index: u16,
        name: Option<String>,
        value: f64,
        elidable: bool,
        older_sibling: bool,
    },
    Range {
        axis_index: u16,
        name: Option<String>,
        nominal: f64,
        min: f64,
        max: f64,
        elidable: bool,
        older_sibling: bool,
    },
    Linked {
        axis_index: u16,
        name: Option<String>,
        value: f64,
        linked_value: f64,
        elidable: bool,
        older_sibling: bool,
    },
    Combo {
        name: Option<String>,
        values: Vec<(u16, f64)>,
        elidable: bool,
        older_sibling: bool,
    },
}

A value that a STAT table names on its axes, in one of the four shapes the table can record.

Stat::values lists them. Each ties a name, such as Bold, to a place in the design: one value on an axis, a range of an axis, a value linked to the style it pairs with, or a combination across several axes. All values are in user coordinates, the scale Font::axes reports, such as 700 for a weight.

A value that names an axis the table does not list is left out when the table is read, so every axis_index is good for Stat::axes.

It is #[non_exhaustive], so a match on it needs a _ arm: a later release may add a shape.

use daegun::metrics::StatAxisValue;
use daegun::Location;

let stat = font.stat(&Location::default()).expect("Source Serif has a STAT table");
let mut lines = Vec::new();
for value in &stat.values {
    let text = |name: &Option<String>| name.clone().unwrap_or_default();
    lines.push(match value {
        StatAxisValue::Single { name, value, .. } => format!("{} at {value}", text(name)),
        StatAxisValue::Range { name, min, max, .. } => format!("{} from {min} to {max}", text(name)),
        StatAxisValue::Linked { name, value, linked_value, .. } => {
            format!("{} at {value}, linked to {linked_value}", text(name))
        }
        StatAxisValue::Combo { name, values, .. } => format!("{} on {} axes", text(name), values.len()),
        // A later release may add a shape.
        _ => continue,
    });
}
// Source Serif names ranges of weight, and links its upright style to the italic.
assert_eq!(lines[5], "Bold from 650 to 750");
assert_eq!(lines[13], "Regular at 0, linked to 1");
Single { axis_index: u16, name: Option<String>, value: f64, elidable: bool, older_sibling: bool, }
A name for one value on one axis, such as Bold at a weight of 700.
axis_index: u16
The axis the value is on, as an index into Stat::axes.
name: Option<String>
The name of the value, from the name table. None where the name table has no record for it, or where the table's names add up to more text than daegun hands out, which only a hostile font reaches.
value: f64
The value on the axis that the name is for.
elidable: bool
True when the name is to be left out as style names are put together, the way Regular drops out of Regular Italic.
older_sibling: bool
True when the value is there to describe other fonts of the family, ones made too early to describe themselves, and not this font.
Range { axis_index: u16, name: Option<String>, nominal: f64, min: f64, max: f64, elidable: bool, older_sibling: bool, }
A name for a range of values on one axis, such as Bold for every weight from 650 to 750.
axis_index: u16
The axis the range is on, as an index into Stat::axes.
name: Option<String>
The name of the range, from the name table. None where the name table has no record for it, or where the table's names add up to more text than daegun hands out, which only a hostile font reaches.
nominal: f64
The value the name stands for: the one to show, or to move to, when the name is picked.
min: f64
The low end of the range.
max: f64
The high end of the range.
elidable: bool
True when the name of the range is to be left out as style names are put together.
older_sibling: bool
True when the range describes other fonts of the family and not this one.
Linked { axis_index: u16, name: Option<String>, value: f64, linked_value: f64, elidable: bool, older_sibling: bool, }
A name for one value on one axis, with the value of the style it pairs with: Regular at 400 linked to 700 says that bold is its partner.
axis_index: u16
The axis both values are on, as an index into Stat::axes.
name: Option<String>
The name of the value, from the name table. None where the name table has no record for it, or where the table's names add up to more text than daegun hands out, which only a hostile font reaches.
value: f64
The value on the axis that the name is for.
linked_value: f64
The value its partner style has on the same axis: where a bold or italic button goes from here.
elidable: bool
True when the name of the linked value is to be left out as style names are put together.
older_sibling: bool
True when the linked value describes other fonts of the family and not this one.
Combo { name: Option<String>, values: Vec<(u16, f64)>, elidable: bool, older_sibling: bool, }
One name for a combination of values on several axes, for a style no single axis can name.
name: Option<String>
The name of the combination, from the name table. None where the name table has no record for it, or where the table's names add up to more text than daegun hands out, which only a hostile font reaches.
values: Vec<(u16, f64)>
The combination: pairs of an index into Stat::axes and the value on that axis.
elidable: bool
True when the name of the combination is to be left out as style names are put together.
older_sibling: bool
True when the combination describes other fonts of the family and not this one.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
metrics::TypographicMetrics
#[non_exhaustive]
pub struct TypographicMetrics {
    pub x_height: Option<f64>,
    pub underline: Option<DecorationLine>,
    pub strikeout: Option<DecorationLine>,
    pub subscript: Option<ScriptMetrics>,
    pub superscript: Option<ScriptMetrics>,
}

A font's measures for setting text: the x-height, where to draw an underline and a strikeout, and how to set subscripts and superscripts.

Font::typographic_metrics returns one, in font units. Each field is an Option, None where the font has no table or no field to read it from, so have a fallback of your own ready for each.

It is #[non_exhaustive], so read its fields rather than building one by literal. TypographicMetrics::default() gives one with every field None where a test needs it.

use daegun::metrics::TypographicMetrics;
use daegun::Location;

let metrics: TypographicMetrics = font.typographic_metrics(&Location::default());

// Each measure may be missing, so name what to use in its place.
let x_height = metrics.x_height.unwrap_or(font.cap_height(&Location::default()) * 0.7);
let strike_y = metrics.strikeout.map_or(x_height / 2.0, |line| line.position);
// Inter has both: an x-height of 1118, and a strikeout whose top edge is 671 above the baseline.
assert_eq!((x_height, strike_y), (1118.0, 671.0));
x_height: Option<f64>
The height of the lowercase letters that have no ascender, such as x, from the sxHeight field of OS/2. None without an OS/2 table, or with one older than version 2 or cut short before the cap height that follows the field.
underline: Option<DecorationLine>
Where to draw an underline and how thick, from the post table. None without a post table, or with one cut short of the two fields.
strikeout: Option<DecorationLine>
Where to draw a line through the text and how thick, from OS/2. None without an OS/2 table, or with one cut short of the fields.
subscript: Option<ScriptMetrics>
The size and placement the font suggests for subscripts, from OS/2. None without an OS/2 table, or with one cut short of the fields.
superscript: Option<ScriptMetrics>
The size and placement the font suggests for superscripts, from OS/2. None without an OS/2 table, or with one cut short of the fields.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
metrics::WinMetrics
#[non_exhaustive]
pub struct WinMetrics {
    pub ascent: f64,
    pub descent: f64,
}

The Windows metrics of OS/2: how far above and below the baseline Windows lets the font draw before it clips.

Os2::win_metrics holds one, in font units. Both numbers are distances from the baseline, so descent is positive, where LineMetrics::descent is negative. Their sum is the height of the band Windows leaves the font to draw in.

Font::line_metrics falls back on them, with the descent turned negative, only when neither hhea nor the typographic metrics state a height.

It is #[non_exhaustive], so read its fields rather than building one by literal. WinMetrics::default() gives one of zeros where a test needs it.

use daegun::metrics::WinMetrics;
use daegun::Location;

let os2 = font.os2(&Location::default()).expect("EB Garamond has an OS/2 table");
if let Some(WinMetrics { ascent, descent, .. }) = os2.win_metrics {
    // Both count away from the baseline: 1047 up and 390 down, a band 1437 units tall.
    assert_eq!((ascent, descent, ascent + descent), (1047.0, 390.0, 1437.0));
}
ascent: f64
How far above the baseline the font may draw, usWinAscent.
descent: f64
How far below the baseline the font may draw, usWinDescent, as a positive distance.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Glyphs

From characters to glyphs, and what each glyph measures: its id for a character, its advance, its box, its vertical origin, its ligature carets, its class and its name. All on Font.

GlyphClass
pub enum GlyphClass {
    Base,
    Ligature,
    Mark,
    Component,
}

What kind of glyph a font says one is: a base, a ligature, a mark or a component.

The classes come from the font's GDEF table, where its designer sorts glyphs by the part they play in text. Font::glyph_class reads the class of one glyph. It answers in an Option, since a font need not have the table and the table need not class every glyph.

These four are the ones OpenType defines, and the set will not grow, so a match on it needs no _ arm.

use daegun::GlyphClass;

let class_of = |c: char| font.glyph_id(c).and_then(|glyph| font.glyph_class(glyph));
assert_eq!(class_of('A'), Some(GlyphClass::Base));
// U+0301 is the combining acute accent.
assert_eq!(class_of('\u{301}'), Some(GlyphClass::Mark));
// Inter gives its space no class.
assert_eq!(class_of(' '), None);

match class_of('A') {
    Some(GlyphClass::Mark) => { /* drawn onto the glyph before it */ }
    Some(GlyphClass::Base | GlyphClass::Ligature | GlyphClass::Component) | None => {}
}
Base
A base glyph: a letter or symbol that stands by itself, and that marks attach to.
Ligature
A ligature: one glyph that stands for several characters, such as fi.
Mark
A mark: an accent or vowel sign that attaches to another glyph.
Component
A component: one part of a glyph that is built from several.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Shaping

Text to glyphs placed in font units, one run or the runs of mixed-direction text, and the carets that hit testing reads off them. The calls are on Font, and their types are in daegun::shape.

shape::BidiRun
#[non_exhaustive]
pub struct BidiRun {
    pub run: Arc<ShapedRun>,
    pub level: u8,
    pub bytes: core::range::Range<usize>,
}

One run of a line of mixed-direction text, as Font::shape_bidi returns it: the shaped glyphs, the bidi level and the bytes of text it covers.

Runs come in visual order, left to right as they are drawn, so you set them one after another by adding each run's width to a pen. The glyphs inside a run are in drawing order too, whichever way it reads.

It is #[non_exhaustive], so read its fields rather than building one by literal. BidiRun::default() gives an empty one where a test needs it.

use daegun::shape::{BidiRun, ShapeOptions};
use daegun::unicode::BaseDirection;
use daegun::Location;

let text = "Read مرحبا aloud";
let runs: Vec<BidiRun> =
    font.shape_bidi(text, &Location::default(), BaseDirection::Auto, &ShapeOptions::DEFAULT);

// The second run from the left is the Arabic word: level 1, bytes 5..15.
let arabic = &runs[1];
assert_eq!(arabic.level, 1);
assert_eq!(&text[arabic.bytes], "مرحبا");
// Its first glyph on the left is the last letter of the word, at byte 8 of the run's own text.
assert_eq!(arabic.run.clusters[0], 8);
run: Arc<ShapedRun>
The shaped run. Its clusters count bytes from the start of this run's own text, so add bytes.start to place one in the whole string.
level: u8
The bidi embedding level. An odd level reads right to left, an even one left to right.
bytes: core::range::Range<usize>
The byte range of the text this run covers, so &text[bidi.bytes] is the text it shows.
  • Implements: Clone, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
shape::ClusterLevel
#[non_exhaustive]
pub enum ClusterLevel {
    MonotoneGraphemes,
    MonotoneCharacters,
    Characters,
    Graphemes,
}

How a shaped run groups characters into clusters: by whole grapheme or by single character, and kept in text order or left as shaping produced them.

A cluster is the piece of text a glyph belongs to. ShapedRun::clusters gives it for each glyph, as the byte offset where the piece starts. The level decides how fine those pieces are and whether they may go backward along the run.

Hit testing and selection want the default, MonotoneGraphemes: every glyph of one user-perceived character shares a cluster, and clusters never go backward. Set another with ShapeOptions::with_cluster_level, which also means the run is shaped without the shape cache.

use daegun::shape::{ClusterLevel, ShapeOptions};
use daegun::Location;

// "कि" is the letter क followed by the vowel sign ि, which is drawn before the letter.
let run = font.shape("कि", &Location::default(), &ShapeOptions::DEFAULT);
// By default the two glyphs share one cluster.
assert_eq!(run.clusters, [0, 0]);

let options = ShapeOptions::DEFAULT.with_cluster_level(ClusterLevel::Characters);
let run = font.shape("कि", &Location::default(), &options);
// Now each keeps its own: the vowel sign's glyph comes first, from byte 3.
assert_eq!(run.clusters, [3, 0]);
MonotoneGraphemes
A grapheme is one cluster, and clusters stay in text order: glyphs that shaping reorders end up sharing a cluster so the order holds. The default.
MonotoneCharacters
A character is one cluster, and clusters stay in text order, so characters that shaping reorders still end up sharing one.
Characters
A character is one cluster, in whatever order shaping leaves the glyphs. Clusters may go backward.
Graphemes
A grapheme is one cluster, in whatever order shaping leaves the glyphs.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
shape::Direction
pub enum Direction {
    LeftToRight = 0,
    RightToLeft = 1,
    TopToBottom = 2,
    BottomToTop = 3,
}

The direction a run is shaped and set in.

Leave ShapeOptions::direction unset and shaping takes left to right or right to left from the text's script. Set one to force it, or to set text vertically with TopToBottom.

In a vertical run each advance in ShapedRun::advances runs down the line, and each offset moves the glyph from its horizontal origin to its place under the pen.

A run shaped against the direction of its script is turned one grapheme at a time, so each character still reads the right way.

use daegun::shape::{Direction, ShapeOptions};
use daegun::Location;

let down = ShapeOptions::DEFAULT.with_direction(Direction::TopToBottom);
let run = font.shape("Wave", &Location::default(), &down);
// Each advance now runs down the line, so run.width() is the height of the column.

let parsed: Direction = "rtl".parse()?;
assert_eq!(parsed, Direction::RightToLeft);
assert_eq!(Direction::TopToBottom.to_string(), "ttb");
LeftToRight = 0
Left to right, as Latin text runs. The default.
RightToLeft = 1
Right to left, as Arabic and Hebrew text run.
TopToBottom = 2
Top to bottom, for vertical text.
BottomToTop = 3
Bottom to top. A run shaped this way never comes from the shape cache.
impl Display
Writes ltr, rtl, ttb or btt, the names shaping tools give a direction.
impl FromStr
Reads a direction by its first letter in either case, spaces around it skipped, so rtl, RTL and right all give RightToLeft. Empty text, or text whose first character past any spaces is none of l, r, t or b, is an error of kind ErrorKind::InvalidArgument.
  • Implements: Clone, Copy, Debug, Default, Display, Eq, FromStr, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
shape::Feature
pub struct Feature {
    pub tag: Tag,
    pub value: u32,
    pub bytes: core::range::Range<usize>,
}

One OpenType feature to turn on, turn off or set to a value, over all of the text or a byte range of it.

Pass a slice of them with ShapeOptions::with_features. Feature::new covers the whole text. To cover part of it, set bytes to a range of byte offsets, the same offsets ShapedRun::clusters uses.

Some common tags: kern for kerning, liga for standard ligatures, smcp for small caps, tnum for tabular figures, ss01 to ss20 for stylistic sets. A run shaped with features is shaped afresh each call, without the shape cache.

A feature that is on or off over the whole text costs nothing. One the font has, over a byte range or with a value above 1, takes bits from a budget of 27 that the shaper's own features draw on too: 1 bit for on or off, and up to 8 for a higher value. Those that no longer fit, counted in tag order, are left out without an error, and wholly: a kern off over a few bytes that finds no room leaves the whole text unkerned. So keep ranged and valued features to a handful.

use daegun::shape::{Feature, ShapeOptions};
use daegun::{Location, Tag};

// Kerning off, over the whole text.
let features = [Feature::new(Tag::new(b"kern"), 0)];
let options = ShapeOptions::DEFAULT.with_features(&features);
let run = font.shape("Wave", &Location::default(), &options);
// Inter sets "Wave" 5513 units wide without kerning, and 5339 with it.

// The same feature from text, this time over bytes 3 to 5 only.
let part: Feature = "kern[3:5]=0".parse()?;
assert_eq!(part, Feature { bytes: (3..5).into(), ..Feature::new(Tag::new(b"kern"), 0) });
assert_eq!(part.to_string(), "-kern[3:5]");
tag: Tag
The feature's four-letter tag, such as liga.
value: u32
0 turns the feature off and 1 turns it on. For a feature that picks among alternates, such as aalt, a higher value picks which one, up to 255: only the low 8 bits count, so 256 turns it off.
bytes: core::range::Range<usize>
The byte range of the text the feature applies to. An end past the text's length runs to its end, which is how Feature::new covers everything.
impl Display
Writes the feature the way parse reads it back: - in front when the value is 0, = and the value when it is above 1, and the byte range in brackets unless it covers the whole text: [3:5], with a start of 0 or an open end left out ([:5], [3:]) and a single byte as [3]. A tag that holds anything but letters and digits, such as one padded with a space, is written in quotes, single ones if it holds a double quote. So kern, -liga, aalt[3:5]=2, "lao ".
impl FromStr
Reads a feature as shaping tools and CSS write one: kern, -liga (off), +smcp (on), aalt=2 or aalt 2, on and off as values, the tag in quotes or not, and [start:end] for a byte range, where either end may be left out, a ; may stand for the :, and [i] means the one byte at i. Anything else is an error of kind ErrorKind::InvalidArgument.
  • Implements: Clone, Copy, Debug, Display, Eq, FromStr, Hash, Ord, PartialEq, PartialOrd.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
shape::Ignorables
#[non_exhaustive]
pub enum Ignorables {
    Hide,
    Remove,
    Preserve,
}

What shaping does with default ignorables: invisible characters such as the zero width joiner and variation selectors.

Set it with ShapeOptions::with_ignorables.

use daegun::shape::{Ignorables, ShapeOptions};
use daegun::Location;

// An "a", a zero width joiner and a "b".
let text = "a\u{200D}b";
let hidden = font.shape(text, &Location::default(), &ShapeOptions::DEFAULT);
// Three glyphs, the middle one invisible and 0 wide.
assert_eq!(hidden.glyphs.len(), 3);
assert_eq!(hidden.advances[1], 0.0);

let options = ShapeOptions::DEFAULT.with_ignorables(Ignorables::Remove);
let removed = font.shape(text, &Location::default(), &options);
// Two glyphs: the joiner is gone.
assert_eq!(removed.glyphs.len(), 2);
Hide
Kept in the run as an invisible glyph with an advance of 0, so the clusters still account for them. The glyph is the font's space unless ShapeOptions::invisible_glyph names another. In a font with no space glyph, and none named, they are left out as under Remove. The default.
Remove
Left out of the run altogether.
Preserve
Shaped like any other character, with whatever glyph the font maps them to and that glyph's advance. One the font has no glyph for becomes ShapeOptions::not_found_glyph.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
shape::Offset
pub struct Offset {
    pub x: f64,
    pub y: f64,
}

How far a glyph or a run sits from where it would otherwise be, in font units.

Each glyph of a ShapedRun has one in offsets, with y up. Most are zero. A mark's offset moves it onto its base, and in vertical text the offset puts each glyph under the pen. Draw glyph i at the pen plus its offset, then move the pen by its advance.

A layout uses the same type in PositionedRun::offset for where each run starts along its line: in x across a horizontal line, and in y down a vertical one. There, and only there, a larger y is lower.

use daegun::shape::{Offset, ShapeOptions};
use daegun::Location;

// An Arabic letter with a vowel mark above it.
let run = font.shape("بَ", &Location::default(), &ShapeOptions::DEFAULT);
for (glyph, offset) in run.glyphs.iter().zip(&run.offsets) {
    let Offset { x, y } = *offset;
    // The run is right to left, so the mark comes first: its offset moves it into place over the
    // letter, whose own offset is zero.
}

let pair: (f64, f64) = Offset { x: 3.0, y: 4.0 }.into();
assert_eq!(pair, (3.0, 4.0));
x: f64
Across. A positive value moves right.
y: f64
Up for a glyph: a positive value moves it up. A run's offset in a vertical line of a layout counts down the line instead.
impl From<(f64, f64)>
An offset from an (x, y) pair.
impl From<Offset> for (f64, f64)
The offset as an (x, y) pair.
  • Implements: Clone, Copy, Debug, Default, From<(f64, f64)>, From<Offset> for (f64, f64), PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
shape::ShapedRun
#[non_exhaustive]
pub struct ShapedRun {
    pub glyphs: Vec<GlyphId>,
    pub advances: Vec<f64>,
    pub offsets: Vec<Offset>,
    pub unsafe_to_break: Vec<bool>,
    pub unsafe_to_concat: Vec<bool>,
    pub safe_to_insert_tatweel: Vec<bool>,
    pub clusters: Vec<u32>,
    pub complete: bool,
    pub has_broken_syllable: bool,
    pub shaper: Shaper,
}

The result of shaping: the glyphs of a run in the order they are drawn, each with its advance, its offset and the cluster of text it came from.

The lists glyphs, advances, offsets, clusters and unsafe_to_break each hold one entry per glyph, at the same index. Everything is in font units, so a position in pixels is value * px / f64::from(font.units_per_em()).

The number of glyphs is not the number of characters. A ligature makes one glyph from several characters, and some scripts make several glyphs from one. clusters maps each glyph back to the text.

Font::shape returns the run inside an Arc, which is how the shape cache hands one run to every caller without copying it. Font::shape_into fills a run you own instead, and ShapedRun::default() is an empty one to start from.

use daegun::shape::{ShapeOptions, ShapedRun};
use daegun::Location;
use std::sync::Arc;

let run: Arc<ShapedRun> = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT);
let scale = 16.0 / f64::from(font.units_per_em());

let mut pen = 0.0;
for i in 0..run.glyphs.len() {
    let x = (pen + run.offsets[i].x) * scale;
    let y = run.offsets[i].y * scale;
    // Draw run.glyphs[i] at (x, y) pixels from the start of the baseline, at 16 px.
    pen += run.advances[i];
}
// Four letters gave four glyphs, and glyph i came from the character at byte run.clusters[i].
assert_eq!(run.clusters, [0, 1, 2, 3]);
glyphs: Vec<GlyphId>
The glyph ids in visual order: from the left as drawn, for right-to-left text too.
advances: Vec<f64>
How far the pen moves after each glyph: across the line, or down it in vertical text.
offsets: Vec<Offset>
Each glyph's Offset from the pen.
unsafe_to_break: Vec<bool>
True for a glyph when breaking the text where its cluster starts and shaping the two sides apart could give different glyphs, as before the second letter of a kerned pair. A line breaker that breaks there shapes both sides again. A break inside a cluster, such as between the letters of a ligature, has no glyph to carry a flag and always needs both sides shaped again.
unsafe_to_concat: Vec<bool>
True for a glyph when shaping the text on either side of it separately and joining the two runs could differ from shaping it whole. Empty unless ShapeOptions::report_unsafe_to_concat asked for it.
safe_to_insert_tatweel: Vec<bool>
True for a glyph that a tatweel, the stroke that stretches Arabic words, may go before in the text. In a right-to-left run that is on the glyph's right as drawn. Empty unless ShapeOptions::report_tatweel_positions asked for it.
clusters: Vec<u32>
For each glyph, the byte offset in the text where its cluster starts. Glyphs of one cluster share a value. With the default ClusterLevel the values rise along a left-to-right run and fall along a right-to-left one.
complete: bool
False if shaping stopped short because the font pushed it past daegun's limits, as a hostile font can. The run then holds the glyphs as they stood when it stopped. True for any ordinary font, and false in a run from ShapedRun::default() that nothing has been shaped into.
has_broken_syllable: bool
True if the run held a malformed syllable, such as a vowel sign with no letter before it. A dotted circle may then stand in for the missing base. Only the models that shape by syllable look for one, Shaper::Indic, Shaper::Khmer, Shaper::Myanmar and Shaper::Universal, so text left to the general model, as Devanagari is in a Latin font, reports false.
shaper: Shaper
The shaping model the run went through, a Shaper.
  • Implements: Clone, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
shape::ShapeOptions
#[non_exhaustive]
pub struct ShapeOptions<'a> {
    pub direction: Option<Direction>,
    pub script: Option<Tag>,
    pub language: Option<&'a str>,
    pub features: &'a [Feature],
    pub cluster_level: ClusterLevel,
    pub before: &'a str,
    pub after: &'a str,
    pub beginning_of_text: bool,
    pub point_size: Option<f64>,
    pub report_unsafe_to_concat: bool,
    pub report_tatweel_positions: bool,
    pub ignorables: Ignorables,
    pub suppress_dotted_circle: bool,
    pub invisible_glyph: Option<GlyphId>,
    pub seed_script: Option<Script>,
    pub not_found_glyph: GlyphId,
    pub not_found_variation_selector_glyph: Option<GlyphId>,
}

Everything shaping can be told: direction, script, language, features, the text around the run and what to draw for characters the font can't.

Start from ShapeOptions::DEFAULT and change what you need with the with_ methods, each of which returns the changed options. The defaults shape text the way it reads: direction and script taken from the text, the font's default features, no language.

The lifetime is that of the strings and the feature slice the options borrow.

The shape cache. Font::shape keeps runs and as a rule gives the same Arc back for the same request. It keeps a request that sets nothing beyond a direction other than bottom to top, the text around the run, a language and a seed script. Any other option means the run is shaped afresh on every call, as is a run too long for the cache to keep: Font::shape says how long that is.

use daegun::shape::{Direction, Feature, ShapeOptions};
use daegun::{Location, Tag};

// Turkish text with small caps, set right to left.
let features = [Feature::new(Tag::new(b"smcp"), 1)];
let options = ShapeOptions::DEFAULT
    .with_language("tr")
    .with_features(&features)
    .with_direction(Direction::RightToLeft);

let run = font.shape("fit", &Location::default(), &options);
// Forced right to left, the glyphs come back in visual order: t, i, f.
assert_eq!(run.clusters, [2, 1, 0]);
// EB Garamond draws the t and the f as small caps, and the i as the dotted form it keeps for Turkish.
direction: Option<Direction>
The direction to shape in. None takes left to right or right to left from the text's script.
script: Option<Tag>
An OpenType script tag, such as latn or arab, whose lookups to use in place of those the text's own script selects. A tag the font lacks falls back to the font's default script, DFLT, or to latn where it has none, and with it some scripts fall back to the general shaping model: ShapeOptions::with_script says which. None goes by the text.
language: Option<&'a str>
The language of the text as a BCP 47 tag, such as tr or sr-Latn, so the font can apply the forms it keeps for that language. None uses its default forms.
features: &'a [Feature]
Features to turn on, off or set, each over its byte range. Empty leaves the font's defaults.
cluster_level: ClusterLevel
How clusters are formed. ClusterLevel::MonotoneGraphemes by default.
before: &'a str
The text just before the run. Shaping reads the 5 characters nearest the run, and reads them for joining only: an Arabic letter at the edge takes the form its neighbor calls for. Kerning, ligatures and the font's other contextual lookups do not reach across the edge.
after: &'a str
The text just after the run, read the same way.
beginning_of_text: bool
True when nothing comes before the run. A combining mark that opens the text then gets a dotted circle to sit on, if the font has one and before is empty.
point_size: Option<f64>
The point size that tracking from the font's trak table is read at. None, or a size that isn't finite and above zero, reads it at metrics::DEFAULT_POINT_SIZE.
report_unsafe_to_concat: bool
Whether to fill ShapedRun::unsafe_to_concat. Off by default.
report_tatweel_positions: bool
Whether to fill ShapedRun::safe_to_insert_tatweel. Off by default.
ignorables: Ignorables
What to do with default ignorables. Ignorables::Hide by default.
suppress_dotted_circle: bool
True leaves out the dotted circle daegun would otherwise add for a broken syllable, a Hangul tone mark with no syllable, a mark that opens the text, or a vowel written as a sequence Unicode forbids. ShapeOptions::with_suppress_dotted_circle says when each goes in.
invisible_glyph: Option<GlyphId>
The glyph a hidden ignorable is drawn with. None uses the font's space, and so does glyph 0.
seed_script: Option<Script>
The script to shape the run as, in place of scanning the text for one. The run takes the shaping model daegun picks for that script and, where direction is None, its direction too. For text with no script of its own, such as the punctuation of an Arabic sentence.
not_found_glyph: GlyphId
The glyph that stands in for a character the font has no glyph for and no other way to draw, as Font::shape explains. GlyphId::NOTDEF, glyph 0, by default.
not_found_variation_selector_glyph: Option<GlyphId>
The glyph for a variation selector the font can't apply. None treats such a selector as a default ignorable.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
shape::Shaper
#[non_exhaustive]
pub enum Shaper {
    Default,
    Dumber,
    Arabic,
    Hangul,
    Hebrew,
    Indic,
    Khmer,
    Myanmar,
    MyanmarZawgyi,
    Thai,
    Universal,
}

The shaping model a run went through.

daegun picks the model from the text's script, the direction and the font, and reports it in ShapedRun::shaper. It is there to read, for a log or a test. You don't choose one directly. ShapeOptions::with_seed_script names the script, and the script tag given to ShapeOptions::with_script can change the model as well.

It is #[non_exhaustive], so a match on it needs a _ arm: a later release may add a model.

use daegun::shape::{ShapeOptions, Shaper};
use daegun::Location;

let run = font.shape("مرحبا", &Location::default(), &ShapeOptions::DEFAULT);
assert_eq!(run.shaper, Shaper::Arabic);

match run.shaper {
    Shaper::Arabic => { /* joined letters */ }
    Shaper::Default => { /* plain text */ }
    _ => {}
}
Default
The general model, for a script that needs none of its own, such as Latin, Greek or Cyrillic.
Dumber
Stands in for a script's own model (Arabic's, an Indic one, Thai's and so on) where the font's morx table shapes the text, as in Apple's fonts: daegun applies no features, masks or reordering of its own and leaves the work to the font. Text of a script with no model of its own reports Default in such a font too.
Arabic
Joining, for Arabic and Syriac.
Hangul
Hangul's syllables.
Hebrew
Hebrew's marks.
Indic
The syllables of the Indic scripts, Devanagari and its kin.
Khmer
Khmer's syllables.
Myanmar
Myanmar's syllables.
MyanmarZawgyi
Myanmar text in the older Zawgyi encoding. You ask for it by naming the script tag Qaag with ShapeOptions::with_script. Its syllables stay in the order given: nothing is reordered but a run of combining marks, which goes in Unicode's canonical order as in any text.
Thai
The marks of Thai and Lao.
Universal
The Universal Shaping Engine, for the many complex scripts it covers, such as Tibetan, Sinhala and Javanese, and for an Indic script whose lookups the font files under a version 3 tag such as dev3.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Unicode

Text analysis that needs no font: bidi, grapheme and word boundaries, line breaking, scripts and character properties. Free functions and types in daegun::unicode. Every position is a byte offset where a character starts.

unicode::BaseDirection
pub enum BaseDirection {
    Auto,
    LeftToRight,
    RightToLeft,
}

The direction a paragraph starts out with: taken from its text, or set left to right or right to left.

The Unicode bidirectional algorithm orders a paragraph around a base direction. It decides which side the paragraph starts from, and where spaces, punctuation and runs of the other direction fall within it. The same text can come out in a different order under each base direction.

Pass one to BidiParagraph::new, to Font::shape_bidi, or to a layout with LayoutOptions::with_base_direction. Auto is the default, and the right choice unless you know the direction from elsewhere, such as the language of the page.

use daegun::unicode::{BaseDirection, BidiParagraph};

let text = "שלום abc";
// Auto takes the direction from the first strong character, here a Hebrew letter: right to left.
let auto = BidiParagraph::new(text, BaseDirection::Auto);
assert_eq!(auto.base_level, 1);
// So the Latin word, last in the text, is the first run from the left.
assert_eq!(&text[auto.visual_runs(text, ..)[0].bytes], "abc");

// Set left to right, the same text starts with the Hebrew word.
let forced = BidiParagraph::new(text, BaseDirection::LeftToRight);
assert_eq!(forced.base_level, 0);
assert_eq!(&text[forced.visual_runs(text, ..)[0].bytes], "שלום");
Auto
The direction of the paragraph's first strong character: a letter that reads one way, as a Latin, Hebrew or Arabic letter does. Letters inside a directional isolate, from U+2066, U+2067 or U+2068 to the U+2069 that closes it, are passed over. A paragraph with none, such as one of only digits and punctuation, is left to right. The default.
LeftToRight
Left to right, whatever the text holds. A Hebrew or Arabic word in it still reads right to left, as a run inside the line.
RightToLeft
Right to left, whatever the text holds. Latin text in it still reads left to right, as a run at level 2.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::BidiParagraph
#[non_exhaustive]
pub struct BidiParagraph {
    pub base_level: u8,
    pub levels: alloc::vec::Vec<u8>,
    pub visual_order: alloc::vec::Vec<usize>,
    pub paragraphs: alloc::vec::Vec<ParagraphRun>,
}

Text resolved by the Unicode bidirectional algorithm: a level for every byte, the paragraphs, and the order the characters are drawn in.

Text that mixes directions, such as Arabic inside English, is stored in the order it is read and drawn in a different one. The Unicode bidirectional algorithm (UAX #9) works out the drawn order by giving every character a level. An even level reads left to right and an odd level reads right to left. Level 0 is plain left-to-right text and level 1 is right-to-left text. Level 2 is left-to-right text inside right-to-left text, such as a number or a Latin word in an Arabic sentence.

The text is cut into paragraphs at each paragraph separator: a newline, a carriage return (with a newline right after it, the pair counts as one), U+0085, U+2029, or one of U+001C to U+001E. Each paragraph has a direction of its own and is ordered on its own, and its separator belongs to it. U+2028, the line separator, ends a line without ending the paragraph.

Make one with BidiParagraph::new, which needs no font. Then, for each line you set, BidiParagraph::visual_runs gives the visual runs of that line: stretches of one level, in the order they are drawn from the left. Every position is a UTF-8 byte offset where a character starts, so it slices the text directly.

Font::shape_bidi and Font::layout do this work themselves. BidiParagraph is for when you break lines or order runs yourself. It is #[non_exhaustive], so read its fields rather than building one by literal.

use daegun::unicode::{BaseDirection, BidiParagraph};

let text = "Read مرحبا aloud";
let para = BidiParagraph::new(text, BaseDirection::Auto);

// The first strong character is a Latin letter, so the paragraph reads left to right.
assert_eq!(para.base_level, 0);
// One level per byte. The Arabic word starts at byte 5, at level 1: odd, so right to left.
assert_eq!(para.levels.len(), text.len());
assert_eq!(para.levels[3..7], [0, 0, 1, 1]);

// The whole text as one line: three runs, in the order they are drawn from the left.
let runs = para.visual_runs(text, ..);
let drawn: Vec<(&str, u8)> = runs.iter().map(|run| (&text[run.bytes], run.level)).collect();
assert_eq!(drawn, [("Read ", 0), ("مرحبا", 1), (" aloud", 0)]);
base_level: u8
The level of the first paragraph: 0 for left to right, 1 for right to left. Empty text has no paragraph, and then it is 1 if base was BaseDirection::RightToLeft and 0 otherwise.
levels: alloc::vec::Vec<u8>
One level per byte of the text. Every byte of a character holds that character's level, so levels[i] is right for any byte offset i. Odd is right to left.
visual_order: alloc::vec::Vec<usize>
The byte offset where each character starts, in the order the characters are drawn from the left. One entry per character. Each paragraph is ordered as a line of its own, and the paragraphs follow one another in text order.
paragraphs: alloc::vec::Vec<ParagraphRun>
The paragraphs in text order, each a ParagraphRun with its bytes and its level. Empty for empty text.
  • Implements: Clone, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::GeneralCategory
pub enum GeneralCategory {
    Unassigned = 0,
    Control = 1,
    Format = 2,
    PrivateUse = 3,
    Surrogate = 4,
    LowercaseLetter = 5,
    ModifierLetter = 6,
    OtherLetter = 7,
    TitlecaseLetter = 8,
    UppercaseLetter = 9,
    SpacingMark = 10,
    EnclosingMark = 11,
    NonspacingMark = 12,
    DecimalNumber = 13,
    LetterNumber = 14,
    OtherNumber = 15,
    ConnectPunctuation = 16,
    DashPunctuation = 17,
    ClosePunctuation = 18,
    FinalPunctuation = 19,
    InitialPunctuation = 20,
    OtherPunctuation = 21,
    OpenPunctuation = 22,
    CurrencySymbol = 23,
    ModifierSymbol = 24,
    MathSymbol = 25,
    OtherSymbol = 26,
    LineSeparator = 27,
    ParagraphSeparator = 28,
    SpaceSeparator = 29,
}

A character's Unicode general category: what kind of character it is, such as an uppercase letter, a digit, a combining mark or a space.

general_category returns it for a char. Unicode gives every code point exactly one category and writes it as two letters, the first of which is the broad class: L for letters, M for marks, N for numbers, P for punctuation, S for symbols, Z for separators and C for controls and the rest.

The set is fixed by Unicode's stability policy, so the enum is not #[non_exhaustive]: a match can name every variant and needs no _ arm.

use daegun::unicode::{general_category, GeneralCategory};

// Count the letters and the digits of a string, in any script.
let (mut letters, mut digits) = (0, 0);
for c in "Route 66, Größe ٣".chars() {
    match general_category(c) {
        GeneralCategory::UppercaseLetter
        | GeneralCategory::LowercaseLetter
        | GeneralCategory::TitlecaseLetter
        | GeneralCategory::ModifierLetter
        | GeneralCategory::OtherLetter => letters += 1,
        GeneralCategory::DecimalNumber => digits += 1,
        _ => {}
    }
}
assert_eq!((letters, digits), (10, 3));
Unassigned = 0
Cn. A code point with no character assigned to it, such as U+0378, noncharacters such as U+FFFF included.
Control = 1
Cc. A C0 or C1 control code, such as tab, newline and U+0085.
Format = 2
Cf. A format control, which draws nothing and steers the text around it, such as the zero width joiner U+200D and the soft hyphen U+00AD.
PrivateUse = 3
Co. A private use character, such as U+E000, whose meaning is left to the font and the application.
Surrogate = 4
Cs. A surrogate code point, half of a UTF-16 pair. A Rust char is never one, so general_category does not return it.
LowercaseLetter = 5
Ll. A lowercase letter, such as a or ß.
ModifierLetter = 6
Lm. A modifier letter, such as the superscript ʰ or the Japanese long vowel mark ー.
OtherLetter = 7
Lo. A letter with no case, which covers most scripts: Arabic and Hebrew letters, Han ideographs, kana and Hangul syllables.
TitlecaseLetter = 8
Lt. A digraph in title case, one character drawn as a capital and a small letter, such as Dž.
UppercaseLetter = 9
Lu. An uppercase letter, such as A or Σ.
SpacingMark = 10
Mc. A combining mark that takes room of its own on the line, such as the Devanagari vowel sign U+093F.
EnclosingMark = 11
Me. A combining mark that surrounds its base, such as the enclosing circle U+20DD.
NonspacingMark = 12
Mn. A combining mark that takes no room of its own, such as the acute accent U+0301.
DecimalNumber = 13
Nd. A decimal digit of any script, such as 7 or the Arabic-Indic ٣.
LetterNumber = 14
Nl. A number written as a letter, such as the Roman numeral Ⅷ.
OtherNumber = 15
No. Any other number, such as the fraction ½ or the superscript ².
ConnectPunctuation = 16
Pc. Punctuation that joins words, such as the underscore.
DashPunctuation = 17
Pd. A dash or hyphen, such as - and the en dash.
ClosePunctuation = 18
Pe. A closing bracket, such as ), ] or }.
FinalPunctuation = 19
Pf. A closing quotation mark, such as ” or ».
InitialPunctuation = 20
Pi. An opening quotation mark, such as “ or «.
OtherPunctuation = 21
Po. All other punctuation, such as ., ,, !, ?, % and the straight quotation mark and apostrophe.
OpenPunctuation = 22
Ps. An opening bracket, such as (, [ or {.
CurrencySymbol = 23
Sc. A currency sign, such as $ or €.
ModifierSymbol = 24
Sk. A modifier symbol, an accent that stands alone and takes room, such as ^ or ¨.
MathSymbol = 25
Sm. A math symbol, such as +, =, < or ~.
OtherSymbol = 26
So. Any other symbol, such as © or °, and pictographs such as 😀.
LineSeparator = 27
Zl. The line separator, U+2028, and nothing else.
ParagraphSeparator = 28
Zp. The paragraph separator, U+2029, and nothing else.
SpaceSeparator = 29
Zs. A space, such as the ordinary space, the no-break space U+00A0 and the ideographic space U+3000. Tab and newline are Cc, not spaces.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::LineBreak
#[non_exhaustive]
pub struct LineBreak {
    pub at: usize,
    pub mandatory: bool,
}

One place a line may end, as line_break_opportunities finds it: where the next line would start, and whether the break is forced.

at is a byte offset where a character starts. The line before the break is the text up to at, and the next line starts there. Spaces that a break follows stay on the line before it.

A break is either allowed or mandatory. An allowed break, with mandatory false, is a place the line may end when it has run out of room, such as after a space or a hyphen. A mandatory break is a place the line must end however much room is left: after a newline or another hard line break, and at the end of the text.

It is #[non_exhaustive], so read its fields rather than building one by literal.

use daegun::unicode::{line_break_opportunities, LineBreak};

let text = "one two\nthree";
let breaks: Vec<LineBreak> = line_break_opportunities(text, None);

// Cut the text into the lines its mandatory breaks demand.
let mut lines = Vec::new();
let mut start = 0;
for b in breaks.iter().filter(|b| b.mandatory) {
    lines.push(&text[start..b.at]);
    start = b.at;
}
assert_eq!(lines, ["one two\n", "three"]);

// The one allowed break is at byte 4, after the space.
let allowed: Vec<usize> = breaks.iter().filter(|b| !b.mandatory).map(|b| b.at).collect();
assert_eq!(allowed, [4]);
at: usize
Where the next line starts, as a byte offset into the text, so &text[..at] ends with the line before the break. It is never 0, and it is text.len() for the last break of a text.
mandatory: bool
True where the text demands the break: after a newline, a carriage return (with a newline right after it, the break comes after the pair), a vertical tab, a form feed, U+0085, U+2028 or U+2029, and at the end of the text. False where a line may break and need not.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::ParagraphRun
#[non_exhaustive]
pub struct ParagraphRun {
    pub start: usize,
    pub end: usize,
    pub level: u8,
}

One paragraph of a BidiParagraph: the bytes it covers, its separator included, and its level.

The entries of BidiParagraph::paragraphs. A paragraph runs through the separator that ends it, a newline for instance, so the end of one is the start of the next and together they cover the whole text. The last paragraph ends at the end of the text, and a newline that closes the text starts no empty paragraph after it.

It has a start and an end rather than a range, so slice with &text[p.start..p.end]. It is #[non_exhaustive]: read its fields rather than building one by literal.

use daegun::unicode::{BaseDirection, BidiParagraph, ParagraphRun};

let text = "abc\nשלום";
let para = BidiParagraph::new(text, BaseDirection::Auto);
let found: Vec<(&str, u8)> =
    para.paragraphs.iter().map(|p: &ParagraphRun| (&text[p.start..p.end], p.level)).collect();
// The newline belongs to the first paragraph. The second starts with a Hebrew letter: right to left.
assert_eq!(found, [("abc\n", 0), ("שלום", 1)]);
start: usize
The byte offset where the paragraph starts.
end: usize
The byte offset where it ends, which is past its separator where it has one.
level: u8
The paragraph's own level: 0 for left to right, 1 for right to left.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::Script
pub struct Script(/* private */);

A Unicode script: the writing system a character belongs to, such as Latin, Arabic or Han.

Every script is a constant on the type: Script::LATIN, Script::ARABIC, Script::DEVANAGARI and so on. There is one for each script in the Unicode data daegun is built from, version 18.0, which makes 177 with Script::COMMON and Script::INHERITED. You also get a script from script for a character, from script_runs for a text, from Script::from_iso15924 for a four-letter code, and by parsing a name or a code. It is Copy, compares with ==, and its constants work as match patterns.

Three values are not writing systems. Script::COMMON is for the characters many scripts share: digits, spaces, punctuation and symbols. Script::INHERITED is for the combining marks several scripts share, such as accents, which take the script of the character they are attached to. And a character Unicode gives no script, an unassigned or private use one, has an unknown script: it has no constant, its Script::name is Unknown and its Script::iso15924 is None. Script::is_context_dependent is true for these three and false for every other.

Shaping goes by script. The script of a run picks the shaping model, the direction and which of the font's OpenType script tables apply. Font::shape takes it from the first character of the text that has a script of its own, and Font::shape_bidi and Font::layout cut the text where the script changes and shape each piece as its own. For text with no script of its own, such as digits that belong to an Arabic sentence, name the script with ShapeOptions::with_seed_script.

use daegun::unicode::{script, Script};

// From a character, from a name and from an ISO 15924 code.
assert_eq!(script('ب'), Script::ARABIC);
let parsed: Script = "Arabic".parse()?;
assert_eq!(parsed, Script::ARABIC);
assert_eq!(Script::from_iso15924("Arab"), Some(Script::ARABIC));

// The constants work as patterns.
let family = match script('字') {
    Script::HAN | Script::HIRAGANA | Script::KATAKANA => "Chinese or Japanese",
    Script::LATIN => "Latin",
    _ => "another",
};
assert_eq!(family, "Chinese or Japanese");
assert_eq!(Script::HAN.to_string(), "Han");
impl Display
Writes the script's Unicode name, the text Script::name returns, such as Arabic or Old_Italic.
impl FromStr
Reads a Unicode script name as Script::name writes it, such as Arabic or Old_Italic, or an ISO 15924 code such as Arab, in any letter case. Anything else is an error of kind ErrorKind::InvalidArgument, a name written with a space in place of its underscore included.
  • Implements: Clone, Copy, Debug, Display, Eq, FromStr, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::ScriptDirection
pub enum ScriptDirection {
    LeftToRight,
    RightToLeft,
}

Which way a script is written across a line: left to right or right to left.

Script::direction returns it. It describes a script, not a piece of text: the order of mixed text comes from BidiParagraph.

A script answers with the direction its letters have in Unicode. One that was once written either way, as Old Italic was, answers left to right.

use daegun::unicode::{script_runs, ScriptDirection};

// Which parts of a text are in a right-to-left script?
let text = "abc שלום";
let right_to_left: Vec<&str> = script_runs(text)
    .iter()
    .filter(|run| run.script.direction() == ScriptDirection::RightToLeft)
    .map(|run| &text[run.bytes])
    .collect();
assert_eq!(right_to_left, ["שלום"]);
LeftToRight
Left to right, as Latin, Greek, Cyrillic and Devanagari are written. Also the answer for a script with no direction of its own, such as Script::COMMON.
RightToLeft
Right to left, as Arabic, Hebrew, Syriac and Thaana are written.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::ScriptRun
#[non_exhaustive]
pub struct ScriptRun {
    pub bytes: core::range::Range<usize>,
    pub script: Script,
}

One run of text in a single script, as script_runs returns it: the bytes it covers and the script.

The runs of a text come in order and each starts where the last one ended, so together they cover every byte.

It is #[non_exhaustive], so read its fields rather than building one by literal.

use daegun::unicode::{script_runs, Script, ScriptRun};

let text = "abc αβγ";
let runs: Vec<ScriptRun> = script_runs(text);
assert_eq!(runs.len(), 2);
// The space has no script of its own and stays with the run before it.
assert_eq!((&text[runs[0].bytes], runs[0].script), ("abc ", Script::LATIN));
assert_eq!((&text[runs[1].bytes], runs[1].script), ("αβγ", Script::GREEK));
// Each run starts where the last one ended.
assert_eq!(runs[0].bytes.end, runs[1].bytes.start);
bytes: core::range::Range<usize>
The byte range of the text the run covers, with both ends where a character starts, so &text[run.bytes] is its text. The range is Copy, and slicing with it does not use it up.
script: Script
The run's script. It is never Script::INHERITED or the unknown script, and it is Script::COMMON only for a text with no character of a script of its own, which is one run.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::VerticalOrientation
#[non_exhaustive]
pub enum VerticalOrientation {
    Rotated = 0,
    TransformedRotated = 1,
    TransformedUpright = 2,
    Upright = 3,
}

How a character stands in vertical text: upright, or turned on its side.

It is the character's Vertical_Orientation property from UAX #50, which vertical_orientation returns. In a line that runs down the page, CJK ideographs and kana stand upright one under another, while Latin letters and digits lie on their side, turned a quarter turn clockwise.

Two of the values are for characters whose upright shape in vertical text differs from the horizontal one, such as brackets and small kana. Font::layout reads the property under TextOrientation::Mixed, the default for vertical lines: it sets Upright and TransformedUpright characters upright and Rotated ones on their side, and sets a TransformedRotated character upright only where vertical_form has a form for it.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::unicode::{vertical_orientation, VerticalOrientation};

// Which characters of a vertical line are turned on their side?
let turned: String = "日本語とABC"
    .chars()
    .filter(|&c| vertical_orientation(c) == VerticalOrientation::Rotated)
    .collect();
assert_eq!(turned, "ABC");

let stands = match vertical_orientation('「') {
    VerticalOrientation::Upright | VerticalOrientation::TransformedUpright => "upright",
    VerticalOrientation::TransformedRotated => "upright if it has a vertical form",
    VerticalOrientation::Rotated => "on its side",
    _ => "unknown to this code",
};
assert_eq!(stands, "upright if it has a vertical form");
Rotated = 0
R. Set on its side, turned a quarter turn clockwise, as Latin letters and digits are.
TransformedRotated = 1
Tr. Set upright, in a shape made for vertical text, where Unicode encodes such a shape, the one vertical_form gives, and on its side otherwise. Brackets such as 「 and ( have one. The long vowel mark ー has none, so a layout sets it on its side.
TransformedUpright = 2
Tu. Set upright, in a shape made for vertical text where there is one. The ideographic comma and full stop, 、 and 。, and small kana such as っ.
Upright = 3
U. Set upright as it is, as CJK ideographs, kana, Hangul syllables and emoji are.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::VisualRun
#[non_exhaustive]
pub struct VisualRun {
    pub bytes: core::range::Range<usize>,
    pub level: u8,
}

One run of a line in drawing order, as BidiParagraph::visual_runs returns it: the bytes it covers and their level.

The runs of a line come in the order they are drawn, from the left, and each covers one stretch of the text at one level. A run with an even level reads left to right, so its first character is at its left edge. A run with an odd level reads right to left, so its first character is at its right edge.

The byte ranges follow the drawing order, not the text, so a later run can cover earlier bytes. To draw a line, shape &text[run.bytes] for each run in the direction its level gives and set the runs one after another from the left.

It is #[non_exhaustive], so read its fields rather than building one by literal.

use daegun::unicode::{BaseDirection, BidiParagraph, VisualRun};

// A Hebrew word, then an English one: a right-to-left paragraph.
let text = "שלום abc";
let para = BidiParagraph::new(text, BaseDirection::Auto);
let runs: Vec<VisualRun> = para.visual_runs(text, ..);

// The English word comes last in the text and first from the left, at level 2.
assert_eq!((&text[runs[0].bytes], runs[0].level), ("abc", 2));
assert_eq!((&text[runs[1].bytes], runs[1].level), ("שלום ", 1));
for run in &runs {
    let right_to_left = run.level % 2 == 1;
    // Shape &text[run.bytes] in that direction and draw it at the pen.
}
bytes: core::range::Range<usize>
The byte range of the text the run covers, so &text[run.bytes] is its text in reading order. In a run with an odd level that text is drawn from its last character to its first.
level: u8
The bidi level of the run. Odd is right to left, even is left to right.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
unicode::WordSegmenter
pub struct WordSegmenter<'a>(

A function of yours that finds the word boundaries in text written without spaces between words, such as Thai, Lao, Khmer and Myanmar.

A line may break between words, and in these scripts nothing in the text marks where a word ends: it takes a word list or a language model to know. daegun has word lists for Thai, Lao, Khmer and Myanmar behind its dictionaries crate feature. A WordSegmenter is how you supply the words yourself. It works with or without that feature, and is used in place of the lists.

It wraps a reference to a function or closure that takes a &str and a &mut Vec<usize>. daegun calls it with one stretch of such text at a time: a run of consecutive characters of UAX #14's line break class SA, which holds the letters and marks of these scripts, so a stretch ends at a space, a digit or any character of another kind. The function pushes the word boundaries inside the stretch onto the list, which arrives empty, as byte offsets counted from the start of the stretch.

Each offset becomes an allowed line break. One is ignored if it is 0, if it is the length of the stretch or more, if it is not where a character starts, or if it falls before a combining mark.

Pass it to line_break_opportunities, or to Font::layout with LayoutOptions::with_segmenter, which is how a layout breaks such text between words. It holds a reference, so the function must live as long as the segmenter is in use. The function must be Sync, since options that hold a segmenter may be shared between threads, and it is called on the thread that breaks the text. State it changes between calls belongs in a Mutex or an atomic, not a Cell.

use daegun::unicode::{line_break_opportunities, WordSegmenter};

// A Thai greeting of two words, with no space between them.
let text = "สวัสดีครับ";
let first = "สวัสดี".len();

// A real segmenter looks words up. This one knows the one boundary in this text.
let find_words = |stretch: &str, boundaries: &mut Vec<usize>| {
    boundaries.push(first);
};
let breaks = line_break_opportunities(text, Some(WordSegmenter(&find_words)));
let at: Vec<usize> = breaks.iter().map(|b| b.at).collect();
// An allowed break between the two words, then the end of the text.
assert_eq!(at, [first, text.len()]);

// With no segmenter, and built without the `dictionaries` feature, only the end is left.
let plain = line_break_opportunities(text, None);
assert_eq!(plain.len(), 1);
Segmenter<'a>
The function, a &(dyn Fn(&str, &mut Vec<usize>) + Sync). It is given one stretch of text and an empty list, and pushes the byte offsets of the word boundaries inside the stretch, counted from its start.
  • Implements: Clone, Copy, Debug.
  • Auto traits: Send, Sync, Unpin.

Layout

Paragraphs laid out in lines: wrapped, broken, aligned, in either writing mode, and one line justified by a font's JSTF table. Font::layout and the types in daegun::layout, all in font units.

layout::Adjustment
pub enum Adjustment {
    Shrink,
    Extend,
}

The two ways justification can change a line: make it narrower or make it wider.

A JSTF priority level holds one set of lookups for each. You pass an Adjustment to Font::shape_justified to say which set to apply, and Justified::adjustment reports which way Font::justify had to go.

The enum is complete, so a match on it needs no _ arm.

use daegun::layout::{Adjustment, JustifyOptions};
use daegun::{Location, Orientation, Tag};

let (text, at, arab) = ("Aa الماس", Location::default(), Tag::new(b"arab"));
// daegun's JSTF test font sets this line 7649 units wide. A target below that means it
// has to shrink, and the second level's shrinkage lookups bring it to 6744.
let narrower = JustifyOptions::new(arab, 6_744.0);
let line = font.justify(text, &at, Orientation::Horizontal, &narrower);
assert_eq!(line.adjustment, Adjustment::Shrink);
assert_eq!((line.level, line.width), (Some(1), 6744.0));

// A target above it means it has to grow, which the first level's extension lookups do.
let wider = JustifyOptions::new(arab, 8_127.0);
let line = font.justify(text, &at, Orientation::Horizontal, &wider);
match line.adjustment {
    Adjustment::Extend => { /* the line had to grow */ }
    Adjustment::Shrink => { /* the line had to shrink */ }
}
Shrink
Make the line narrower, with the level's four shrinkage lists.
Extend
Make the line wider, with the level's four extension lists.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::Align
#[non_exhaustive]
pub enum Align {
    Start,
    End,
    Center,
    Justify,
}

Where each line sits in the measure: at the start edge, at the end edge, centered, or spread to fill it.

Set it with LayoutOptions::with_align. The measure is LayoutOptions::max_inline_size. With no measure there is no far edge, so lines align against the longest line of the layout instead.

Start and end follow the direction of the paragraph. In a left-to-right paragraph the start edge is the left one, and in a right-to-left paragraph it is the right one. In a vertical line the two edges are the top and the bottom: the start edge is the top in a left-to-right paragraph and the bottom in a right-to-left one. Under TextOrientation::Upright it is always the top.

The shift is already in each run's PositionedRun::offset, so you draw runs where their offsets say.

Justifying. Justify changes every character Unicode classes as a space separator: the plain space, the no-break space, and the fixed-width ones such as the em space, the thin space and the ideographic space (U+3000). The room is shared in proportion to each space's own advance, so a wider space takes more of it. On a line with tabs only the spaces after the last tab change, so the tab stops hold. A justified line's LayoutLine::inline_size is the measure, to within rounding, and its runs carry the changed advances.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::layout::{Align, LayoutOptions};
use daegun::Location;

let text = "Type is the voice of the page, and a paragraph is where it speaks.";
let scale = 16.0 / f64::from(font.units_per_em());
let measure = 240.0 / scale;
let column = LayoutOptions::default().with_max_inline_size(measure);

let centered = font.layout(text, &Location::default(), &column.with_align(Align::Center));
let line = &centered.lines[0];
// Half of the room the line leaves is on its left.
assert_eq!(line.runs[0].offset.x, (measure - line.inline_size) / 2.0);

let justified = font.layout(text, &Location::default(), &column.with_align(Align::Justify));
// The first two lines now fill the measure. The last line of the paragraph keeps its width.
assert!((justified.lines[0].inline_size - measure).abs() < 1e-6);
assert!((justified.lines[1].inline_size - measure).abs() < 1e-6);
assert!(justified.lines[2].inline_size < measure);
Start
Lines begin at the start edge: the left in a left-to-right paragraph, the right in a right-to-left one. The default.
End
Lines finish at the end edge, the side opposite the start.
Center
Each line is centered in the measure.
Justify
Each line is made to fill the measure by widening its spaces, or under BreakStrategy::Optimal by narrowing them up to a third. A line that ends at a hard break keeps its width and sits at the start edge: the last line of a paragraph, and a line cut short by a line separator (U+2028) as well. LayoutLine::hard_break is true for exactly these lines. A line with no space to widen is left alone too.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::BreakStrategy
#[non_exhaustive]
pub enum BreakStrategy {
    Greedy,
    Optimal,
}

How the line breaks of a paragraph are chosen: one line at a time, or all together.

The measure is LayoutOptions::max_inline_size. Both strategies break at the same opportunities, and both keep every line within the measure wherever the text can be cut to fit. They differ in which breaks they pick. Set one with LayoutOptions::with_strategy.

With no measure there is nothing to choose, and both break only at hard breaks.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::layout::{BreakStrategy, LayoutOptions};
use daegun::Location;

let text = "Type is the voice of the page, and a paragraph is where it speaks.";
let scale = 16.0 / f64::from(font.units_per_em());
let lines = |strategy: BreakStrategy| -> Vec<&str> {
    let options = LayoutOptions::default().with_max_inline_size(160.0 / scale).with_strategy(strategy);
    let layout = font.layout(text, &Location::default(), &options);
    layout.lines.iter().map(|line| &text[line.bytes]).collect()
};

// Greedy fills the first line, and the second comes out short.
assert_eq!(lines(BreakStrategy::Greedy)[..2], ["Type is the voice of ", "the page, and a "]);
// Optimal moves a word down, and the two come out nearer in length.
assert_eq!(lines(BreakStrategy::Optimal)[..2], ["Type is the voice ", "of the page, and a "]);
Greedy
Puts as much on each line as fits, then starts the next: every line breaks at the last opportunity that fits. The default.
Optimal
Chooses all the breaks of a paragraph together, by the total-fit method of Knuth and Plass, so the lines come out close in length. It weighs how far each line falls from the measure, avoids a tight line next to a loose one, and charges for a break at a soft hyphen, more for two in a row. It does more work per paragraph than Greedy.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::JstfModLists
#[non_exhaustive]
pub struct JstfModLists {
    pub shrinkage_enable_gsub: Option<Vec<u16>>,
    pub shrinkage_disable_gsub: Option<Vec<u16>>,
    pub shrinkage_enable_gpos: Option<Vec<u16>>,
    pub shrinkage_disable_gpos: Option<Vec<u16>>,
    pub extension_enable_gsub: Option<Vec<u16>>,
    pub extension_disable_gsub: Option<Vec<u16>>,
    pub extension_enable_gpos: Option<Vec<u16>>,
    pub extension_disable_gpos: Option<Vec<u16>>,
}

One JSTF priority level: the GSUB and GPOS lookups a font says to turn on and off to shrink a line, and those to extend one.

Font::justification_priorities returns a list of them, and Font::shape_justified shapes with one applied. Each field is a list of lookup indices into the font's GSUB or GPOS lookup list. The four shrinkage_ lists are for making a line narrower and the four extension_ lists for making it wider.

A field is None where the level has no such list at all, and Some of an empty list where it has one that names no lookups. Shaping treats the two alike. A level's two JstfMax tables, the font's limits for a justifier that adds space itself, are not read: the eight lookup lists are all daegun gives you.

It is #[non_exhaustive], so to make a level of your own start from JstfModLists::default(), which has no lists, and set the fields you want.

use daegun::layout::{Adjustment, JstfModLists};
use daegun::{Location, Orientation, Tag};

let levels: Vec<JstfModLists> =
    font.justification_priorities(Tag::new(b"arab"), None).unwrap_or_default();
// daegun's JSTF test font has two levels. To extend a line, the first lists GSUB lookup 0
// to turn on, and the second has a GPOS list that names no lookups.
assert_eq!(levels.len(), 2);
assert_eq!(levels[0].extension_enable_gsub, Some(vec![0]));
assert_eq!(levels[1].extension_enable_gpos, Some(vec![]));

// Shaped with the first level's extension lists, this line goes from 7649 units to 8127.
let (text, at) = ("Aa الماس", Location::default());
let wider = font.shape_justified(text, &at, Orientation::Horizontal, &levels[0], Adjustment::Extend);
assert_eq!(wider.width(), 8127.0);

// A level of your own starts with no lists.
let mut level = JstfModLists::default();
level.extension_disable_gpos = Some(vec![1]);
shrinkage_enable_gsub: Option<Vec<u16>>
GSUB lookups to turn on when shrinking a line, such as one that forms extra ligatures.
shrinkage_disable_gsub: Option<Vec<u16>>
GSUB lookups to leave out of shaping when shrinking a line.
shrinkage_enable_gpos: Option<Vec<u16>>
GPOS lookups to turn on when shrinking a line, such as one that tightens spacing.
shrinkage_disable_gpos: Option<Vec<u16>>
GPOS lookups to leave out of shaping when shrinking a line.
extension_enable_gsub: Option<Vec<u16>>
GSUB lookups to turn on when extending a line, such as one that swaps in wider forms of letters.
extension_disable_gsub: Option<Vec<u16>>
GSUB lookups to leave out of shaping when extending a line, such as ligatures, so the letters take their full width.
extension_enable_gpos: Option<Vec<u16>>
GPOS lookups to turn on when extending a line, such as one that adds space between letters.
extension_disable_gpos: Option<Vec<u16>>
GPOS lookups to leave out of shaping when extending a line, such as kerning that pulls letters together.
  • Implements: Clone, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::Justified
#[non_exhaustive]
pub struct Justified {
    pub run: Arc<ShapedRun>,
    pub level: Option<usize>,
    pub adjustment: Adjustment,
    pub width: f64,
    pub best_effort: bool,
}

What Font::justify returns: the line as shaped, its width, the JSTF level that produced it and whether it reached the target.

Draw run. Then check best_effort: when it is true the font could not bring the line within the tolerance, and what is left between width and your target is yours to make up by other means, such as widening spaces.

It is #[non_exhaustive] and has no constructor: you get one from Font::justify.

use daegun::layout::{Justified, JustifyOptions};
use daegun::{Location, Orientation, Tag};

let text = "Aa الماس";
// This line is 7649 units wide as it stands. Ask for 9000.
let options = JustifyOptions::new(Tag::new(b"arab"), 9_000.0);
let line: Justified = font.justify(text, &Location::default(), Orientation::Horizontal, &options);

// daegun's JSTF test font gets it to 8127 at its first level, and no level gets nearer.
assert_eq!(line.level, Some(0));
assert_eq!(line.width, 8127.0);
assert!(line.best_effort);
// What is left to make up by other means, such as widening the space.
let gap = options.target_width - line.width;
assert_eq!(gap, 873.0);
run: Arc<ShapedRun>
The shaped line to draw, a ShapedRun in an Arc. When no level was used it is the natural run, the one plain shaping gives.
level: Option<usize>
The index of the priority level the run was shaped at, counting from 0 in the order Font::justification_priorities returns them. None when the natural run was kept.
adjustment: Adjustment
Which way the line had to go: Adjustment::Shrink when its natural width is above the target by more than the tolerance, otherwise Adjustment::Extend. A line that already fit reports Extend.
width: f64
The width of run in font units, the sum of its advances.
best_effort: bool
True when neither the natural run nor any level came within the tolerance of the target, so run is only the nearest of them. False when the target was reached.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::JustifyOptions
#[non_exhaustive]
pub struct JustifyOptions {
    pub script: Tag,
    pub language_system: Option<Tag>,
    pub target_width: f64,
    pub tolerance: f64,
}

What Font::justify should justify a line to: the target width, how near counts as reached, and which script's JSTF levels to use.

Build one with JustifyOptions::new, which takes the two things that have no default, the script and the width. Then add a tolerance or a language system with the with_ methods. It is #[non_exhaustive], so there is no struct literal to write, and it has no Default.

Widths are in font units. For a line 240 px wide at 16 px, the target is 240.0 / (16.0 / f64::from(font.units_per_em())).

use daegun::layout::JustifyOptions;
use daegun::{Location, Orientation, Tag};

// A line 8000 units wide, give or take 200, justified with the font's levels for Arabic.
let options = JustifyOptions::new(Tag::new(b"arab"), 8_000.0).with_tolerance(200.0);
assert_eq!((options.target_width, options.tolerance), (8_000.0, 200.0));

let line = font.justify("Aa الماس", &Location::default(), Orientation::Horizontal, &options);
// daegun's JSTF test font takes the line from 7649 units to 8127 at its first level,
// which is within the tolerance.
assert_eq!((line.level, line.width, line.best_effort), (Some(0), 8127.0, false));
script: Tag
The OpenType script tag whose JSTF levels to use, such as arab. It is not worked out from the text. If the font's table does not list this script there are no levels to try, and the line keeps its natural shaping.
language_system: Option<Tag>
An OpenType language system tag, such as URD , whose levels to use. None, the default, uses the script's default levels, and so does a language system the script does not list.
target_width: f64
The width the line should have, in font units.
tolerance: f64
How far from the target a width may be, on either side, and still count as reaching it, in font units. 0 by default, which asks for the exact width. Below 0, or NaN, it accepts nothing.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::LayoutLine
#[non_exhaustive]
pub struct LayoutLine {
    pub runs: Vec<PositionedRun>,
    pub bytes: Range<usize>,
    pub baseline: f64,
    pub inline_size: f64,
    pub ascent: f64,
    pub descent: f64,
    pub hard_break: bool,
}

One line of a layout: its runs in the order they are drawn, the text it covers and where its baseline sits.

Lines come in TextLayout::lines. Their byte ranges follow one another with no gaps, so a line's bytes takes in the spaces and the line break that end it, though they are not drawn.

Every line of a layout has the same ascent and descent. They are the line metrics of the font, as Font::line_metrics gives them for the writing mode, not measured from the glyphs on the line.

It is #[non_exhaustive], so read its fields rather than building one by literal. LayoutLine::default() gives an empty one where a test needs it.

use daegun::layout::{LayoutLine, LayoutOptions};
use daegun::Location;

let text = "Type is the voice of the page, and a paragraph is where it speaks.";
let scale = 16.0 / f64::from(font.units_per_em());
let options = LayoutOptions::default().with_max_inline_size(240.0 / scale);
let layout = font.layout(text, &Location::default(), &options);

let first: &LayoutLine = &layout.lines[0];
// The line's text, with the space it wrapped at.
assert_eq!(&text[first.bytes], "Type is the voice of the page, ");
// It ends where the text wrapped, not at a hard break.
assert!(!first.hard_break);
// Its top and bottom edges in pixels, down from the top of the block: 0 and about 19.4.
let top = (first.baseline - first.ascent) * scale;
let bottom = (first.baseline - first.descent) * scale;
runs: Vec<PositionedRun>
The runs of the line in visual order: left to right as drawn in horizontal text, top to bottom in vertical text. There is one run for each stretch of a single script, bidi level and orientation. A blank line has none.
bytes: Range<usize>
The byte range of the text on this line, with the trailing spaces and the line break characters that end it. &text[line.bytes] is the line's text.
baseline: f64
Where the baseline sits in the block. In horizontal text, how far down it is from the top of the block. In vertical text, how far right it is from the left edge of the block.
inline_size: f64
The length of the line: the sum of its runs' advances, without the spaces that hang at its end. A line that Align::Justify filled is as long as the measure.
ascent: f64
How far the line reaches above its baseline: the ascent of the font's line metrics. In vertical text it is the part to the right of the baseline.
descent: f64
How far the line reaches below its baseline, as a negative number: the descent of the font's line metrics. In vertical text it is the part to the left of the baseline.
hard_break: bool
True when the line ends at a hard break or at the end of the text. The hard breaks are a newline, a carriage return (a CR LF pair counts once), a next line (U+0085), a vertical tab, a form feed, a line separator (U+2028) and a paragraph separator (U+2029). False for a line that ends where the text wrapped. Align::Justify leaves a line alone when this is true.
  • Implements: Clone, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::LayoutOptions
#[non_exhaustive]
pub struct LayoutOptions<'a> {
    pub max_inline_size: f64,
    pub align: Align,
    pub writing_mode: WritingMode,
    pub text_orientation: TextOrientation,
    pub base_direction: BaseDirection,
    pub language: Option<&'a str>,
    pub line_height: Option<f64>,
    pub strategy: BreakStrategy,
    pub max_lines: Option<usize>,
    pub tab_size: f64,
    pub segmenter: Option<WordSegmenter<'a>>,
    pub features: &'a [Feature],
}

How Font::layout sets text: the width to wrap at, alignment, writing mode, line height, how lines are chosen and what shaping is told.

Start from LayoutOptions::default(), or from LayoutOptions::DEFAULT in a constant, and change what you need with the with_ methods, each of which returns the changed options. The type is #[non_exhaustive], so there is no struct literal to write. The fields are public, so you can read them, and assign one on a mut copy, for instance to put max_lines back to None.

The defaults set text in horizontal lines that end only at hard breaks: no measure, lines at the start edge, direction taken from the text, the font's own line height, greedy breaking, tab stops 8 spaces apart, and no language, features or segmenter.

Every length is in font units. To wrap 16 px text at 240 px, the measure is 240.0 / (16.0 / f64::from(font.units_per_em())).

The lifetime is that of the language string, the feature slice and the segmenter the options borrow.

use daegun::layout::{Align, BreakStrategy, LayoutOptions};
use daegun::Location;

// 16 px text, justified in a column 240 px wide, with baselines 22 px apart.
let scale = 16.0 / f64::from(font.units_per_em());
let options = LayoutOptions::default()
    .with_max_inline_size(240.0 / scale)
    .with_line_height(22.0 / scale)
    .with_align(Align::Justify)
    .with_strategy(BreakStrategy::Optimal);

let text = "Type is the voice of the page, and a paragraph is where it speaks.";
let layout = font.layout(text, &Location::default(), &options);
// Three lines. The first two fill the 240 px, and the last keeps its own width.
assert_eq!((layout.lines[1].baseline - layout.lines[0].baseline) * scale, 22.0);
max_inline_size: f64
The measure: the longest a line may be, in font units, which is where text wraps. It is the width of a column of horizontal text and the height of a column of vertical text. The default is infinite, which wraps only at hard breaks. A value below 0 is taken as 0, and NaN as infinite.
align: Align
Where each line sits in the measure. Align::Start by default. With no measure, lines align against the longest line.
writing_mode: WritingMode
Whether lines run across or down, and which way they stack. WritingMode::Horizontal by default.
text_orientation: TextOrientation
How characters stand in vertical lines. TextOrientation::Mixed by default. Horizontal text does not read it.
base_direction: BaseDirection
The direction of the paragraphs, which orders the runs of a mixed line and decides which edge is the start. BaseDirection::Auto, the default, lets the first strongly directional character of each paragraph decide.
language: Option<&'a str>
The language of the text as a BCP 47 tag, such as tr, handed to shaping so the font applies the forms it keeps for that language. None by default. It does not change where lines may break.
line_height: Option<f64>
The distance from one baseline to the next, in font units. None, the default, takes it from the font: ascent less descent plus line gap, as Font::line_metrics gives them for the writing mode.
strategy: BreakStrategy
How line breaks are chosen. BreakStrategy::Greedy by default.
max_lines: Option<usize>
The most lines to lay out. None, the default, lays out all of them. When lines are left out, TextLayout::truncated says where they begin.
tab_size: f64
The distance between tab stops, as a multiple of the advance of a space. 8 by default. A tab moves to the next stop, counted from the start edge of its line, and skips one closer than half the advance of the digit 0, or than a quarter of the em in a font with no digit 0. At 0 or less, or a size that is not a finite number, tabs take no width.
segmenter: Option<WordSegmenter<'a>>
A WordSegmenter that finds the words in text written without spaces between them, such as Thai, Lao, Khmer and Myanmar, so lines can break there. None by default, which leaves it to the word lists of the dictionaries crate feature. Without that feature such text breaks at spaces and, where it must, between graphemes.
features: &'a [Feature]
OpenType features to turn on, off or set, each a Feature over a byte range of the whole text. Empty by default, which leaves the font's defaults.
  • Implements: Clone, Copy, Debug, Default.
  • Auto traits: Send, Sync, Unpin.
layout::PositionedRun
#[non_exhaustive]
pub struct PositionedRun {
    pub run: ShapedRun,
    pub offset: Offset,
    pub level: u8,
    pub bytes: Range<usize>,
    pub upright: bool,
}

One run on a line: a stretch of text in one script, direction and orientation, shaped and placed.

A line's LayoutLine::runs holds them in visual order. Draw a run by starting a pen at its offset and walking its glyphs, as with any ShapedRun. The offset already includes the line's alignment.

Where a glyph goes. What the layout places counts from the top left corner of the block, x to the right and y down: a run's offset along its line, and the line's LayoutLine::baseline across the block. The offsets of the glyphs inside run are y up, as in any ShapedRun, so going down the block you subtract them. On a horizontal line the pen starts at offset.x and moves right by each advance, and glyph i goes at x pen + run.offsets[i].x and y line.baseline - run.offsets[i].y. On a vertical line the pen starts at offset.y and moves down by each advance, and a glyph of an upright run goes at x line.baseline + run.offsets[i].x and y pen - run.offsets[i].y.

It is #[non_exhaustive], so read its fields rather than building one by literal. PositionedRun::default() gives an empty one where a test needs it.

use daegun::layout::{LayoutOptions, PositionedRun};
use daegun::Location;

let text = "Read مرحبا aloud";
let layout = font.layout(text, &Location::default(), &LayoutOptions::default());

// The second run from the left is the Arabic word.
let arabic: &PositionedRun = &layout.lines[0].runs[1];
assert_eq!(&text[arabic.bytes], "مرحبا");
// It reads right to left, and starts where "Read " ends, 4358 units in.
assert_eq!(arabic.level, 1);
assert_eq!((arabic.offset.x, arabic.offset.y), (4358.0, 0.0));
// Its first glyph on the left is the last letter of the word, at byte 8 of the run's own text.
assert_eq!(arabic.run.clusters[0], 8);
run: ShapedRun
The shaped glyphs, a ShapedRun of the layout's own. Its clusters count bytes from bytes.start, so add that to place a glyph in the whole text. On a justified line the advances of its spaces are already changed, and a tab's advance already reaches its stop.
offset: Offset
Where the run starts along its line, alignment included. In horizontal text x is the distance from the left edge of the column and y is 0. In vertical text x is 0 and y is the distance down from the top of the column: a positive number that grows downward, unlike the y of a glyph offset, which is up.
level: u8
The bidi embedding level. An odd level reads right to left, an even one left to right.
bytes: Range<usize>
The byte range of the text this run covers, so &text[run.bytes] is the text it shows. Spaces that hang at the end of the line are in no run.
upright: bool
False for a run laid on its side in a vertical line, as Latin is under TextOrientation::Mixed. Such a run is shaped as horizontal text, for you to draw turned a quarter turn clockwise so it reads down the line. The layout does not place it across its line: its offset.x is 0 like any other run's, and its glyphs' offsets are measured from the run's own horizontal baseline, so once the run is turned, where that baseline sits beside LayoutLine::baseline is yours to choose. True for every run of horizontal text, and for a run that stands upright in a vertical line, which is shaped top to bottom.
  • Implements: Clone, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::TextLayout
#[non_exhaustive]
pub struct TextLayout {
    pub lines: Vec<LayoutLine>,
    pub inline_size: f64,
    pub block_size: f64,
    pub truncated: Option<usize>,
}

A laid-out block of text: its lines in order, and the size of the block they make.

What Font::layout returns. Everything is in font units. To draw it, walk lines, and on each line its LayoutLine::runs: a run starts at its PositionedRun::offset along the line, and the line's LayoutLine::baseline says where the line sits in the block.

inline_size is the length of the longest line, not the measure: text wrapped at 240 px may be only 224 px wide. Together with block_size it gives the box the text needs, to size a label or a button.

It is #[non_exhaustive], so read its fields rather than building one by literal. TextLayout::default() gives an empty one where a test needs it.

use daegun::layout::{LayoutOptions, TextLayout};
use daegun::Location;

let text = "Type is the voice of the page, and a paragraph is where it speaks.";
let scale = 16.0 / f64::from(font.units_per_em());
let options = LayoutOptions::default().with_max_inline_size(240.0 / scale);
let layout: TextLayout = font.layout(text, &Location::default(), &options);

// The box the text needs, in pixels: about 223.6 wide and 58.1 tall, in three lines.
let (width, height) = (layout.inline_size * scale, layout.block_size * scale);
assert_eq!(layout.lines.len(), 3);
assert_eq!(layout.truncated, None);
lines: Vec<LayoutLine>
The lines in order. In horizontal text they run from the top down. In vertical text the first line is the rightmost column with WritingMode::VerticalRl and the leftmost with WritingMode::VerticalLr. Empty for empty text.
inline_size: f64
The longest line's LayoutLine::inline_size: the width of the widest line in horizontal text, the height of the tallest column in vertical text. It can be less than the measure.
block_size: f64
The extent of the lines stacked together, from the first line's ascent to the last line's descent: the height of the block in horizontal text, its width in vertical text. 0 when there are no lines.
truncated: Option<usize>
When LayoutOptions::max_lines cut the layout short, the byte offset where the text left out begins. None when every line was laid out.
  • Implements: Clone, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::TextOrientation
#[non_exhaustive]
pub enum TextOrientation {
    Mixed,
    Upright,
    Sideways,
}

How characters stand in vertical lines: upright, on their side, or each as Unicode says.

It is read only in a vertical WritingMode. Set it with LayoutOptions::with_text_orientation. Each run of the result says which way it went, in PositionedRun::upright.

An upright run is shaped top to bottom, as Direction::TopToBottom shapes it. A sideways run is shaped as horizontal text, and its horizontal advances carry it down the line. You draw it turned a quarter turn clockwise.

The layout does not place a sideways run across its line. The x of its PositionedRun::offset is 0 like any other run's, and its glyphs' offsets are measured from the run's own horizontal baseline, so once the run is turned, where that baseline sits beside LayoutLine::baseline is yours to choose.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::layout::{LayoutOptions, TextOrientation, WritingMode};
use daegun::Location;

let vertical = LayoutOptions::default().with_writing_mode(WritingMode::VerticalRl);
let stands = |orientation: TextOrientation| -> Vec<bool> {
    let options = vertical.with_text_orientation(orientation);
    let layout = font.layout("日本語ABC", &Location::default(), &options);
    layout.lines[0].runs.iter().map(|run| run.upright).collect()
};

// Two runs, the kanji and the Latin letters.
assert_eq!(stands(TextOrientation::Mixed), [true, false]);
assert_eq!(stands(TextOrientation::Upright), [true, true]);
assert_eq!(stands(TextOrientation::Sideways), [false, false]);
Mixed
Each character stands as its Unicode vertical orientation says: CJK ideographs and kana upright, Latin letters and digits on their side. A character that Unicode stands upright only in a vertical form, such as a CJK bracket, is upright where Unicode has a vertical presentation form for it and lies on its side where it has none. The long vowel mark ー (U+30FC) has none, so inside a katakana word it comes out as a sideways run of its own. The vertical glyphs of the font are not consulted. The default.
Upright
Every character stands upright, Latin included. The line is laid out in text order from top to bottom: the bidirectional algorithm is not run, so right-to-left text is not reordered.
Sideways
Every character lies on its side, CJK included.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
layout::WritingMode
#[non_exhaustive]
pub enum WritingMode {
    Horizontal,
    VerticalRl,
    VerticalLr,
}

Which way lines run, and which way they stack: across and down the page, or down and across it.

Set it with LayoutOptions::with_writing_mode. The two vertical modes are the vertical-rl and vertical-lr of CSS.

In a vertical mode the measure is the height of a column, a run's PositionedRun::offset counts down its column in y, a line's LayoutLine::baseline is an x from the left edge of the block, and the line metrics are the font's vertical ones, as Font::line_metrics gives them for Orientation::Vertical. TextOrientation decides which characters stand upright.

In both vertical modes a line's ascent is the part to the right of its baseline and its descent the part to the left.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::layout::{LayoutOptions, WritingMode};
use daegun::Location;

let options = LayoutOptions::default().with_writing_mode(WritingMode::VerticalRl);
let layout = font.layout("日本語\nテキスト", &Location::default(), &options);

for line in &layout.lines {
    // Every run here stands upright. One that lies on its side is drawn turned instead.
    for run in &line.runs {
        let mut pen = run.offset.y;
        for i in 0..run.run.glyphs.len() {
            let x = line.baseline + run.run.offsets[i].x;
            let y = pen - run.run.offsets[i].y;
            // Draw run.run.glyphs[i] with its origin x units right of the block's left edge and
            // y units below its top.
            pen += run.run.advances[i];
        }
    }
}
// Two columns, the first on the right: its baseline is at x 1500, the second one's at 500.
assert_eq!(layout.lines[0].baseline, 1500.0);
assert_eq!(layout.lines[1].baseline, 500.0);
Horizontal
Lines run across the page and stack downward. The default.
VerticalRl
Lines run down the page and stack from right to left, as Japanese is set. The first line is the rightmost column.
VerticalLr
Lines run down the page and stack from left to right, as Mongolian is set. The first line is the leftmost column.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Outlines

A glyph's shape: as the font stores it in font units, hinted in pixels, or prepared for a rasterizer of your own, with the paths, pens, strokes, curves and polygons around it. The calls are on Font, and the rest is in daegun::outline.

outline::Cap
#[non_exhaustive]
pub enum Cap {
    Butt,
    Round,
    Square,
}

How a stroke ends an open contour: flush, rounded or squared off.

A cap matters only for a contour that is not closed. A glyph's contours all are, so in Font::prepared_outline the cap never shows, and it is with Path::stroke on a path of your own that you choose one. Set it with StrokeStyle::with_cap. A style from StrokeStyle::new has Butt.

An open contour of a single point is drawn as a dot the stroke's width across: round with Round, square with Square, and not at all with Butt.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::outline::{Cap, OutlinePen, Path, StrokeStyle};

// A line 100 units long, stroked 20 wide.
let mut line = Path::new();
line.move_to(0.0, 0.0);
line.line_to(100.0, 0.0);

let reach = |cap: Cap| -> daegun::Result<(f64, f64)> {
    let mut stroked = Path::new();
    line.stroke(&StrokeStyle::new(20.0).with_cap(cap), 0.1, &mut stroked)?;
    let bounds = stroked.bounds().expect("the stroke has ink");
    Ok((bounds.x_min, bounds.x_max))
};
// A butt cap ends with the line. The other two run half the width, 10 units, past each end.
assert_eq!(reach(Cap::Butt)?, (0.0, 100.0));
assert_eq!(reach(Cap::Square)?, (-10.0, 110.0));
assert_eq!(reach(Cap::Round)?, (-10.0, 110.0));
Butt
The stroke stops square at the end of the contour and reaches no farther.
Round
A half circle past the end, half the width in radius.
Square
Squared off, half the width past the end.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::CffHints
#[non_exhaustive]
pub struct CffHints {
    pub stems: Vec<CffStem>,
    pub masks: Vec<CffMask>,
}

A CFF glyph's stem hints and the hint masks its charstring sets as it draws.

Font::cff_hints returns one. stems lists every stem the glyph declares, and masks says which of them are in force from which point of the outline on. Both lists are empty for a glyph that declares no hints.

It is #[non_exhaustive]: read its fields. CffHints::default() is an empty one.

use daegun::outline::CffHints;
use daegun::Location;

// STIX Two Math has CFF outlines.
let glyph = font.glyph_id('A').expect("the font maps A");
let hints: CffHints = font.cff_hints(glyph, &Location::default()).expect("a CFF glyph");

// Its A declares six stems, three level and three upright, and sets four masks as it draws.
assert_eq!(hints.stems.len(), 6);
assert_eq!(hints.stems.iter().filter(|stem| stem.vertical).count(), 3);
assert_eq!(hints.masks.len(), 4);
stems: Vec<CffStem>
Every stem the glyph declares, in the charstring's order. A mask's bits count along this list.
masks: Vec<CffMask>
The hint masks, in the order the charstring sets them. Each puts a set of the stems in force from one point of the outline until the next mask takes over. Empty where the glyph sets none.
  • Implements: Clone, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::CffMask
#[non_exhaustive]
pub struct CffMask {
    pub point: usize,
    pub bits: Vec<u8>,
}

One hint mask of a CFF glyph: which of its stems are in force, and the point they take effect from.

A CFF charstring can change its set of active stems partway through a glyph, with the hintmask operator, so that stems which would conflict are never in force together. Each change is one of these, in CffHints::masks, and holds until the next takes effect. Counter masks, the cntrmask operator, are not listed.

It is #[non_exhaustive]: read its fields.

use daegun::outline::CffMask;
use daegun::Location;

let glyph = font.glyph_id('A').expect("the font maps A");
let hints = font.cff_hints(glyph, &Location::default()).expect("a CFF glyph");

for mask in &hints.masks {
    let in_force: Vec<usize> =
        (0..hints.stems.len()).filter(|&i| mask.bits[i / 8] & (0x80 >> (i % 8)) != 0).collect();
    // From point mask.point on, the stems numbered in `in_force` apply.
}
// The first mask of STIX Two Math's A starts at point 0 and puts stems 0, 1, 2 and 5 of its six in force.
let first: &CffMask = &hints.masks[0];
assert_eq!(first.point, 0);
assert_eq!(first.bits, [0b1110_0100]);
point: usize
The index of the first point the mask applies to. The glyph's points are numbered as HintedOutline::points lists a CFF glyph's, on the curve or a control alike, so a contour's closing line adds no point and a pen's own count can run higher.
bits: Vec<u8>
A bit for each stem of CffHints::stems, in that order, the high bit of each byte first: stem i is in force where bits[i / 8] & (0x80 >> (i % 8)) is not zero. It has a byte for every eight stems, rounded up.
  • Implements: Clone, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::CffStem
#[non_exhaustive]
pub struct CffStem {
    pub min: f32,
    pub max: f32,
    pub vertical: bool,
}

One stem hint of a CFF glyph: the two edges of a stroke that a hinter keeps a steady width.

Edges are in font units, as the charstring states them. An upright stem's edges are x positions, and a level stem's are y positions. In a variable CFF2 font they are blended at the location you asked Font::cff_hints for.

An edge hint marks a single edge and not a stroke, and CFF writes it as a stem with a width of -20 or -21. It keeps that width here, so its max is below its min: look for that before you treat the two as a range.

It is #[non_exhaustive] and laid out as C reads it: read its fields.

use daegun::outline::CffStem;
use daegun::{Location, Tag};

// Source Serif 4 is a variable CFF2 font, so its stems move with the weight.
let glyph = font.glyph_id('H').expect("the font maps H");
let left_upright = |at: &Location| -> Option<CffStem> {
    font.cff_hints(glyph, at)?.stems.into_iter().find(|stem| stem.vertical)
};

let regular = left_upright(&Location::default()).expect("the H has upright stems");
let black = left_upright(&font.location(&[(Tag::new(b"wght"), 900.0)])).expect("at weight 900 too");
// The left upright of the H is about 97 units wide at the default weight and 198 at weight 900.
assert!((regular.max - regular.min - 96.7).abs() < 0.1);
assert!((black.max - black.min - 198.0).abs() < 0.1);
min: f32
Where the stem starts: the lower edge of a level stem, or the left edge of an upright one.
max: f32
Where it ends: min plus the width the charstring gives. Above min for a stem, and 20 or 21 units below it for an edge hint.
vertical: bool
True for an upright stem, whose edges are x positions. False for a level stem, whose edges are y positions.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::FillRule
pub enum FillRule {
    NonZero,
    EvenOdd,
}

Which points a path fills: by the non-zero rule or by the even-odd rule.

The two agree on a plain shape and differ where contours overlap or nest. Count how many times the contours wind around a point, one direction as +1 and the other as -1. Non-zero fills the point where that count is not zero, and even-odd where it is odd.

Glyph outlines are made for non-zero. A font may overlap its contours freely, an embolden from Font::prepared_outline always does, and a stroke often does. Filled even-odd, those overlaps turn into holes.

You pass one to raster::Rasterizer::path, and each fill of a color::DisplayList carries one. The default is NonZero.

use daegun::outline::{FillRule, OutlinePen, Path};
use daegun::raster::Rasterizer;

// An 8 by 8 square with a 4 by 4 square inside it, both drawn the same way around.
let mut path = Path::new();
for (low, high) in [(0.0, 8.0), (2.0, 6.0)] {
    path.move_to(low, low);
    path.line_to(high, low);
    path.line_to(high, high);
    path.line_to(low, high);
    path.close();
}

let mut rasterizer = Rasterizer::new();
let mut covered = |rule: FillRule| -> daegun::Result<usize> {
    let image = rasterizer.path(&path, rule, None)?;
    Ok(image.pixels.iter().filter(|&&coverage| coverage == 255).count())
};
// Non-zero fills all 64 pixels. Even-odd leaves the 16 of the inner square empty.
assert_eq!(covered(FillRule::NonZero)?, 64);
assert_eq!(covered(FillRule::EvenOdd)?, 48);
NonZero
Fills the points that the contours wind around a number of times other than zero. How glyph outlines are filled, and the default.
EvenOdd
Fills the points that the contours wind around an odd number of times, so a contour inside another cuts a hole whichever way it runs.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::HintedOutline
pub struct HintedOutline(/* private */);

A glyph's outline as a hinter left it: its points in pixels, fitted to the pixel grid at one size.

Font::hinted_outline returns one. Where Font::prepared_outline draws a hinted glyph straight onto a pen, this keeps the points, so you can read them with HintedOutline::points and HintedOutline::contours, compare them with the unhinted outline, or draw them when you like with HintedOutline::draw.

Points are in pixels, y up, measured from the glyph's origin, each coordinate a multiple of 1/64 of a pixel. It lists the outline's points contour by contour, those on the curve and the controls between them alike. It holds only the glyph's own points, not the four phantom points TrueType hinting moves, so it carries no hinted advance.

It owns its points and borrows nothing from the font, so it can be kept, cloned and compared.

use daegun::outline::{HintMode, HintedOutline, Path};
use daegun::Location;

let glyph = font.glyph_id('o').expect("Inter maps o");
let hinted: HintedOutline = font
    .hinted_outline(glyph, &Location::default(), 16.0, HintMode::Auto)?
    .expect("the autohinter takes Inter's o");

// Two contours of 48 points in all: the outside of the o and its counter.
assert_eq!(hinted.contours().len(), 2);
assert_eq!(hinted.points().len(), 48);

let mut path = Path::new();
hinted.draw(&mut path);
// `path` is the o in pixels at 16 px, its bottom and its top on whole pixels.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::HintMode
#[non_exhaustive]
pub enum HintMode {
    None,
    Font,
    Auto,
    AutoForce,
}

Which hinter fits a glyph to the pixel grid, if any.

Hinting moves an outline's points at one pixel size so that its heights and level strokes land on whole pixels and small text stays even. Pass a mode to Font::hinted_outline, or set one with OutlineOptions::with_hinting for Font::prepared_outline. The default is HintMode::None.

daegun has three hinters. The bytecode hinter runs the TrueType programs a font carries. The CFF hinter applies the stem hints and alignment zones of a CFF or CFF2 font. The autohinter needs no hints from the font: it measures the font's Latin letters for the heights to align to, and fits any outline to them.

All three move points up and down and leave x where scaling put it, with one exception: bytecode moves x too in a font that declares native ClearType.

A mode never fails a call. Where the hinter it names doesn't take a glyph, Font::hinted_outline answers None and Font::prepared_outline draws the glyph unhinted. A glyph that a VARC table composes is never hinted, as it has no hints.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::outline::HintMode;
use daegun::Location;

// A test font with TrueType bytecode. Its B has instructions of its own, and its D has none.
let b = font.glyph_id('B').expect("the font maps B");
let d = font.glyph_id('D').expect("the font maps D");
let at = Location::default();

assert!(font.hinted_outline(b, &at, 16.0, HintMode::Font)?.is_some());
// The font's hints leave D alone. Auto keeps to them in a font that has programs.
assert!(font.hinted_outline(d, &at, 16.0, HintMode::Font)?.is_none());
assert!(font.hinted_outline(d, &at, 16.0, HintMode::Auto)?.is_none());
// The autohinter takes it all the same.
assert!(font.hinted_outline(d, &at, 16.0, HintMode::AutoForce)?.is_some());
None
No hinting: the outline as scaled. The default.
Font
The font's own hints: its TrueType bytecode, or the stem hints of a CFF or CFF2 font. Bytecode fits y to the pixel grid, and x only in a font that declares native ClearType (INSTCTRL selector 3); otherwise x stays as drawn. A glyph those hints leave where scaling put it stays unhinted, as a simple TrueType glyph with no instructions does in a font without native ClearType. A composite glyph whose components ask for their offsets rounded to the grid gets them rounded, and where that moves a component the glyph counts as hinted, even in a font with no programs.
Auto
The choice made for you, once for the whole font. A font with TrueType outlines, no font program (fpgm) and a CVT program (prep) of at most 7 bytes goes to the autohinter, every glyph of it. Any other font keeps its own hints, as Font uses them, and a glyph they don't hint stays unhinted: the autohinter doesn't step in glyph by glyph.
AutoForce
The autohinter for every glyph, whatever hints the font carries. It still leaves a glyph unhinted where it has nothing to work from: a glyph that draws nothing, or a font with too few of the Latin letters it measures.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::Join
#[non_exhaustive]
pub enum Join {
    Miter {
        limit: f32,
    },
    Round,
    Bevel,
}

How a stroke turns a corner: to a sharp point, rounded, or cut straight across.

The join shapes the outer side of every corner of a stroked path. Set one with StrokeStyle::with_join. A style from StrokeStyle::new has a miter with a limit of 4.

A stroke is flattened to lines as it is drawn, so a round join is a run of short lines, as many as the stroke's tolerance asks for. Through Font::prepared_outline that tolerance is a quarter of a pixel, so the round join of a thin stroke can come out as a single line, the same as a bevel.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::outline::{Join, OutlinePen, Path, StrokeStyle, Verb};

// A square 100 units a side.
let mut square = Path::new();
square.move_to(0.0, 0.0);
square.line_to(100.0, 0.0);
square.line_to(100.0, 100.0);
square.line_to(0.0, 100.0);
square.close();

let lines = |join: Join| -> daegun::Result<usize> {
    let mut stroked = Path::new();
    square.stroke(&StrokeStyle::new(20.0).with_join(join), 0.1, &mut stroked)?;
    Ok(stroked.segments().filter(|(verb, _)| *verb == Verb::Line).count())
};
// A bevel cuts each corner with one line. A miter runs out to the point, and an arc takes more lines.
assert!(lines(Join::Bevel)? < lines(Join::Miter { limit: 4.0 })?);
assert!(lines(Join::Miter { limit: 4.0 })? < lines(Join::Round)?);
// The point of a right angle reaches 1.41 half widths, so a limit of 1.4 bevels it.
assert_eq!(lines(Join::Miter { limit: 1.4 })?, lines(Join::Bevel)?);
Miter { limit: f32 }
The two outer edges run on until they meet in a point. Where that point would reach farther from the corner than limit times half the width, the corner is beveled instead.
limit: f32
How far the point may reach from the corner, in half widths. A limit of 0 or less, or NaN, means 4. A limit under 1 acts as 1, which bevels every corner. At 4, a corner sharper than about 29 degrees is beveled.
Round
An arc around the corner, half the width in radius.
Bevel
A straight cut across the corner, from the end of one outer edge to the start of the next.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::OutlineOptions
#[non_exhaustive]
pub struct OutlineOptions {
    pub transform: Option<[f32; 6]>,
    pub hinting: HintMode,
    pub stroke: Option<StrokeStyle>,
    pub embolden: Option<f32>,
    pub oblique: Option<f32>,
}

What Font::prepared_outline does to an outline on its way to the pen: hinting, an oblique, a transform, and a stroke or an embolden.

Start from OutlineOptions::DEFAULT, which changes nothing, and name what you want with the with_ methods, each of which returns the changed options. The type is #[non_exhaustive], so there is no struct literal for it, but its fields are public to read and to set. daegun's own rasterizer takes the same options, in raster::RasterOptions.

Order. Hinting comes first, on the glyph as the font drew it. Then the oblique leans it, then the transform moves it. A stroke or an embolden comes last, around the outline as it then stands. The transform is applied to the hinted points, so one that scales or turns the glyph takes them off the pixel grid again.

Units. Every length here is in font units, although the outline comes out in pixels: a stroke of 40 is 40 units wide at any size, which is 40.0 * px / f32::from(font.units_per_em()) pixels. The transform scales the outline alone, and neither a stroke, an embolden nor the advances.

Overlaps. An embolden's bands lie half over the glyph's own fill, and a stroke runs over itself where a corner is too tight for its width or two parts of the glyph lie closer than it is wide. A non-zero fill hides both. A rasterizer that sums the coverage of each contour counts those places twice, and needs the contours merged first: flatten the path with Path::flatten and pass the polygons to outline::resolve_overlaps, which answers None where there was nothing to merge.

use daegun::outline::{HintMode, OutlineOptions, Path};
use daegun::Location;

// A synthetic bold italic, hinted: 40 units heavier, and leaning by a quarter of its height.
let options = OutlineOptions::DEFAULT
    .with_hinting(HintMode::Auto)
    .with_embolden(40.0)
    .with_oblique(0.25);

let glyph = font.glyph_id('H').expect("Inter maps H");
let at = Location::default();
let mut path = Path::new();
let styled = font.prepared_outline(glyph, &at, 32.0, &options, &mut path)?;

let mut plain_path = Path::new();
let plain = font.prepared_outline(glyph, &at, 32.0, &OutlineOptions::DEFAULT, &mut plain_path)?;
// The embolden widened the advance by its 40 units, which is 0.625 pixels at 32 px in Inter.
assert_eq!(styled.advance_width - plain.advance_width, 0.625);
transform: Option<[f32; 6]>
A 2×3 transform [a, b, c, d, dx, dy] for the outline, applied after hinting and after the oblique: a point (x, y) moves to (a*x + c*y + dx, b*x + d*y + dy). The offsets dx and dy are in font units, hinted or not. It scales neither a stroke, an embolden nor the advances. None leaves the outline where it is.
hinting: HintMode
Which hinter fits the outline to the pixel grid, a HintMode. HintMode::None, the default, draws it as scaled.
stroke: Option<StrokeStyle>
A StrokeStyle to draw the glyph's contours as a stroke in place of filling them. Its width is in font units, and a width of 0 draws nothing. None fills the glyph.
embolden: Option<f32>
Extra stem width in font units, for a synthetic bold: every edge moves out by half of it, and the advances grow by all of it, the height only in a font with vertical metrics. Ignored when a stroke is set, which takes its place, and at zero or below.
oblique: Option<f32>
The tangent of a lean from upright, for a synthetic italic: each point moves right by this times its y, so 0.25 leans the glyph about 14 degrees to the right and a negative value leans it left. It is applied before the transform, so the glyph leans in its own frame.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::OutlinePen
pub trait OutlinePen {
    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 curve_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32);
    fn close(&mut self);
}

What an outline is drawn onto: five methods that receive a shape one contour at a time, as moves, lines, curves and closes.

Implement it for a rasterizer, an exporter or anything else of your own that takes outlines. Every call that draws one takes a pen: Font::outline, Font::prepared_outline, HintedOutline::draw, Path::replay and Path::stroke.

A contour starts with OutlinePen::move_to. Each OutlinePen::line_to, OutlinePen::quad_to and OutlinePen::curve_to adds a segment from the point the call before it ended on, and OutlinePen::close ends the contour. A shape of several contours, such as an o and its hole, sends that sequence once for each.

The numbers are f32, y up, in the units of whatever is drawing: font units from Font::outline, measured from the glyph's origin, and pixels from Font::prepared_outline and HintedOutline::draw.

Write all five. A TrueType outline arrives as lines and quadratic curves and a CFF or CFF2 outline as lines and cubic curves, and a pen can't know which font it will meet. A font that keeps cubic curves in its glyf table, as a draft extension of the format allows, can send both kinds in one glyph. If your rasterizer takes one kind of segment only, draw into a QuadraticPen for quadratic curves alone, or into a Path and call Path::flatten for straight edges.

Four types are pens already. Path records the calls, QuadraticPen collects them as quadratic curves, TransformPen passes them to another pen through a transform, and a &mut reference to a pen is a pen too. To call the methods yourself, on a Path say, bring the trait into scope with use daegun::outline::OutlinePen;.

use daegun::outline::OutlinePen;
use daegun::Location;
use std::fmt::Write;

// A pen that writes what it is given as SVG path data.
struct Svg(String);

impl OutlinePen for Svg {
    fn move_to(&mut self, x: f32, y: f32) {
        let _ = write!(self.0, "M{x} {y}");
    }
    fn line_to(&mut self, x: f32, y: f32) {
        let _ = write!(self.0, "L{x} {y}");
    }
    fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
        let _ = write!(self.0, "Q{cx} {cy} {x} {y}");
    }
    fn curve_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) {
        let _ = write!(self.0, "C{c1x} {c1y} {c2x} {c2y} {x} {y}");
    }
    fn close(&mut self) {
        self.0.push('Z');
    }
}

let glyph = font.glyph_id('l').expect("Inter maps l");
let mut svg = Svg(String::new());
font.outline(glyph, &Location::default(), &mut svg)?;
// Inter's l is one rectangle, in font units with y up.
assert_eq!(svg.0, "M338 1490L338 0L158 0L158 1490Z");
outline::Path
pub struct Path {
    /* private fields */
}

An outline you can keep: a pen that records what is drawn into it as a list of verbs and a list of points.

Make one with Path::new and pass &mut path wherever a pen goes, such as Font::outline for a glyph in font units or Font::prepared_outline for one in pixels. Or build a shape by hand with the OutlinePen methods, which need use daegun::outline::OutlinePen; in scope.

Then read it back with Path::segments, draw it onto another pen with Path::replay, measure it with Path::bounds, or turn it into something else: Path::flatten gives polygons, and Path::stroke the outline of its stroke.

A path holds its points in whatever units they were drawn in, and checks nothing as it records. A coordinate that is not finite goes in as it is, and it is Path::flatten or Path::stroke that refuses it later.

Drawing appends. A path that already holds a glyph gains the next one after it, so call Path::clear between glyphs when you reuse one. Two paths are equal when their verbs and points are.

use daegun::outline::{Path, Verb};
use daegun::Location;

let glyph = font.glyph_id('o').expect("Inter maps o");
let mut path = Path::new();
font.outline(glyph, &Location::default(), &mut path)?;

// Inter's o is two contours, the bowl and the hole in it, of 12 quadratic curves each.
let contours = path.segments().filter(|(verb, _)| *verb == Verb::Move).count();
let curves = path.segments().filter(|(verb, _)| *verb == Verb::Quad).count();
assert_eq!((contours, curves), (2, 24));

// In font units, y up from the baseline: the o is 1020 units wide.
let bounds = path.bounds().expect("the o has points");
assert_eq!(bounds.x_max - bounds.x_min, 1020.0);
impl OutlinePen
Appends each call as it comes: move_to as Verb::Move with its point, line_to as Verb::Line with its end, quad_to as Verb::Quad with its control and its end, curve_to as Verb::Cubic with both controls and its end, and close as Verb::Close with no point.
  • Implements: Clone, Debug, Default, OutlinePen, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::PathView
pub struct PathView<'a> {
    /* private fields */
}

A path borrowed from where it is kept: the same verbs and points as a Path, as two slices.

You get one from Path::view, and from the scene of a color glyph, which keeps all its outlines in one buffer and lends each through DisplayList::path and DisplayList::paths. A view is Copy, and it can't outlive the path or scene it borrows from.

Read it with PathView::segments or PathView::parts, measure it with PathView::bounds and draw it onto a pen with PathView::replay. For a path of your own to keep, flatten or stroke, call PathView::to_path.

use daegun::color::SceneOptions;
use daegun::outline::PathView;
use daegun::{GlyphId, Location};

// A color glyph's scene keeps every outline it uses and lends each one as a view.
let scene = font.color_scene(GlyphId(9), &Location::default(), &SceneOptions::default())?;
let scene = scene.expect("glyph 9 of this font is a color glyph");
for view in scene.paths() {
    let view: PathView = view;
    // Read it, measure it or replay it onto a pen, as you would a Path.
}
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::Point
pub struct Point {
    pub x: f32,
    pub y: f32,
}

A point of an outline: x across and y up, as two f32s.

It is in the units its outline was drawn in: font units for a path from Font::outline, pixels for one from Font::prepared_outline. Path::parts, Path::flatten and Quad all give points.

A plain value of eight bytes, laid out as C reads it. Build one by literal, Point { x, y }, or from a pair.

use daegun::outline::{Path, Point};
use daegun::Location;

let glyph = font.glyph_id('l').expect("Inter maps l");
let mut path = Path::new();
font.outline(glyph, &Location::default(), &mut path)?;

// The first point of Inter's l, in font units: its top right corner.
let Point { x, y } = path.parts().1[0];
assert_eq!((x, y), (338.0, 1490.0));

// To a pair and back.
let pair: (f32, f32) = Point { x, y }.into();
assert_eq!(Point::from(pair), Point { x: 338.0, y: 1490.0 });
x: f32
Across. A larger value is further right.
y: f32
Up. A larger value is higher, the opposite of the y on most screens.
impl From<(f32, f32)>
A point from an (x, y) pair.
impl From<Point> for (f32, f32)
The point as an (x, y) pair.
  • Implements: Clone, Copy, Debug, Default, From<(f32, f32)>, From<Point> for (f32, f32), PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::PointKind
pub enum PointKind {
    OnCurve,
    Quadratic,
    Cubic,
}

What a point of a hinted outline is: on the curve, or a control point of a quadratic or a cubic curve.

HintedOutline::points pairs every point with one. A hinted outline is a list of points for each contour, not a list of pen calls, and the kind says what role a point plays in its contour.

To draw a hinted outline you need not read the kinds at all: HintedOutline::draw turns the points into pen calls. The set is closed, so a match needs no _ arm.

use daegun::outline::{HintMode, PointKind};
use daegun::Location;

let glyph = font.glyph_id('o').expect("Inter maps o");
let hinted = font.hinted_outline(glyph, &Location::default(), 16.0, HintMode::Auto)?;
let hinted = hinted.expect("a hinter takes this glyph");

let (mut on_curve, mut controls) = (0, 0);
for (point, kind) in hinted.points() {
    match kind {
        PointKind::OnCurve => on_curve += 1,
        PointKind::Quadratic => controls += 1,
        PointKind::Cubic => unreachable!("Inter is a TrueType font"),
    }
}
// Inter's o: 24 points on the curve and 24 quadratic control points.
assert_eq!((on_curve, controls), (24, 24));
OnCurve
The outline passes through the point. Lines and curves start and end on these, or on a point TrueType implies between two quadratic controls in a row.
Quadratic
The control point of a quadratic curve, as the outlines of a TrueType font have. Two in a row imply an on-curve point halfway between them, which is not listed.
Cubic
One of the two control points of a cubic curve, as the outlines of a CFF font have.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::PreparedGlyph
#[non_exhaustive]
pub struct PreparedGlyph {
    pub advance_width: f32,
    pub advance_height: f32,
    pub hinted: bool,
}

What Font::prepared_outline returns: the glyph's advances in pixels, and whether a hinter ran.

The advances are the font's own at the location, scaled to the size and not rounded, hinted or not. An embolden adds its amount to them, and the transform in the options doesn't touch them.

They are the glyph's own advances, with no kerning in them. For shaped text, step by ShapedRun::advances instead, scaled to pixels.

It is #[non_exhaustive] and laid out as C reads it: read its fields. PreparedGlyph::default() is a zeroed one.

use daegun::outline::{OutlineOptions, Path, PreparedGlyph};
use daegun::{Location, Orientation};

let glyph = font.glyph_id('a').expect("Inter maps a");
let at = Location::default();
let mut path = Path::new();
let prepared: PreparedGlyph = font.prepared_outline(glyph, &at, 16.0, &OutlineOptions::DEFAULT, &mut path)?;

// The advance is the font's, 1150 units for Inter's a, scaled to 16 px.
let units = font.advance(glyph, &at, Orientation::Horizontal);
assert_eq!(units, 1150.0);
assert_eq!(f64::from(prepared.advance_width), units * 16.0 / f64::from(font.units_per_em()));
// Inter has no vertical metrics, and no hinting was asked for.
assert_eq!(prepared.advance_height, 0.0);
assert!(!prepared.hinted);
advance_width: f32
How far the pen moves across after the glyph in horizontal text, in pixels.
advance_height: f32
How far the pen moves down after the glyph in vertical text, in pixels. It is 0 in a font without vertical metrics, where Font::advance answers with the height of the font's line instead.
hinted: bool
Whether a hinter took the glyph. False with HintMode::None, and false where hinting was asked for but no hinter took this glyph, which was then drawn unhinted.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::Quad
pub struct Quad {
    pub start: Point,
    pub control: Point,
    pub end: Point,
}

One quadratic curve: where it starts, the control point it bends toward, and where it ends.

Font::quads and QuadraticPen::finish return lists of these, for a rasterizer that works curves out in a GPU shader and wants a single kind of segment. A straight line is a Quad too, with its control point halfway between its ends.

The point at t, from 0 at the start to 1 at the end, is (1 - t)² * start + 2 * (1 - t) * t * control + t² * end.

A plain value laid out as C reads it: three Points, which is six f32s and 24 bytes, so a slice of them can go into a buffer as it is. The points are in the units the outline was drawn in, y up.

use daegun::outline::Quad;
use daegun::Location;

let glyph = font.glyph_id('l').expect("Inter maps l");
let curves: Vec<Quad> = font.quads(glyph, &Location::default())?;
// Inter's l is four straight sides, so four curves, each with its control halfway along.
assert_eq!(curves.len(), 4);
let Quad { start, control, end } = curves[0];
assert_eq!((start.y, control.y, end.y), (1490.0, 745.0, 0.0));

// The point at t on the curve, here halfway.
let t = 0.5;
let u = 1.0 - t;
let y = u * u * start.y + 2.0 * u * t * control.y + t * t * end.y;
assert_eq!(y, 745.0);
start: Point
Where the curve starts.
control: Point
The control point. The curve leaves start heading for it and arrives at end coming from it, without passing through it. For a straight line it is the midpoint of the two.
end: Point
Where the curve ends. In a list as QuadraticPen::finish returns it, the next curve of the same contour starts here.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::QuadraticPen
pub struct QuadraticPen {
    /* private fields */
}

A pen that collects whatever is drawn into it as quadratic curves and nothing else.

For a rasterizer that works curves out in a GPU shader and wants a single kind of segment. Draw an outline into it, then call QuadraticPen::finish for the list of Quads. Font::quads does this for a glyph and then winds the result with normalize_winding. Use the pen yourself for a path of your own, for an outline drawn through a TransformPen, or for a different tolerance.

A quadratic curve is kept as it is. A line becomes a curve with its control point at the midpoint. A cubic curve is cut in half, and each half again, until the quadratic curve that stands for each piece lies within the pen's tolerance of it, measured at the piece's quarter points. The cutting stops at 256 pieces for one cubic, past which f32 cannot place the pieces any closer.

Every contour comes out closed. A close, the next move_to or QuadraticPen::finish adds a line back to the contour's start if the pen is not there already. The curves stay in the units they were drawn in, y up, in the order and the direction they were drawn.

use daegun::outline::QuadraticPen;
use daegun::Location;

// Source Serif 4 has CFF2 outlines, so its glyphs are drawn with cubic curves.
let glyph = font.glyph_id('o').expect("the font maps o");
let mut pen = QuadraticPen::new(f32::from(font.units_per_em()) / 4096.0);
font.outline(glyph, &Location::default(), &mut pen)?;
let curves = pen.finish()?;

// The 8 cubic curves of its o became 24 quadratic ones.
assert_eq!(curves.len(), 24);
impl OutlinePen
Turns each call into curves in its list: quad_to adds the curve as given, line_to a curve with its control at the midpoint, and curve_to the quadratic curves that stand for the cubic. move_to and close first close the contour before them with a line back to its start, if it is open.
  • Implements: Debug, OutlinePen.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::StrokeStyle
#[non_exhaustive]
pub struct StrokeStyle {
    pub width: f32,
    pub join: Join,
    pub cap: Cap,
}

How a path is stroked: how wide, and how the stroke turns corners and ends.

Build one with StrokeStyle::new and change the join or the cap with StrokeStyle::with_join and StrokeStyle::with_cap. Pass it to OutlineOptions::with_stroke to draw a glyph as a stroke, or to Path::stroke to stroke a path of your own.

The width is in the units of whatever is stroked. For a glyph through Font::prepared_outline that is font units, so a stroke keeps its weight against the glyph at every size.

StrokeStyle::default() is StrokeStyle::new(1.0). The type is #[non_exhaustive], so there is no struct literal for it, but its fields are public to read and to set.

use daegun::outline::{Join, OutlineOptions, Path, StrokeStyle};
use daegun::Location;

// 60 font units wide, with round corners.
let style = StrokeStyle::new(60.0).with_join(Join::Round);
assert_eq!(style.width, 60.0);

let glyph = font.glyph_id('H').expect("Inter maps H");
let options = OutlineOptions::DEFAULT.with_stroke(style);
let mut path = Path::new();
font.prepared_outline(glyph, &Location::default(), 32.0, &options, &mut path)?;

// The stroke lies half its width to either side of the H's edges: 30 units, 0.46875 pixels at
// 32 px. The left edge of the H is 2.8125 pixels in, so the stroke begins 0.46875 before it.
let bounds = path.bounds().expect("the stroke has ink");
assert_eq!(bounds.x_min, 2.8125 - 0.46875);
width: f32
The stroke's whole width, half of it to either side of the path, in the path's units. Its sign is ignored, and a width of 0 draws nothing. One that is not finite fails the call that strokes with it, with ErrorKind::InvalidArgument.
join: Join
How the stroke turns corners, a Join. A miter with a limit of 4 unless you set another.
cap: Cap
How the stroke ends a contour that is not closed, a Cap. Cap::Butt unless you set another.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
outline::TransformPen
pub struct TransformPen<'a, P: OutlinePen + ?Sized> {
    /* private fields */
}

A pen that passes everything drawn into it on to another pen, with every point moved through a transform.

The transform is 2 by 3, [a, b, c, d, dx, dy], and sends a point (x, y) to (a * x + c * y + dx, b * x + d * y + dy). Control points go through it like any other, so curves stay curves. It is worked out in f64, and the inner pen gets f32.

Use it to scale, move, turn or shear an outline as it is drawn, without recording it first: put one over your pen and hand it to Font::outline to get a glyph at your own size and place. Path::replay with a transform does the same for a recorded path.

It borrows the inner pen for as long as it lives. The inner pen can be of a type known at compile time, whose methods are then called directly, or a dyn OutlinePen.

Nothing is checked. A result too large for f32 reaches the inner pen as infinity, so keep the transform and the outline in a range that fits.

use daegun::outline::{Path, TransformPen};
use daegun::Location;

let glyph = font.glyph_id('l').expect("Inter maps l");
// Font units to pixels at 16 px to the em, applied as the glyph is drawn.
let scale = 16.0 / f64::from(font.units_per_em());
let mut pixels = Path::new();
let mut scaled = TransformPen::new(&mut pixels, [scale, 0.0, 0.0, scale, 0.0, 0.0]);
font.outline(glyph, &Location::default(), &mut scaled)?;

// `pixels` holds the l at 16 px, about 11.6 pixels tall.
let bounds = pixels.bounds().expect("the l has points");
assert_eq!((bounds.y_min, bounds.y_max), (0.0, 11.640625));
impl OutlinePen
Moves the points of each call through the transform and makes the same call on the inner pen. close is passed on as it is.
  • Implements: Debug, OutlinePen.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin.
outline::Verb
pub enum Verb {
    Move = 0,
    Line = 1,
    Quad = 2,
    Cubic = 3,
    Close = 4,
}

One step of a path: what to draw, and so how many points it takes from the list.

A Path is a list of verbs and a list of points. Each verb takes its points from the front of what is left of the point list, and Path::segments pairs them up for you.

A verb is one byte with a fixed value, 0 to 4 in the order below, so verb as u8 is safe to hand to C or to store. The set is closed, so a match needs no _ arm.

use daegun::outline::{Path, Verb};
use daegun::Location;

let glyph = font.glyph_id('A').expect("Inter maps A");
let mut path = Path::new();
font.outline(glyph, &Location::default(), &mut path)?;

// How many points each verb takes from the list.
let takes = |verb: Verb| match verb {
    Verb::Move | Verb::Line => 1,
    Verb::Quad => 2,
    Verb::Cubic => 3,
    Verb::Close => 0,
};
let (verbs, points) = path.parts();
assert_eq!(verbs.iter().map(|&verb| takes(verb)).sum::<usize>(), points.len());

// One byte each, with a fixed value.
assert_eq!(Verb::Close as u8, 4);
Move = 0
Starts a new contour. Takes one point, where the contour begins.
Line = 1
A straight line from the current point. Takes one point, its end.
Quad = 2
A quadratic curve from the current point. Takes two points: its control, then its end.
Cubic = 3
A cubic curve from the current point. Takes three points: its two controls, then its end.
Close = 4
Ends the contour with a straight line back to its start. Takes no point.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Color

Color glyphs: bitmap strikes, COLR layers and palettes, paint graphs and the scenes made from them, and the color math to sample a gradient and composite a layer. The calls are on Font, and the rest is in daegun::color.

color::BitmapImage
#[non_exhaustive]
pub enum BitmapImage<'a> {
    Png(&'a [u8]),
    Coverage {
        width: u16,
        height: u16,
        pixels: Vec<u8>,
    },
}

The picture of a bitmap glyph: the PNG file the font stores, or decoded coverage at one byte a pixel.

It is the image of the GlyphBitmap that Font::bitmap returns. Which variant you get depends on how the font stores the glyph. A strike that stores PNG files gives Png: that is sbix, and CBDT as color emoji fonts use it. A strike that stores raw bits gives Coverage: those are the black-and-white and gray images of 1, 2, 4 or 8 bits a pixel, as EBDT and bdat hold them.

There is no variant of decoded color pixels. daegun does not decode PNG files, so the pixels of a color glyph always reach you as the PNG itself. A raw color image of 32 bits a pixel is not decoded either: that strike is passed over for the next nearest one.

sbix can hold pictures in other formats too, such as JPEG or TIFF. daegun returns PNG pictures only: a strike that holds the glyph in another format is passed over for the next nearest one.

The enum is #[non_exhaustive], so a match needs a _ arm.

use daegun::color::BitmapImage;
use daegun::GlyphId;

// A glyph of a font with an sbix table.
let bitmap = font.bitmap(GlyphId(19), 64).expect("a bitmap glyph");
match &bitmap.image {
    BitmapImage::Png(png) => {
        // A whole PNG file, lent from the font. Decode it with a PNG library.
        assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
    }
    BitmapImage::Coverage { width, height, pixels } => {
        // One byte a pixel, rows from the top: use each byte as the alpha of the text's color.
        assert_eq!(pixels.len(), usize::from(*width) * usize::from(*height));
    }
    // BitmapImage is #[non_exhaustive]: a later release may add a format.
    _ => {}
}
Png(&'a [u8])
A whole PNG file, as the font stores it, lent from the font's bytes. Decode it with a PNG library: its size, and whether its pixels are color, gray or carry alpha, are what its own header says. An sbix picture has been checked to open with a PNG header, and a CBDT one is handed over unchecked.
Coverage { width: u16, height: u16, pixels: Vec<u8> }
A black-and-white or gray picture, decoded into one byte a pixel. It is coverage, not color: how much of each pixel the glyph covers, to use as the alpha of the text's color. A glyph the font assembles from other glyphs' bitmaps comes already put together.
width: u16
The width of the picture in pixels, which is the length of a row.
height: u16
The height of the picture in pixels, which is the number of rows.
pixels: Vec<u8>
width * height bytes, row after row from the top, each row from left to right. 0 is empty and 255 is fully covered. A 1-bit strike gives only those two values, and a 2-bit or 4-bit strike gives its gray levels spread evenly from 0 to 255.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Blend
#[non_exhaustive]
pub enum Blend {
    Clear,
    Src,
    Dest,
    SrcOver,
    DestOver,
    SrcIn,
    DestIn,
    SrcOut,
    DestOut,
    SrcAtop,
    DestAtop,
    Xor,
    Plus,
    Screen,
    Overlay,
    Darken,
    Lighten,
    ColorDodge,
    ColorBurn,
    HardLight,
    SoftLight,
    Difference,
    Exclusion,
    Multiply,
    HslHue,
    HslSaturation,
    HslColor,
    HslLuminosity,
}

How a layer is combined with what is already drawn under it: one of the 28 composite modes of COLR.

You meet one in a scene as the blend of an Op::PushLayer, and in a paint graph as the mode of a PaintNode::Composite. When the layer is popped, each of its pixels, the source, is combined with the pixel under it, the backdrop. Blend::composite does that for one pixel.

The first thirteen, Clear to Plus, are the Porter-Duff operators. They mix no colors: they only decide, from the two alphas, how much of the source and how much of the backdrop is kept. The other fifteen, from Screen on, are the blend modes of the W3C Compositing and Blending specification. Those work out a new color from the two where they overlap, then lay it on as SrcOver does.

The variants are declared in COLR's own order, so Blend::from_colr maps the numbers 0 to 27 onto them. SrcOver is the default. The enum is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::color::{Blend, Op, SceneOptions};
use daegun::{GlyphId, Location};

// Glyph 133 of the COLR test font composites one shape onto another with Screen.
let scene = font.color_scene(GlyphId(133), &Location::default(), &SceneOptions::DEFAULT)?
    .expect("a color glyph");
let modes: Vec<Blend> = scene.ops().iter().filter_map(|op| match op {
    Op::PushLayer { blend, .. } => Some(*blend),
    _ => None,
}).collect();
// Two layers: the backdrop's, drawn the ordinary way, and inside it the source's.
assert_eq!(modes, [Blend::SrcOver, Blend::Screen]);

// Popping the inner layer puts each of its pixels onto the pixel under it.
let (source, backdrop) = ([0.5, 0.5, 1.0], [0.2, 0.4, 0.6]);
let pixel = Blend::Screen.composite(source, 1.0, backdrop, 1.0);
// Screen only lightens: no channel ends up below what either color had.
assert!((0..3).all(|i| pixel.color[i] >= source[i].max(backdrop[i])));
Clear
Nothing is kept: the result is transparent, whatever the source and the backdrop held.
Src
Only the source is kept. The backdrop is erased, even where the source is transparent.
Dest
Only the backdrop is kept, as if the source had never been drawn.
SrcOver
The source is drawn on top of the backdrop, which shows through wherever the source is transparent. The ordinary way to stack layers, and the default.
DestOver
The backdrop stays on top, and the source shows only where the backdrop is transparent: the source is slipped in underneath.
SrcIn
The source is kept only where the backdrop has something drawn, and the backdrop itself is dropped. The backdrop works as a mask for the source.
DestIn
The backdrop is kept only where the source has something drawn, and the source itself is dropped. The source works as a mask for the backdrop.
SrcOut
The source is kept only where the backdrop is empty, and the backdrop is dropped.
DestOut
The backdrop is kept only where the source is empty, and the source is dropped: the source cuts a hole in the backdrop.
SrcAtop
The source is drawn over the backdrop, but only where the backdrop has something drawn. The rest of the backdrop is kept, and the rest of the source is dropped.
DestAtop
The backdrop is drawn over the source, but only where the source has something drawn. The rest of the source is kept, and the rest of the backdrop is dropped.
Xor
Each is kept where the other is empty. Where an opaque source meets an opaque backdrop, nothing is left.
Plus
The two are added, color and alpha alike, and capped at 1. Where they overlap the result is lighter.
Screen
Lightens. The two colors are inverted, multiplied, and the result inverted again, like two slides projected onto one screen. Black changes nothing, and white gives white.
Overlay
Multiplies where the backdrop is dark and screens where it is light, so the backdrop keeps its shadows and highlights.
Darken
The darker of the two, channel by channel.
Lighten
The lighter of the two, channel by channel.
ColorDodge
Brightens the backdrop by the source: the lighter the source, the stronger the effect. A black source changes nothing.
ColorBurn
Darkens the backdrop by the source: the darker the source, the stronger the effect. A white source changes nothing.
HardLight
Multiplies where the source is dark and screens where it is light, like a harsh spotlight on the backdrop.
SoftLight
A gentler HardLight: it darkens the backdrop a little where the source is dark and lightens it a little where the source is light. A mid-gray source changes nothing.
Difference
The darker of the two taken from the lighter, channel by channel. A black source changes nothing, and a white one inverts the backdrop.
Exclusion
Like Difference with less contrast. A black source changes nothing, a white one inverts the backdrop, and a mid-gray one gives mid-gray.
Multiply
Darkens. Each channel is the two multiplied, like two inks printed one over the other. White changes nothing, and black gives black.
HslHue
The source's hue, with the saturation and the luminosity of the backdrop.
HslSaturation
The source's saturation, with the hue and the luminosity of the backdrop.
HslColor
The source's hue and saturation, with the luminosity of the backdrop: it tints the backdrop and keeps its light and dark.
HslLuminosity
The source's luminosity, with the hue and the saturation of the backdrop.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Center
pub struct Center {
    pub x: f64,
    pub y: f64,
}

The point a scaling, rotating or skewing paint keeps fixed, in font units, y up.

PaintNode::Scale, PaintNode::ScaleUniform, PaintNode::Rotate and PaintNode::Skew each carry an optional one. None means the origin, the glyph's (0, 0). A transform about a center is the same as moving the center to the origin, transforming, and moving it back.

It is a plain value: build one from its two fields. Center::default() is the origin.

use daegun::color::{concat, Center, PaintNode};
use daegun::{GlyphId, Location};

let graph = font.paint_graph(GlyphId(84), &Location::default(), 0).expect("a COLR version 1 glyph");
// The first paint under this root is scaled about the middle of the font's em square.
let scaled = graph.root().children().next().expect("a paint").node();
let PaintNode::Scale { sx, sy, center } = scaled else { panic!("not a scale") };
assert_eq!(center, Some(Center { x: 500.0, y: 500.0 }));

// The matrix for it: move the center to the origin, scale, and move it back.
let c = center.unwrap_or_default();
let to_origin = [1.0, 0.0, 0.0, 1.0, -c.x, -c.y];
let back = [1.0, 0.0, 0.0, 1.0, c.x, c.y];
let matrix = concat(&concat(&to_origin, &[sx, 0.0, 0.0, sy, 0.0, 0.0]), &back);
assert_eq!(matrix, [0.5, 0.0, 0.0, 1.5, 250.0, -250.0]);
x: f64
Across, in font units. A larger value is further right.
y: f64
Up, in font units. A larger value is higher.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::ClipShape
#[non_exhaustive]
pub struct ClipShape {
    pub path: PathId,
    pub rule: FillRule,
    pub transform: [f64; 6],
}

One shape of a clip: a path of the scene, the rule it fills by and the transform that places it.

An Op::PushClip names a run of these, and DisplayList::shapes reads them. The clip is the area the shapes cover together, so a point inside any one of them is inside the clip.

In a scene from Font::color_scene every clip has exactly one shape: the outline of a glyph, or the rectangle of a clip box.

It is #[non_exhaustive] and has no constructor, so code outside daegun cannot write one from nothing. To put a clip in a list you build, copy a shape out of a scene and set its fields, which are public. DisplayList::push_shapes shows how.

use daegun::color::{ClipShape, Op, SceneOptions};
use daegun::{GlyphId, Location};

let options = SceneOptions::DEFAULT;
let scene = font.color_scene(GlyphId(8), &Location::default(), &options)?.expect("a color glyph");
// This glyph has a clip box, so its scene opens with a clip to it.
let Op::PushClip { shapes } = scene.ops()[0] else { panic!("the scene opens with a clip") };
for &ClipShape { path, rule, transform, .. } in scene.shapes(shapes) {
    let outline = scene.path(path).expect("a shape names a path of its scene");
    // Add `outline`, placed by `transform` and filled by `rule`, to the clip.
}
path: PathId
The id of the path that outlines the shape. DisplayList::path reads it.
rule: FillRule
Which points count as inside the path. FillRule::NonZero in every scene Font::color_scene makes.
transform: [f64; 6]
Where the path is placed: a Matrix [a, b, c, d, e, f] that takes the path's points into the scene's space, x' = a·x + c·y + e and y' = b·x + d·y + f.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::ColorStop
#[non_exhaustive]
pub struct ColorStop {
    pub offset:     f64,
    pub color:      Rgba,
    pub foreground: bool,
}

One stop of a gradient as a COLR paint graph holds it: an offset, a palette color and whether it takes the text's color.

This is a stop before a scene is made of it. You meet it in the stops of a gradient paint, such as PaintNode::LinearGradient, when you walk a PaintGraph. The palette has been applied already, so color is a real color. Two things that a Stop has settled are still open here: the offset may lie outside 0 to 1, and the stop may ask for the text's color.

To draw one, take color as it is unless foreground is set. If it is, take the text's color and multiply its alpha by color.a over 255, which Rgba::fade does. Font::color_scene and color::lower do the same with the foreground you give them.

It is #[non_exhaustive] and has no constructor, so you can't build one from nothing: stops come out of a font's graph. The fields of a copy can be changed, which is how a graph built by hand gets stops of its own.

use daegun::color::{ColorStop, PaintNode, Rgba, Stop};
use daegun::{GlyphId, Location};

let graph = font.paint_graph(GlyphId(149), &Location::default(), 0).expect("a COLR v1 glyph");
let text = Rgba::opaque(200, 0, 0);
// What a stop is drawn as: its own color, or the text's at the stop's alpha.
let drawn = |stop: &ColorStop| Stop {
    offset: stop.offset as f32,
    color: if stop.foreground { text.fade(f64::from(stop.color.a) / 255.0) } else { stop.color },
};

// In glyph 149 of the COLR test font, the paint under the root is a linear gradient.
let fill = graph.root().children().next().expect("a paint under the root");
if let PaintNode::LinearGradient { stops, .. } = fill.node() {
    // Its middle stop asks for the text's color, at an alpha of 76.
    assert!(stops[1].foreground && stops[1].color.a == 76);
    let stops: Vec<Stop> = stops.iter().map(drawn).collect();
    assert_eq!(stops[1], Stop { offset: 0.5, color: Rgba { r: 200, g: 0, b: 0, a: 76 } });
}
offset: f64
Where along the color line the stop sits: 0 at its start and 1 at its end. A font may place stops below 0 or above 1.
color: Rgba
The stop's color from the palette, its alpha already multiplied by the stop's own. For a foreground stop it is black at that alpha, there to carry the alpha alone.
foreground: bool
True if the stop takes the text's color in place of color, with the alpha of color applied to it.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::ColrLayer
#[non_exhaustive]
pub struct ColrLayer {
    pub glyph: GlyphId,
    pub color: Rgba,
    pub foreground: bool,
}

One layer of a COLR version 0 color glyph: a glyph's outline and the one color to fill it with.

COLR version 0 is the plain color format. A color glyph is a stack of ordinary glyphs, each filled with one flat color. Font::colr_layers returns the stack for a glyph in the palette you name, back to front, so draw the layers in order and each lands over the one before.

To draw a layer, take the outline of glyph with Font::outline and fill it by the nonzero rule with color, or with the color of the text when foreground is true. Every layer is drawn at the color glyph's own origin, with no offset. Font::color_scene does all this for you and gives the same fills as a DisplayList.

It is #[non_exhaustive]: read its fields, and get one from Font::colr_layers rather than building it.

use daegun::color::{ColrLayer, Rgba};
use daegun::outline::Path;
use daegun::Location;

let glyph = font.glyph_id('D').expect("the font has a D");
let layers: Vec<ColrLayer> = font.colr_layers(glyph, 0).expect("a COLR version 0 glyph");

for layer in &layers {
    let mut outline = Path::default();
    font.outline(layer.glyph, &Location::default(), &mut outline)?;
    // Fill `outline` with layer.color, or with the text's color where layer.foreground is true.
}
// Bungee Tint draws its D in two layers: the letter in dark red, then an inline in a lighter red.
assert_eq!(layers.len(), 2);
assert_eq!(layers[0].color, Rgba::opaque(201, 9, 0));
assert_eq!(layers[1].color, Rgba::opaque(255, 149, 128));
glyph: GlyphId
The glyph whose outline this layer fills. It is an ordinary glyph of the font, whose outline Font::outline draws.
color: Rgba
The fill color from the palette, as straight (not premultiplied) sRGB. When foreground is true the palette has no say: this is opaque black as a stand-in, and you fill with the text's color.
foreground: bool
True when the font asks for the color of the text here, in place of a palette entry. Fill the layer with whatever color the text is drawn in. Font::color_scene takes that color from SceneOptions::foreground.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::DisplayList
pub struct DisplayList {
    /* private fields */
}

A scene to draw: ops in drawing order, together with the paths, clip shapes and gradients those ops name.

Font::color_scene returns a color glyph as one. To draw it, go through DisplayList::ops in order and do what each Op says: fill a path, start or end a clip, start or end a layer. The ops hold no geometry themselves. A fill names its path by PathId and its gradient by GradientId, a clip names its shapes by a range, and the list hands each back through DisplayList::path, DisplayList::gradient and DisplayList::shapes.

A scene made from a color glyph is in font units, y up. One path can serve many ops, each placing it with a transform of its own.

You can build one too. DisplayList::default() is empty, DisplayList::push_path, DisplayList::push_gradient and DisplayList::push_shapes add what ops will name and return the ids, and DisplayList::push adds the ops. color::lower fills one from a paint graph. A list you build is in whatever units you put into it.

Two lists are equal when they hold the same paths in the same order and their ops draw the same things. A fill is compared by the gradient it names, not by the id, and a clip by its shapes. Debug prints a list the same way, each op with what it names written out.

The paths lie end to end in buffers they share, as do the clip shapes and the gradient stops, so a scene costs a handful of allocations however much it holds.

use daegun::color::{DisplayList, Op, Paint, SceneOptions};
use daegun::Location;

let a = font.glyph_id('A').expect("Bungee Tint has an A");
let scene: DisplayList =
    font.color_scene(a, &Location::default(), &SceneOptions::DEFAULT)?.expect("a color glyph");

// Bungee Tint's A is two outlines, each filled with one color.
assert_eq!(scene.paths().len(), 2);
for op in scene.ops() {
    let Op::Fill { path, paint: Paint::Solid(color), transform, .. } = *op else {
        panic!("this glyph is solid fills only")
    };
    let outline = scene.path(path).expect("a fill names a path of its scene");
    // Fill `outline`, placed by `transform`, with `color`.
}
impl Drop
With the std feature, a dropped list whose buffers take no more than 64 KiB is emptied and its buffers are kept for the thread: the next scene Font::color_scene makes on that thread starts with them. One list's buffers are kept at a time, a larger list frees its memory as usual, and release_thread lets go of the kept ones.
  • Implements: Clone, Debug, Default, Drop, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Extend
#[non_exhaustive]
pub enum Extend {
    Pad,
    Reflect,
    Repeat,
}

What a gradient paints before its first stop and after its last.

Every point of a gradient has an offset: 0 where the gradient starts, 1 where it ends. The shape being filled usually reaches further, to offsets below 0 and above 1, and this says what is painted there.

Pad is the default. The enum is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::color::gradient::Ramp;
use daegun::color::{Extend, Gradient, GradientKind, Rgba, Stop, IDENTITY};

let (red, blue) = (Rgba::opaque(255, 0, 0), Rgba::opaque(0, 0, 255));
let stops = [Stop { offset: 0.0, color: red }, Stop { offset: 1.0, color: blue }];
// Red at x = 0 to blue at x = 100.
let line = GradientKind::Linear { x0: 0.0, y0: 0.0, x1: 100.0, y1: 0.0 };
let sample = |extend, x| Ramp::new(&Gradient::new(line, &stops, extend, IDENTITY), &IDENTITY).at(x, 0.0);

// At x = 125 the offset is 1.25, a quarter past the end. (`at` samples half a pixel in.)
assert_eq!(sample(Extend::Pad, 124.5), Some(blue));
// Repeat starts over, so this is the color at offset 0.25.
assert_eq!(sample(Extend::Repeat, 124.5), sample(Extend::Pad, 24.5));
// Reflect turns back, so this is the color at offset 0.75.
assert_eq!(sample(Extend::Reflect, 124.5), sample(Extend::Pad, 74.5));
Pad
The first stop's color fills everything before the start, and the last stop's everything after the end. The default.
Reflect
The stops run back and forth: 0 to 1, then 1 back to 0, and so on, so the colors never jump.
Repeat
The stops start over at every whole offset: 0 to 1, then 0 to 1 again, jumping from the last color back to the first.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::GlyphBitmap
#[non_exhaustive]
pub struct GlyphBitmap<'a> {
    pub image: BitmapImage<'a>,
    pub ppem: u16,
    pub left: i16,
    pub top: i16,
    pub mirrored: bool,
}

A glyph's picture from a bitmap table, with the size it was made for and where it sits against the glyph's origin.

Some fonts store glyphs as pictures in place of outlines: color emoji as PNG files, in the sbix or CBDT table, and older screen fonts as small black-and-white or gray bitmaps, in EBDT or bdat. Such a font holds its pictures in strikes, one set for each pixel size it was drawn at. Font::bitmap picks the strike nearest the size you ask for and returns this.

Placing it. The picture was made for text at ppem pixels per em, which is seldom the size you draw at. Scale it by your font size in pixels over ppem. Then, with the glyph's origin on the baseline at (x, y) and y growing downward as it does on a screen, the top left corner of the picture goes at (x + left * scale, y - top * scale). How far to move the pen afterward still comes from Font::advance.

The lifetime is the font's: a PNG is lent from the font's own bytes, not copied. The struct is #[non_exhaustive]: read its fields.

use daegun::color::{BitmapImage, GlyphBitmap};

let glyph = font.glyph_id('😀').expect("the font has the emoji");
// Text at 32 pixels.
let size = 32.0;
let bitmap: GlyphBitmap = font.bitmap(glyph, 32).expect("a bitmap glyph");

// Noto Color Emoji's pictures are made for 109 pixels per em, whatever size you ask for.
assert_eq!(bitmap.ppem, 109);
let scale = size / f64::from(bitmap.ppem);

// With the glyph's origin at (x, y) and y growing downward, the picture's top left corner goes here.
let (x, y) = (10.0, 40.0);
let corner = (x + f64::from(bitmap.left) * scale, y - f64::from(bitmap.top) * scale);
if let BitmapImage::Png(png) = &bitmap.image {
    // Decode `png` with a PNG library and draw it at `corner`, scaled by `scale`.
}
image: BitmapImage<'a>
The picture, as a BitmapImage: a PNG for you to decode, or coverage already decoded.
ppem: u16
The size of the strike the picture came from, in pixels per em. It may not be the size you asked for, since a font has strikes for some sizes only: scale the picture by your size over this.
left: i16
Where the picture's left edge lies, in pixels at ppem, to the right of the glyph's origin. A negative value is to the left of it.
top: i16
Where the picture's top edge lies, in pixels at ppem, above the glyph's origin on the baseline. sbix stores the bottom edge, so there daegun adds the PNG's height, and every format answers the same way.
mirrored: bool
True when the picture is to be drawn flipped left to right. Only an sbix glyph that borrows another glyph's picture through Apple's flip record sets it.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Gradient
#[non_exhaustive]
pub struct Gradient<'s> {
    pub kind: GradientKind,
    pub stops: &'s [Stop],
    pub extend: Extend,
    pub transform: [f64; 6],
}

A gradient as a scene holds it: its shape, its stops, how it goes on past them and where it sits.

A fill whose paint is Paint::Gradient names one by id, and DisplayList::gradient hands it over. From there you either sample it with a Ramp, or read its four fields and build the same gradient in a renderer of your own.

The stops are borrowed, from the scene or from a slice of yours, and that is what the lifetime is.

A gradient from Font::color_scene has two or more stops, sorted by offset. A font may put its first and last stops anywhere along the line or past its ends, and the scene moves the shape's points so that those stops land on offsets 0 and 1. The exception is stops that all share one offset, which stay there when it lies within 0 to 1. A color line with a single stop reaches you as a Paint::Solid fill instead, and one with no stops as no fill at all.

It is #[non_exhaustive], so it can't be built by literal: use Gradient::new.

use daegun::color::{Extend, GradientKind, Op, Paint, Rgba, SceneOptions, IDENTITY};
use daegun::{GlyphId, Location};

// Glyph 8 of the COLR test font is a rectangle filled with a linear gradient.
let scene = font.color_scene(GlyphId(8), &Location::default(), &SceneOptions::DEFAULT)?
    .expect("a color glyph");
for op in scene.ops() {
    let Op::Fill { paint: Paint::Gradient(id), .. } = op else { continue };
    let gradient = scene.gradient(*id).expect("a scene holds every gradient its fills name");

    // Red at x = 100 to blue at x = 900, in font units, repeating past both ends.
    assert_eq!(gradient.kind, GradientKind::Linear { x0: 100.0, y0: 250.0, x1: 900.0, y1: 250.0 });
    assert_eq!(gradient.stops[0].color, Rgba::opaque(255, 0, 0));
    assert_eq!(gradient.stops[1].color, Rgba::opaque(0, 0, 255));
    assert_eq!(gradient.extend, Extend::Repeat);
    assert_eq!(gradient.transform, IDENTITY);
}
kind: GradientKind
The shape, with its points: linear, radial or sweep.
stops: &'s [Stop]
The stops. In a gradient from a scene they are in order of offset. In one of your own they may come in any order, as Ramp sorts its copy.
extend: Extend
What is painted before the first stop and after the last.
transform: [f64; 6]
A Matrix that takes the gradient's own space, the one kind is written in, to the scene's. In a scene from a font it holds every transform the font put around the gradient. It is separate from the transform of the fill that uses the gradient, which places the path.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::gradient::Interpolation
#[non_exhaustive]
pub enum Interpolation {
    LinearLight,
    Srgb,
}

How the colors between two stops are worked out: in linear light, or on the sRGB numbers as stored.

A gradient's stops are sRGB colors, and the color between two of them is a weighted average. The answer depends on what is averaged. Ramp::new uses LinearLight, the default and what the OpenType specification asks for. Ramp::with_interpolation lets you pick.

The two differ most between colors that are far apart, and where the alpha changes. Halfway from opaque red to opaque blue is (188, 0, 188) in linear light and (128, 0, 128) on the sRGB numbers. Halfway from opaque red to fully transparent blue is pure red at half alpha in linear light, since a transparent stop has no color to add, and purple at half alpha on the sRGB numbers.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::color::gradient::{Interpolation, Ramp};
use daegun::color::{Extend, Gradient, GradientKind, Rgba, Stop, IDENTITY};

// Opaque red to fully transparent blue, over 100 pixels.
let stops = [
    Stop { offset: 0.0, color: Rgba::opaque(255, 0, 0) },
    Stop { offset: 1.0, color: Rgba { r: 0, g: 0, b: 255, a: 0 } },
];
let line = GradientKind::Linear { x0: 0.0, y0: 0.0, x1: 100.0, y1: 0.0 };
let gradient = Gradient::new(line, &stops, Extend::Pad, IDENTITY);
// `at` samples half a pixel in, so 49.5 reads x = 50, the halfway point.
let halfway = |how| Ramp::with_interpolation(&gradient, &IDENTITY, how).at(49.5, 0.0);

// In linear light the transparent stop adds no color: red, half faded.
assert_eq!(halfway(Interpolation::LinearLight), Some(Rgba { r: 255, g: 0, b: 0, a: 128 }));
// On the stored numbers the blue leaks in.
assert_eq!(halfway(Interpolation::Srgb), Some(Rgba { r: 128, g: 0, b: 128, a: 128 }));
LinearLight
Each stop's color is converted from sRGB to linear light and multiplied by its alpha, the average is taken on those values, and the result is converted back to a straight sRGB color. The default.
Srgb
The stored numbers are averaged as they are, channel by channel, with the alpha as one more channel. For matching a renderer that does the same.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::gradient::Ramp
pub struct Ramp(/* private */);

A gradient made ready to sample: ask it for the color at any pixel.

A scene gives you a gradient as data. To draw it yourself you need the color under each pixel the fill covers, and that is what a ramp answers. Build one for each gradient with Ramp::new, then call Ramp::at for each pixel.

Building it does the work that is the same for every pixel: it sorts the stops, inverts the transform and prepares the blend between each pair of stops. It keeps its own copy of the stops and borrows nothing, so it may outlive the gradient and the scene. Build a new one when the transform to pixels changes.

A ramp knows nothing of the shape being filled. It answers for any pixel of the plane, and you use the answers where the fill's path covers.

The type is opaque, and its Debug prints Ramp { .. }.

use daegun::color::gradient::Ramp;
use daegun::color::{Op, Paint, SceneOptions};
use daegun::{GlyphId, Location};

// Glyph 8 of the COLR test font is filled with a linear gradient, red on the left to blue on the right.
let scene = font.color_scene(GlyphId(8), &Location::default(), &SceneOptions::DEFAULT)?
    .expect("a color glyph");
// Font units to pixels: 100 px to the em, y down, the baseline 100 px below the top.
let scale = 100.0 / f64::from(font.units_per_em());
let to_device = [scale, 0.0, 0.0, -scale, 0.0, 100.0];

let (width, height) = (100, 100);
let mut pixels = vec![[0u8; 4]; width * height];
for op in scene.ops() {
    let Op::Fill { paint: Paint::Gradient(id), .. } = op else { continue };
    let Some(gradient) = scene.gradient(*id) else { continue };
    let ramp = Ramp::new(&gradient, &to_device);
    for y in 0..height {
        for x in 0..width {
            // A real renderer writes only where the fill's path covers the pixel.
            if let Some(color) = ramp.at(x as f64, y as f64) {
                pixels[y * width + x] = color.into();
            }
        }
    }
}
// The glyph spans pixels 10 to 89 across: nearly pure red at one end, nearly pure blue at the other.
assert_eq!(pixels[50 * width + 10], [254, 0, 18, 255]);
assert_eq!(pixels[50 * width + 89], [18, 0, 254, 255]);
  • Implements: Clone, Debug.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::GradientId
pub struct GradientId(pub usize);

Names one gradient of a DisplayList by its position in the list.

A Paint::Gradient holds one, and DisplayList::gradient turns it into the Gradient itself. Ids count from 0 in the order the gradients were added, so GradientId(n) names item n of DisplayList::gradients. An id means something only to the list it came from.

use daegun::color::{GradientId, Op, Paint, SceneOptions};
use daegun::{GlyphId, Location};

let options = SceneOptions::DEFAULT;
let scene = font.color_scene(GlyphId(8), &Location::default(), &options)?.expect("a color glyph");
for op in scene.ops() {
    if let Op::Fill { paint: Paint::Gradient(id), .. } = *op {
        // The scene has one gradient, so the fill names id 0.
        assert_eq!(id, GradientId(0));
        let gradient = scene.gradient(id).expect("an id from this scene");
        assert_eq!(gradient.stops.len(), 2);
    }
}
usize
The gradient's index in its list, counting from 0.
  • Implements: Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::GradientKind
#[non_exhaustive]
pub enum GradientKind {
    Linear {
        x0: f32,
        y0: f32,
        x1: f32,
        y1: f32,
    },
    Radial {
        x0: f32,
        y0: f32,
        r0: f32,
        x1: f32,
        y1: f32,
        r1: f32,
    },
    Sweep {
        cx: f32,
        cy: f32,
        start_angle: f32,
        end_angle: f32,
    },
}

A gradient's shape: along a line, between two circles, or around a point.

The numbers are in the gradient's own space, which Gradient::transform takes to the scene's. A scene from Font::color_scene is in font units, y up, so there they are font units once that transform is applied.

In each shape a point has an offset, 0 at the start and 1 at the end, and the offset picks the color from the stops. Extend says what is painted outside 0 to 1.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::color::{GradientKind, SceneOptions};
use daegun::{GlyphId, Location};

// Glyph 12 of the COLR test font is filled with a sweep gradient.
let scene = font.color_scene(GlyphId(12), &Location::default(), &SceneOptions::DEFAULT)?
    .expect("a color glyph");
for gradient in scene.gradients() {
    match gradient.kind {
        GradientKind::Linear { x0, y0, x1, y1 } => { /* a line from (x0, y0) to (x1, y1) */ }
        GradientKind::Radial { x0, y0, r0, x1, y1, r1 } => { /* two circles */ }
        GradientKind::Sweep { cx, cy, start_angle, end_angle } => {
            // Around (500, 600), from 90 degrees, straight up, to 270, straight down.
            assert_eq!((cx, cy, start_angle, end_angle), (500.0, 600.0, 90.0, 270.0));
        }
        _ => {}
    }
}
Linear { x0: f32, y0: f32, x1: f32, y1: f32 }
A linear gradient. The offset is 0 at (x0, y0) and 1 at (x1, y1), and the color is the same all along any line at a right angle to the one between them. A scene from a font has already reduced the three points of a COLR linear gradient to these two.
x0: f32
The x of the start point, where the offset is 0, in the units of the gradient's space.
y0: f32
The y of the start point, in the same units.
x1: f32
The x of the end point, where the offset is 1.
y1: f32
The y of the end point.
Radial { x0: f32, y0: f32, r0: f32, x1: f32, y1: f32, r1: f32 }
A radial gradient between two circles. The offset is 0 on the first circle and 1 on the second, and each offset between or beyond has its own circle, the center and the radius changing evenly from one to the next. Where two of those circles pass through a point, the one with the higher offset colors it. A point that none of them passes through is not painted.
x0: f32
The x of the first circle's center, in the units of the gradient's space.
y0: f32
The y of the first circle's center.
r0: f32
The first circle's radius, in the same units as the centers. 0 makes it a point. In a scene it can be below 0, where the font put its first stop before the start of the line: only circles with a radius of 0 or more paint.
x1: f32
The x of the second circle's center.
y1: f32
The y of the second circle's center.
r1: f32
The second circle's radius, in the same units as the centers.
Sweep { cx: f32, cy: f32, start_angle: f32, end_angle: f32 }
A sweep gradient, also called conic: the color changes with the angle around a center. The offset is 0 at start_angle and 1 at end_angle. Angles are in degrees and run counterclockwise from the positive x axis in a space with y up, so 0 points right and 90 points up. A point's own angle is counted from 0 up to 360, and is not wrapped to fit the start and the end.
cx: f32
The x of the center, in the units of the gradient's space.
cy: f32
The y of the center.
start_angle: f32
The angle where the offset is 0, in degrees counterclockwise from the positive x axis.
end_angle: f32
The angle where the offset is 1, in degrees, measured the same way. It may be the smaller of the two, which runs the stops clockwise.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Matrix
pub type Matrix = [f64; 6];

A 2 by 3 affine transform as six numbers, [a, b, c, d, dx, dy].

A point (x, y) goes to (a * x + c * y + dx, b * x + d * y + dy). So a and d scale x and y, b and c skew and rotate, and dx and dy move the result. IDENTITY is the one that changes nothing.

Every transform of a color scene is one: the transform of an Op::Fill and of a ClipShape, the transform of a Gradient, the to_device you give Ramp::new and the ctm of color::lower. Chain two with color::concat and undo one with color::invert.

TransformPen and Path::replay take the same six numbers in the same order, so a matrix goes to them as it is. OutlineOptions::transform keeps the same order too, but holds f32 values, so a matrix has to be converted number by number for it.

use daegun::color::Matrix;

// Half the size, y flipped to run down, then moved 10 right and 30 down.
let to_pixels: Matrix = [0.5, 0.0, 0.0, -0.5, 10.0, 30.0];
let apply = |m: &Matrix, x: f64, y: f64| (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]);

// The point (40, 20) lands on (30, 20).
assert_eq!(apply(&to_pixels, 40.0, 20.0), (30.0, 20.0));
color::Op
#[non_exhaustive]
pub enum Op {
    Fill {
        path: PathId,
        paint: Paint,
        rule: FillRule,
        transform: [f64; 6],
    },
    PushClip {
        shapes: Range<usize>,
    },
    PopClip,
    PushLayer {
        opacity: f32,
        blend: Blend,
    },
    PopLayer,
}

One step of a scene: fill a path, start or end a clip, or start or end a layer.

A DisplayList is a sequence of these, and drawing it means doing each in order. A renderer keeps two stacks as it goes, one of clips and one of layers, with the canvas as the bottom layer.

Fills. Fill paints a path into the layer on top of the stack, source over what that layer already holds, inside the clips pushed since that layer began. A clip pushed before the layer cuts the whole layer as it is composited, so each clip counts once.

Clips. PushClip narrows the clip to the part of it that the named shapes cover. PopClip puts back the clip that was in force before the push it pairs with. They pair like brackets: a PopClip ends the most recent PushClip still open.

Layers. PushLayer starts a new, fully transparent layer and makes it the target of the fills that follow. PopLayer ends the most recent layer still open: that layer is composited onto the one below, by the blend mode and opacity its PushLayer gave, and drawing goes on in the one below. A COLR composite whose two sides both draw arrives as two layers, one inside the other: the outer holds the backdrop, and the inner, which carries the composite's blend mode, holds the source.

daegun's own renderer does all this in linear light with premultiplied alpha, turning each sRGB color into that form as it paints.

In a scene from Font::color_scene every push has its pop, and clips and layers together never nest more than 128 deep. The enum is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::color::{Op, SceneOptions};
use daegun::{GlyphId, Location};

let options = SceneOptions::DEFAULT;
let scene = font.color_scene(GlyphId(156), &Location::default(), &options)?.expect("a color glyph");

// How deep the clips and layers nest: the stack a renderer needs for this glyph.
let (mut open, mut deepest) = (0usize, 0usize);
for op in scene.ops() {
    match op {
        Op::PushClip { .. } | Op::PushLayer { .. } => open += 1,
        Op::PopClip | Op::PopLayer => open -= 1,
        // A fill, which opens nothing, or an op a later release adds.
        _ => {}
    }
    deepest = deepest.max(open);
}
// Every push was popped, and at most 4 were open at once.
assert_eq!((open, deepest), (0, 4));
Fill { path: PathId, paint: Paint, rule: FillRule, transform: [f64; 6] }
Fill a path with a color or a gradient.
path: PathId
The id of the path to fill. DisplayList::path returns its outline.
paint: Paint
What to fill it with: a Paint, which is one color or one of the list's gradients.
rule: FillRule
Which points count as inside the path. Always FillRule::NonZero in a scene from a color glyph.
transform: [f64; 6]
Where the path is placed: a Matrix [a, b, c, d, e, f] that takes the path's points into the scene's space, x' = a·x + c·y + e and y' = b·x + d·y + f. It places the path only. A gradient has a transform of its own.
PushClip { shapes: Range<usize> }
Start a clip. From here to the matching PopClip, drawing shows only inside these shapes, and inside whatever clip was already in force.
shapes: Range<usize>
Which of the list's clip shapes make up the clip, as a range to hand to DisplayList::shapes. A point inside any one of the shapes is inside the clip.
PopClip
End the most recent clip still open, and go back to the clip in force before it.
PushLayer { opacity: f32, blend: Blend }
Start a new transparent layer. The ops up to the matching PopLayer draw into it, not onto what lies below.
opacity: f32
What the layer's alpha is multiplied by as it is composited, from 0, which hides it, to 1, which leaves it as drawn. Font::color_scene always gives 1.
blend: Blend
The Blend mode that composites the layer onto the one below, with this layer as the source and the one below as the backdrop.
PopLayer
End the most recent layer still open: composite it onto the layer below by its blend mode and opacity, inside the clip that was in force when it was pushed, and go on drawing there.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Paint
#[non_exhaustive]
pub enum Paint {
    Solid(Rgba),
    Gradient(GradientId),
}

What a fill paints its path with: one color, or one of the scene's gradients.

It is the paint of an Op::Fill. In a scene from Font::color_scene the colors are final: the palette and the text color of the SceneOptions are already applied.

A gradient with a single stop arrives as Solid. One with no stops, one whose stops all sit at one offset under repeat or reflect, and a linear one with no direction leave no fill at all. A radial gradient between two identical circles, or a sweep whose two angles are equal under repeat or reflect, still arrives as a fill, and color::gradient::Ramp paints it as nothing.

The enum is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::color::{Op, Paint, SceneOptions};
use daegun::{GlyphId, Location};

let options = SceneOptions::DEFAULT;
// Glyph 177 of the test font is two fills, one in a solid color and one in a gradient.
let scene = font.color_scene(GlyphId(177), &Location::default(), &options)?.expect("a color glyph");
let (mut solids, mut gradients) = (0, 0);
for op in scene.ops() {
    let Op::Fill { paint, .. } = op else { continue };
    match *paint {
        Paint::Solid(color) => solids += 1,       // fill with `color`
        Paint::Gradient(id) => gradients += 1,    // fill with scene.gradient(id)
        _ => {}
    }
}
assert_eq!((solids, gradients), (1, 1));
Solid(Rgba)
One color over the whole path, an Rgba in sRGB with straight alpha.
Gradient(GradientId)
A gradient, by its id. DisplayList::gradient returns the Gradient, and color::gradient::Ramp samples one pixel by pixel.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::PaintGraph
pub struct PaintGraph {
    /* private fields */
}

A COLR version 1 glyph's paint tree as the font stores it, before anything is turned into drawing commands.

COLR version 1 describes a color glyph as a tree of paints. Some paints fill with a color or a gradient, some clip what is below them to a glyph's outline, some move or turn it, and some stack or blend several. Font::paint_graph reads one glyph's tree into a PaintGraph, with a variable font's values worked out for the location you pass and every color looked up in the palette you name.

Most callers want Font::color_scene instead. It lowers this same tree into a flat list of fills, clips and layers with the outlines included, ready to draw, and it handles COLR version 0 glyphs too. Take the graph when you want the paints themselves: to write them out in another format, to inspect what a font holds, or to feed a renderer that has its own gradients, transforms and blend modes.

To read it, start at PaintGraph::root. That gives a PaintRef, whose PaintRef::node is the paint's own values as a PaintNode and whose PaintRef::children are the paints directly below it. The graph holds the paints alone: the glyph's clip box, which COLR stores beside them, comes from Font::colr_clip_box.

It is always a finite tree. A paint that reuses another color glyph has that glyph's paints read in below it, and a paint that leads back to one it is inside is cut off there and read as layers with nothing in them. So is a paint with more than 64 paints above it, and the rest of a graph past what daegun reads for one glyph.

You can also build one by hand with PaintGraph::new and PaintGraph::with, and hand it to lower to get a scene from paints of your own.

use daegun::color::{PaintGraph, PaintNode, PaintRef};
use daegun::{GlyphId, Location};

// How many fills are painted at or below a paint.
fn fills(paint: PaintRef) -> usize {
    let own = match paint.node() {
        PaintNode::Solid { .. }
        | PaintNode::LinearGradient { .. }
        | PaintNode::RadialGradient { .. }
        | PaintNode::SweepGradient { .. } => 1,
        _ => 0,
    };
    own + paint.children().map(fills).sum::<usize>()
}

// Glyph 123 at the default location, in palette 0.
let graph: Option<PaintGraph> = font.paint_graph(GlyphId(123), &Location::default(), 0);
let graph = graph.expect("a COLR version 1 glyph");

// Its root stacks two layers, and three fills are painted in all.
let root = graph.root();
assert!(matches!(root.node(), PaintNode::Layers));
assert_eq!(root.children().count(), 2);
assert_eq!(fills(root), 3);

// A glyph with no COLR version 1 paints has no graph.
assert!(font.paint_graph(GlyphId(0), &Location::default(), 0).is_none());
impl Drop
With the std feature, which is on by default, a dropped graph leaves its two lists to its thread when together they hold 64 KiB or less, and the next PaintGraph::new on that thread starts in them. Reading one graph after another then reuses the memory. A larger graph frees its lists, and release_thread frees the ones a thread is keeping.
impl PaintVisitor
As a visitor a graph records the paints it is handed: enter adds a paint below the one that is open, the first paint entered being the root, and leave closes it. That is how Font::paint_graph builds its graph, so Font::visit_paint_graph with a PaintGraph as the visitor fills one the same way. Call the two yourself to build a graph paint by paint, or let PaintGraph::with pair them. A leave with no paint open does nothing.
  • Implements: Clone, Debug, Default, Drop, PaintVisitor, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::PaintNode
#[non_exhaustive]
pub enum PaintNode<'s> {
    Layers,
    Glyph {
        glyph: GlyphId,
    },
    ColrGlyph {
        glyph: GlyphId,
    },
    Solid {
        color: Rgba,
        foreground: bool,
    },
    LinearGradient {
        extend: Extend,
        stops: &'s [ColorStop],
        x0: f64,
        y0: f64,
        x1: f64,
        y1: f64,
        x2: f64,
        y2: f64,
    },
    RadialGradient {
        extend: Extend,
        stops: &'s [ColorStop],
        x0: f64,
        y0: f64,
        r0: f64,
        x1: f64,
        y1: f64,
        r1: f64,
    },
    SweepGradient {
        extend: Extend,
        stops: &'s [ColorStop],
        cx: f64,
        cy: f64,
        start_angle: f64,
        end_angle: f64,
    },
    Transform {
        matrix: [f64; 6],
    },
    Translate {
        dx: f64,
        dy: f64,
    },
    Scale {
        sx: f64,
        sy: f64,
        center: Option<Center>,
    },
    ScaleUniform {
        s: f64,
        center: Option<Center>,
    },
    Rotate {
        angle: f64,
        center: Option<Center>,
    },
    Skew {
        x_angle: f64,
        y_angle: f64,
        center: Option<Center>,
    },
    Composite {
        mode: Blend,
    },
}

One paint of a COLR version 1 graph: its kind and its own values, without the paints below it.

You meet a PaintNode in two places. PaintRef::node returns one for each paint of a PaintGraph, and PaintVisitor::enter is handed one for each paint as Font::visit_paint_graph walks. Either way the node is the paint alone. The paints below it are not inside it: they come from PaintRef::children, or as the calls to enter that follow.

There are four kinds. Fills paint color and have nothing below them: PaintNode::Solid and the three gradients. A fill has no shape of its own and covers all the area the paints above it leave open. Clips give it a shape: PaintNode::Glyph paints its child only inside a glyph's outline. Transforms move, resize, turn or slant everything below them: PaintNode::Transform, PaintNode::Translate, PaintNode::Scale, PaintNode::ScaleUniform, PaintNode::Rotate and PaintNode::Skew. Groups combine paints: PaintNode::Layers stacks them, PaintNode::Composite blends two, and PaintNode::ColrGlyph reuses another color glyph.

Positions and lengths are in font units with y up. Angles are in degrees and turn counterclockwise. The values are final: a variable font's deltas are already applied for the location you asked at, and colors are already looked up in the palette. A varied value may leave the range the font format can store, so a radius can come out negative.

Transforms nest from the inside out: the one nearest a paint acts on it first, then the one above that.

A paint daegun can't read comes as PaintNode::Layers with nothing below it, which draws nothing. That is what you get for a paint of a format it doesn't know, for a color the palette has no entry for, for a paint that leads back to one it is inside, for one with more than 64 paints above it, and for any paint past what daegun reads for one glyph: 100,000 paints and 1,000,000 gradient stops, each plus one for every 4 bytes of the COLR table.

The enum is #[non_exhaustive], so a match needs a _ arm. You can still build any variant by name, which is how PaintGraph::with is fed. The lifetime is that of a gradient's stops: a node from PaintRef::node borrows the graph, and a node handed to PaintVisitor::enter is lent for that call only.

use daegun::color::{PaintNode, PaintRef};
use daegun::{GlyphId, Location};

// One line of text for each paint, indented by its depth: the start of an exporter.
fn describe(paint: PaintRef, depth: usize, out: &mut Vec<String>) {
    let what = match paint.node() {
        PaintNode::Layers => "layers".to_string(),
        PaintNode::Glyph { glyph } => format!("clip to glyph {}", glyph.0),
        PaintNode::Solid { foreground: true, .. } => "fill with the text's color".to_string(),
        PaintNode::Solid { color, .. } => format!("fill #{:02x}{:02x}{:02x}", color.r, color.g, color.b),
        PaintNode::LinearGradient { stops, .. } => format!("linear gradient, {} stops", stops.len()),
        PaintNode::Rotate { angle, center } => {
            let c = center.unwrap_or_default();
            format!("rotate {angle:.1} degrees about ({}, {})", c.x, c.y)
        }
        PaintNode::Composite { mode } => format!("composite {mode:?}"),
        // PaintNode is #[non_exhaustive], and a real exporter has an arm for each paint it knows.
        other => format!("{other:?}"),
    };
    out.push(format!("{}{what}", "  ".repeat(depth)));
    for child in paint.children() {
        describe(child, depth + 1, out);
    }
}

let graph = font.paint_graph(GlyphId(101), &Location::default(), 0).expect("a COLR version 1 glyph");
let mut lines = Vec::new();
describe(graph.root(), 0, &mut lines);
assert_eq!(lines, [
    "composite DestOver",
    "  rotate 25.0 degrees about (500, 500)",
    "    clip to glyph 3",
    "      fill #ffa500",
    "  clip to glyph 3",
    "    fill #0000ff",
]);
Layers
Paints its children one after another, the first at the bottom and each later one over it. With no children it draws nothing, which is also how a paint daegun can't read shows up.
Glyph { glyph: GlyphId }
Paints its one child clipped to the outline of a glyph. This is how a shape gets drawn: the outline gives the shape and the child, most often a fill, gives the color.
glyph: GlyphId
The glyph whose outline is the clip. It is read as a plain outline, the one Font::outline draws, whether or not that glyph has color of its own. A glyph with no outline draws nothing.
ColrGlyph { glyph: GlyphId }
Paints another color glyph in place. Its one child is that glyph's root paint, already read into this graph. Font::color_scene also clips it to that glyph's clip box, where it has one.
glyph: GlyphId
The color glyph being reused. Where that glyph has no COLR version 1 paints, the child is layers with nothing in them.
Solid { color: Rgba, foreground: bool }
Fills with one color, over all the area the paints above it leave open. Under a Glyph that is the outline.
color: Rgba
The palette's color as straight (not premultiplied) sRGB, with its alpha already multiplied by the paint's own alpha. When foreground is true no palette color is involved: this is black, and only its alpha means anything.
foreground: bool
True when the font asks for the color of the text here, in place of a palette entry. Paint with the text's color, its alpha multiplied by color.a / 255. Font::color_scene does that with SceneOptions::foreground.
LinearGradient { extend: Extend, stops: &'s [ColorStop], x0: f64, y0: f64, x1: f64, y1: f64, x2: f64, y2: f64, }
A gradient along a line. The colors run from the point p0 (x0, y0) to p1 (x1, y1), and a third point, p2 (x2, y2), sets the tilt: every line of one color is parallel to the line from p0 to p2. With p2 at a right angle to the line from p0 to p1, it is the usual two-point gradient. A gradient whose p1 lies on p0, or whose p2 lies on the line through p0 and p1, has no direction to run in, and Font::color_scene leaves it out.
extend: Extend
What is painted before the first stop and after the last: Extend::Pad carries the end colors on, Extend::Repeat starts the stops over, and Extend::Reflect runs them back and forth.
stops: &'s [ColorStop]
The colors along the line, each a ColorStop, in the order the font lists them. daegun does not sort them here. An offset of 0 is at p0 and 1 is at p1.
x0: f64
The x of p0, where the colors start, in font units.
y0: f64
The y of p0.
x1: f64
The x of p1, where the colors end.
y1: f64
The y of p1.
x2: f64
The x of p2, the point that tilts the gradient: lines of one color run parallel to the line from p0 to p2.
y2: f64
The y of p2.
RadialGradient { extend: Extend, stops: &'s [ColorStop], x0: f64, y0: f64, r0: f64, x1: f64, y1: f64, r1: f64, }
A gradient between two circles. The colors start on the first circle and end on the second, and in between COLR draws the circles you get by sliding the center and the radius evenly from one to the other. With both centers in one place it is a plain round gradient, and with r0 at 0 it starts from a point.
extend: Extend
What is painted before the first stop and after the last: Extend::Pad, Extend::Repeat or Extend::Reflect.
stops: &'s [ColorStop]
The colors from circle to circle, each a ColorStop, in the order the font lists them. An offset of 0 is on the first circle and 1 is on the second.
x0: f64
The x of the first circle's center, in font units.
y0: f64
The y of the first circle's center.
r0: f64
The first circle's radius, in font units. 0 makes it a point.
x1: f64
The x of the second circle's center.
y1: f64
The y of the second circle's center.
r1: f64
The second circle's radius, in font units.
SweepGradient { extend: Extend, stops: &'s [ColorStop], cx: f64, cy: f64, start_angle: f64, end_angle: f64, }
A gradient that turns around a center point, as the colors of a color wheel do. The colors are laid along the angle, starting at start_angle and ending at end_angle.
extend: Extend
What is painted at angles before the first stop and after the last: Extend::Pad, Extend::Repeat or Extend::Reflect.
stops: &'s [ColorStop]
The colors around the center, each a ColorStop, in the order the font lists them. An offset of 0 is at start_angle and 1 is at end_angle.
cx: f64
The x of the center, in font units.
cy: f64
The y of the center.
start_angle: f64
The angle where the colors start, in degrees counterclockwise from the positive x axis: 0 points right and 90 points up. The font format stores angles from -180 to a little under 540.
end_angle: f64
The angle where the colors end, measured the same way. It may be the smaller of the two, and the two may lie more than a full turn apart.
Transform { matrix: [f64; 6] }
Draws its one child through a 2 by 3 matrix, which can move, scale, turn and slant it all at once.
matrix: [f64; 6]
The matrix as [xx, yx, xy, yy, dx, dy]: a point (x, y) of the child lands at (xx*x + xy*y + dx, yx*x + yy*y + dy). dx and dy are in font units. It is laid out as a Matrix is, so it goes straight into concat or invert.
Translate { dx: f64, dy: f64 }
Draws its one child moved, without turning or resizing it.
dx: f64
How far to move it to the right, in font units. A negative value moves it left.
dy: f64
How far to move it up, in font units. A negative value moves it down.
Scale { sx: f64, sy: f64, center: Option<Center> }
Draws its one child stretched or shrunk, by one factor across and another up.
sx: f64
The factor along x. 1 leaves the width as it is, 0.5 halves it, and a negative value mirrors the child left to right.
sy: f64
The factor along y. 1 leaves the height as it is, and a negative value flips the child top to bottom.
center: Option<Center>
The point that stays where it is while the rest scales toward it or away from it. None is the origin, (0, 0).
ScaleUniform { s: f64, center: Option<Center> }
Draws its one child scaled by the same factor both ways, so it keeps its proportions.
s: f64
The factor for both axes. 1 is no change and 2 is twice the size.
center: Option<Center>
The point that stays where it is while the rest scales. None is the origin, (0, 0).
Rotate { angle: f64, center: Option<Center> }
Draws its one child turned around a point.
angle: f64
How far to turn it, in degrees. A positive angle turns counterclockwise. The font format stores angles in steps of about 0.011 degrees, so a turn designed as 10 degrees reads as 9.99755859375.
center: Option<Center>
The point the child turns around. None is the origin, (0, 0).
Skew { x_angle: f64, y_angle: f64, center: Option<Center> }
Draws its one child slanted, as an oblique typeface is. Each angle slants it along one axis.
x_angle: f64
The slant along x, in degrees. A point moves left by tan(x_angle) times its height above the center, so a positive angle leans the top of the child to the left, counterclockwise. A slant of exactly 90 degrees has no finite tangent, and Font::color_scene draws it as no slant.
y_angle: f64
The slant along y, in degrees. A point moves up by tan(y_angle) times its distance to the right of the center, so a positive angle raises the right side of the child, counterclockwise.
center: Option<Center>
The point the slant leaves in place. None is the origin, (0, 0).
Composite { mode: Blend }
Blends its two children. The second child, the backdrop, is painted first, and the first child, the source, is combined with it as mode says. The result then goes over whatever was painted before.
mode: Blend
How the source combines with the backdrop, as a Blend: a Porter-Duff operator such as Blend::SrcOver or Blend::SrcIn, or a blend mode such as Blend::Multiply. A mode number past the last one COLR defines reads as Blend::Clear.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::PaintRef
pub struct PaintRef<'a> {
    /* private fields */
}

One paint of a PaintGraph: a cursor you read the paint from and step down to its children with.

PaintGraph::root gives the first one, and PaintRef::children gives one for each paint below it. PaintRef::node is the paint itself. A ref is a small Copy value that borrows the graph, not the ref it came from, so a child may outlive its parent ref but not the graph.

Two refs compare equal when their paints are equal and so is everything below them, whichever graphs they belong to. Printing one with {:?} writes the whole tree below it, nested.

use daegun::color::{PaintNode, PaintRef};
use daegun::{GlyphId, Location};

// Every glyph whose outline the paints at or below `paint` clip to.
fn outlines(paint: PaintRef, found: &mut Vec<GlyphId>) {
    if let PaintNode::Glyph { glyph } = paint.node() {
        found.push(glyph);
    }
    for child in paint.children() {
        outlines(child, found);
    }
}

let graph = font.paint_graph(GlyphId(169), &Location::default(), 0).expect("a COLR version 1 glyph");
let mut found = Vec::new();
outlines(graph.root(), &mut found);
// This glyph is eight layers, each an outline filled with a color.
assert_eq!(found.len(), 8);
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::PaintVisitor
pub trait PaintVisitor {
    fn enter(&mut self, node: PaintNode<'_>);
    fn leave(&mut self);
}

A trait you implement to be handed a color glyph's paints one by one, with no graph built.

Font::visit_paint_graph walks a COLR version 1 glyph's paints and calls your visitor as it goes: enter for a paint, then the same for each paint below it, then leave. A paint comes before the paints below it, layers come bottom to top, and a composite's source comes before its backdrop. The calls nest as brackets do, so a counter raised in enter and lowered in leave is the depth.

Use it when one pass over the paints is enough, such as collecting the glyphs or colors a color glyph uses, or writing its paints out in another format. No tree is built or kept. When you need to go back and forth over the paints, take the whole PaintGraph from Font::paint_graph.

PaintGraph implements the trait itself: as a visitor it records the paints it is handed, which is how Font::paint_graph is made. A &mut to a visitor is a visitor too, so you can lend yours to a function that takes one by value, and &mut dyn PaintVisitor works where you want no generics.

Both methods are required. If a later release adds a method it will come with a default body, so an implementation written today keeps compiling.

use daegun::color::{PaintNode, PaintVisitor};
use daegun::{GlyphId, Location};

// Collects the outlines a color glyph draws with, and how deep its paints nest.
#[derive(Default)]
struct Outlines {
    glyphs: Vec<GlyphId>,
    depth: usize,
    deepest: usize,
}

impl PaintVisitor for Outlines {
    fn enter(&mut self, node: PaintNode<'_>) {
        self.depth += 1;
        self.deepest = self.deepest.max(self.depth);
        if let PaintNode::Glyph { glyph } = node {
            self.glyphs.push(glyph);
        }
    }
    fn leave(&mut self) {
        self.depth -= 1;
    }
}

let mut seen = Outlines::default();
let found = font.visit_paint_graph(GlyphId(169), &Location::default(), 0, &mut seen);
assert!(found);
// Eight outlines, each under the layers paint and over its fill: three levels.
assert_eq!(seen.glyphs.len(), 8);
assert_eq!(seen.deepest, 3);
color::Palette
#[non_exhaustive]
pub struct Palette {
    pub index:      u16,
    pub light_safe: bool,
    pub dark_safe:  bool,
    pub name_id:    Option<NameId>,
}

One of a font's CPAL color palettes as a palette picker lists it: its index, the backgrounds it suits and its name.

A color font keeps its colors in the CPAL table as one or more palettes. Each palette is a list of the same length, and color glyphs name a color by its place in the list, so choosing another palette recolors every color glyph at once. That is how one font can carry a version for light backgrounds and another for dark. Font::palettes lists them in order.

This is the palette's label, not its colors: Font::palette_colors gives those. To draw in a palette, pass its index wherever a call takes one: SceneOptions::with_palette for Font::color_scene, or the palette argument of Font::colr_layers and Font::paint_graph.

The two flags and the name come from version 1 of CPAL. A version 0 table has neither, so both flags are false and name_id is None. The struct is #[non_exhaustive]: read its fields.

use daegun::color::Palette;
use daegun::Location;

let palettes: Vec<Palette> = font.palettes();
// This font has three palettes: the second is marked for dark backgrounds, the third for light.
assert_eq!(palettes.len(), 3);
assert!(palettes[1].dark_safe && palettes[2].light_safe);

// The palette to draw with on a dark background, or the default where none is marked.
let dark = palettes.iter().find(|p| p.dark_safe).map_or(0, |p| p.index);
assert_eq!(dark, 1);

for palette in &palettes {
    let name = palette.name_id.and_then(|id| font.name(id, &Location::default()));
    // Show `name` in a picker, or a label made from palette.index where the font names none.
}
index: u16
The palette's number, counting from 0. Palette 0 is the default. Pass it as the palette of the color calls.
light_safe: bool
True if the font marks the palette as usable on a light background.
dark_safe: bool
True if the font marks the palette as usable on a dark background. A palette may set both flags, or neither.
name_id: Option<NameId>
The id of the palette's name in the font's name table, for a picker to show: Font::name reads the text. None where the font gives the palette no name.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::PathId
pub struct PathId(pub usize);

Names one path of a DisplayList by its position in the list.

An Op::Fill and a ClipShape each hold one, and DisplayList::path turns it into the outline. Ids count from 0 in the order the paths were added, so PathId(n) names item n of DisplayList::paths. Because ops name paths by id, one outline can be filled many times and is stored once. An id means something only to the list it came from.

use daegun::color::{Op, PathId, SceneOptions};
use daegun::Location;

// A color glyph whose eight layers all fill the same outline.
let glyph = font.glyph_id('R').expect("the font maps R");
let options = SceneOptions::DEFAULT;
let scene = font.color_scene(glyph, &Location::default(), &options)?.expect("a color glyph");
let filled: Vec<PathId> = scene.ops().iter()
    .filter_map(|op| match op { Op::Fill { path, .. } => Some(*path), _ => None })
    .collect();
// Eight fills, every one of path 0: the outline is in the scene once.
assert_eq!(filled, [PathId(0); 8]);
assert_eq!(scene.paths().len(), 1);
usize
The path's index in its list, counting from 0.
  • Implements: Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Premultiplied
pub struct Premultiplied {
    pub color: Rgb,
    pub alpha: f32,
}

A color and its alpha with each channel already multiplied by the alpha: what Blend::composite returns.

Each channel of color lies between 0 and alpha. A half-transparent pure red is color: [0.5, 0.0, 0.0] with alpha: 0.5, where the straight form would be [1.0, 0.0, 0.0] beside an alpha of 0.5.

To get the straight color back, divide each channel by alpha wherever it is above 0. A fully transparent result has no color to recover.

A plain value: build one by literal. Premultiplied::default() is fully transparent.

use daegun::color::{Blend, Premultiplied, Rgb};

// Half-transparent red drawn onto nothing.
let out: Premultiplied = Blend::SrcOver.composite([1.0, 0.0, 0.0], 0.5, [0.0; 3], 0.0);
assert_eq!(out, Premultiplied { color: [0.5, 0.0, 0.0], alpha: 0.5 });

// Back to a straight color, for a format that wants one.
let straight: Rgb = if out.alpha > 0.0 { out.color.map(|v| v / out.alpha) } else { [0.0; 3] };
assert_eq!(straight, [1.0, 0.0, 0.0]);
color: Rgb
Red, green and blue, each multiplied by alpha, so from 0 to alpha.
alpha: f32
The alpha, from 0, transparent, to 1, opaque.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Rgb
pub type Rgb = [f32; 3];

A color as three f32 values, red, green and blue, straight and from 0 to 1.

The form Blend::blend and Blend::composite take colors in. Straight means the values are not multiplied by an alpha, which those calls take beside the color. From an Rgba, divide each channel by 255.

The type doesn't say whether the values are sRGB-encoded or linear light, and neither call converts: what comes back is in the space of what went in. Rasterizer::color_glyph, the renderer daegun ships, composites in linear light.

use daegun::color::{Blend, Rgb, Rgba};

let to_rgb = |c: Rgba| -> Rgb { [c.r, c.g, c.b].map(|v| f32::from(v) / 255.0) };
let orange: Rgb = to_rgb(Rgba::opaque(255, 165, 0));
let gray: Rgb = [0.5, 0.5, 0.5];

// Multiplied by mid-gray, each channel of the orange is halved.
assert_eq!(Blend::Multiply.blend(orange, gray), [0.5, orange[1] * 0.5, 0.0]);
color::Rgba
pub struct Rgba {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

An sRGB color in 8 bits a channel, with straight alpha.

The color type of the module. A palette entry from Font::palette_colors is one, and so are the color of a Paint::Solid fill, the color of a Stop, what Ramp::at samples and the text color you set in SceneOptions::foreground.

Straight alpha means that red, green and blue are the color itself, not yet multiplied by the alpha: a half-transparent red is Rgba { r: 255, g: 0, b: 0, a: 128 }. The three channels are sRGB-encoded values, not linear light.

It is a plain value of four bytes in the order red, green, blue, alpha (#[repr(C)]), so build one by literal or with Rgba::opaque. Rgba::default() is transparent black.

use daegun::color::Rgba;

// The first color of the font's first palette is an opaque red.
let red: Rgba = font.palette_colors(0)[0];
assert_eq!(red, Rgba { r: 255, g: 0, b: 0, a: 255 });

// As the four bytes of an RGBA pixel, and back.
let pixel: [u8; 4] = red.into();
assert_eq!(pixel, [255, 0, 0, 255]);
assert_eq!(Rgba::from(pixel), red);
r: u8
Red, from 0 to 255.
g: u8
Green, from 0 to 255.
b: u8
Blue, from 0 to 255.
a: u8
Alpha, from 0, fully transparent, to 255, fully opaque.
impl From<[u8; 4]>
A color from the four bytes of an RGBA pixel, in the order red, green, blue, alpha.
impl From<Rgba> for [u8; 4]
The color as the four bytes of an RGBA pixel: red, green, blue, alpha. The alpha stays straight.
  • Implements: Clone, Copy, Debug, Default, Eq, From<Rgba> for [u8; 4], From<[u8; 4]>, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::SceneOptions
#[non_exhaustive]
pub struct SceneOptions {
    pub palette: u16,
    pub foreground: Rgba,
}

What Font::color_scene draws a color glyph with: which palette, and what color the text is.

Start from SceneOptions::DEFAULT, which is palette 0 and opaque black text, and change it with SceneOptions::with_palette and SceneOptions::with_foreground. The struct is #[non_exhaustive], so it cannot be written as a literal, but its fields are public to read and to set.

The text color matters because a color font can leave a color open. A layer or a paint can ask for "the color of the text" where others name a palette entry, so that part of the glyph matches the words around it. Pass the color you draw the rest of the line in.

use daegun::color::{Op, Paint, Rgba, SceneOptions};
use daegun::{GlyphId, Location};

// The third palette, and white text for a dark background.
let white = Rgba::opaque(255, 255, 255);
let options = SceneOptions::DEFAULT.with_palette(2).with_foreground(white);
assert_eq!((options.palette, options.foreground), (2, white));

// Glyph 154 of the test font is filled with the text color, whatever the palette.
let scene = font.color_scene(GlyphId(154), &Location::default(), &options)?.expect("a color glyph");
let filled = scene.ops().iter().find_map(|op| match op {
    Op::Fill { paint: Paint::Solid(color), .. } => Some(*color),
    _ => None,
});
assert_eq!(filled, Some(white));
palette: u16
The index of the CPAL palette that colors are taken from. Font::palettes lists them. An index the font doesn't have reads palette 0, the default.
foreground: Rgba
The color of the text, which a layer or paint that asks for the foreground takes. Where a version 1 paint or gradient stop has an alpha of its own, this color's alpha is multiplied by it. Opaque black by default.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Stop
pub struct Stop {
    pub offset: f32,
    pub color: Rgba,
}

One stop of a gradient: a color, and where along the gradient it sits.

Between two stops the gradient blends from one color to the next. Two stops at the same offset make a hard edge: the first colors the side before that offset, and the last colors the offset itself and the side after it.

The stops of a scene's gradients come sorted by offset, each within 0 to 1. This is the stop as drawn, with the palette and the text color already applied. ColorStop is the stop as the font holds it.

A plain #[repr(C)] value: build one by literal.

use daegun::color::gradient::Ramp;
use daegun::color::{Extend, Gradient, GradientKind, Rgba, Stop, IDENTITY};

let (red, blue) = (Rgba::opaque(255, 0, 0), Rgba::opaque(0, 0, 255));
// Red up to the middle, then blue: the two stops at 0.5 make a hard edge.
let stops = [
    Stop { offset: 0.0, color: red },
    Stop { offset: 0.5, color: red },
    Stop { offset: 0.5, color: blue },
    Stop { offset: 1.0, color: blue },
];
let line = GradientKind::Linear { x0: 0.0, y0: 0.0, x1: 100.0, y1: 0.0 };
let ramp = Ramp::new(&Gradient::new(line, &stops, Extend::Pad, IDENTITY), &IDENTITY);
assert_eq!(ramp.at(49.0, 0.0), Some(red));
assert_eq!(ramp.at(50.0, 0.0), Some(blue));
offset: f32
Where along the gradient the stop sits: 0 at its start, 1 at its end.
color: Rgba
The color at that point, straight sRGB.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
color::Stops
#[non_exhaustive]
pub enum Stops {
    Nothing,
    Solid(Rgba),
    Many(Vec<Stop>),
}

What a list of stops comes to once it is ready to draw: nothing, one flat color, or a real gradient.

Stops::resolve gives you one, and the three cases are the three things a renderer does: skip the fill, fill with one color, or set up a gradient. Ramp goes through the same step itself, so you need this only when you hand stops to a renderer of your own.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::color::{Extend, Rgba, Stop, Stops};

let stops = vec![
    Stop { offset: 0.0, color: Rgba::opaque(255, 0, 0) },
    Stop { offset: 1.0, color: Rgba::opaque(0, 0, 255) },
];
match Stops::resolve(stops, Extend::Pad) {
    Stops::Nothing => { /* skip the fill */ }
    Stops::Solid(color) => { /* fill with `color` */ }
    Stops::Many(stops) => {
        // Hand the stops, now in order, to your renderer's gradient.
        assert_eq!(stops.len(), 2);
    }
    _ => {}
}
Nothing
Nothing to paint. The list was empty, or its stops all sat at one offset under Extend::Repeat or Extend::Reflect.
Solid(Rgba)
One color everywhere. The list held a single stop, and this is its color: its offset and the extend no longer matter.
Many(Vec<Stop>)
Two or more stops, each offset clamped to 0 to 1 and the list sorted by offset. Stops that share an offset keep the order they came in.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Math

The MATH table, for setting formulas: its constants, each glyph's italic correction and kerning, and the larger variants and assemblies a stretched glyph is built from. In font units at a location. The calls are on Font, and their types are in daegun::math.

math::GlyphAssembly
#[non_exhaustive]
pub struct GlyphAssembly {
    pub italics_correction: f64,
    pub parts: Vec<GlyphPart>,
}

How to build a stretched glyph of any size from parts.

Where a glyph has to be larger than any ready-made variant, a math font gives parts to join: for a parenthesis, a bottom hook, a top hook and a straight piece to go between them. You find one in MathGlyphConstruction::assembly.

Lay the parts one after another along the direction of the stretch, in the order given: from the bottom up for a vertical glyph, from the left for a horizontal one. A part marked extender may be left out or repeated as often as needed, and every other part is used exactly once. Where there are several extenders, as in a brace, repeat each the same number of times. Each part starts where the one before it ends, less the overlap between the two.

The overlap at a join is yours to choose, within limits. It is at least what Font::math_min_connector_overlap gives, and at most the shorter of the two connectors that meet there: the end_connector_length of the first part and the start_connector_length of the next. So, for a size you need, take the fewest extenders whose longest build reaches it, then widen the overlaps evenly until the build comes down to that size.

It is #[non_exhaustive], so you read its fields and can't build one by literal.

use daegun::math::GlyphAssembly;
use daegun::{Location, Orientation};

let paren = font.glyph_id('(').ok_or("no parenthesis")?;
let assembly: GlyphAssembly = font
    .math_glyph_variants(paren, &Location::default(), Orientation::Vertical)
    .and_then(|stretch| stretch.assembly)
    .ok_or("no parts to build it from")?;
let overlap = font.math_min_connector_overlap().unwrap_or(0.0);

// The tallest glyph the parts make with each extender used `repeats` times: every advance
// added up, less the least overlap at each join.
let tallest = |repeats: u32| {
    let (mut laid, mut length) = (0, 0.0);
    for part in &assembly.parts {
        let times = if part.extender { repeats } else { 1 };
        laid += times;
        length += part.full_advance * f64::from(times);
    }
    length - overlap * f64::from(laid.saturating_sub(1))
};

// A parenthesis 5000 units tall is past every ready-made size. How many extenders does it take?
let repeats = (0..16).find(|&repeats| tallest(repeats) >= 5000.0);
// With STIX Two Math, three: two extenders reach 4750 units and three reach 5902.
assert_eq!(repeats, Some(3));
italics_correction: f64
The italic correction of the built glyph, in font units, whatever size it is built to. Use it as you would the answer of Font::math_italics_correction for a single glyph. It is the one value here that follows the location.
parts: Vec<GlyphPart>
The parts in the order they are laid: from the bottom for a vertical stretch, from the left for a horizontal one.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
math::GlyphPart
#[non_exhaustive]
pub struct GlyphPart {
    pub glyph: GlyphId,
    pub start_connector_length: f64,
    pub end_connector_length: f64,
    pub full_advance: f64,
    pub extender: bool,
}

One part of a glyph assembly: the glyph to draw, how long it is along the stretch, and how much of each end may overlap its neighbor.

A part is an ordinary glyph of the font, drawn like any other. What this adds is how parts join. Each end of a part has a connector, a length of plain straight stroke that can lie over the connector of the neighboring part without changing the shape.

The three lengths are in font units, measured along the direction of the stretch: heights in a vertical assembly, widths in a horizontal one. They are the same at every location. The parts come in GlyphAssembly::parts, which says how to lay them.

It is #[non_exhaustive], so you read its fields and can't build one by literal.

use daegun::math::GlyphPart;
use daegun::{Location, Orientation};

let paren = font.glyph_id('(').ok_or("no parenthesis")?;
let parts: Vec<GlyphPart> = font
    .math_glyph_variants(paren, &Location::default(), Orientation::Vertical)
    .and_then(|stretch| stretch.assembly)
    .ok_or("no parts to build it from")?
    .parts;

// STIX Two Math builds a parenthesis from three parts, bottom to top: the lower hook, a
// straight piece that may repeat, and the upper hook.
let repeats: Vec<bool> = parts.iter().map(|part| part.extender).collect();
assert_eq!(repeats, [false, true, false]);

// Where the lower hook meets the straight piece, the overlap can be no more than the shorter
// of the two connectors that meet: the end of the hook, 250 units, not the 1000 of the piece.
let (hook, piece) = (parts[0], parts[1]);
let most = hook.end_connector_length.min(piece.start_connector_length);
assert_eq!(most, 250.0);
glyph: GlyphId
The glyph to draw for this part.
start_connector_length: f64
The length of connector at the start of the part, its bottom or left end. The part before may overlap this one by up to that much.
end_connector_length: f64
The length of connector at the end of the part, its top or right end. The part after may overlap this one by up to that much.
full_advance: f64
The whole length of the part along the stretch. Laid with no overlap, the part would take this much.
extender: bool
True for a part that may be left out, or repeated any number of times, to reach the size. False for a part that is used exactly once.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
math::MathConstants
#[non_exhaustive]
pub struct MathConstants {
    pub script_percent_scale_down: f64,
    pub script_script_percent_scale_down: f64,
    pub delimited_sub_formula_min_height: f64,
    pub display_operator_min_height: f64,
    pub math_leading: f64,
    pub axis_height: f64,
    pub accent_base_height: f64,
    pub flattened_accent_base_height: f64,
    pub subscript_shift_down: f64,
    pub subscript_top_max: f64,
    pub subscript_baseline_drop_min: f64,
    pub superscript_shift_up: f64,
    pub superscript_shift_up_cramped: f64,
    pub superscript_bottom_min: f64,
    pub superscript_baseline_drop_max: f64,
    pub sub_superscript_gap_min: f64,
    pub superscript_bottom_max_with_subscript: f64,
    pub space_after_script: f64,
    pub upper_limit_gap_min: f64,
    pub upper_limit_baseline_rise_min: f64,
    pub lower_limit_gap_min: f64,
    pub lower_limit_baseline_drop_min: f64,
    pub stack_top_shift_up: f64,
    pub stack_top_display_style_shift_up: f64,
    pub stack_bottom_shift_down: f64,
    pub stack_bottom_display_style_shift_down: f64,
    pub stack_gap_min: f64,
    pub stack_display_style_gap_min: f64,
    pub stretch_stack_top_shift_up: f64,
    pub stretch_stack_bottom_shift_down: f64,
    pub stretch_stack_gap_above_min: f64,
    pub stretch_stack_gap_below_min: f64,
    pub fraction_numerator_shift_up: f64,
    pub fraction_numerator_display_style_shift_up: f64,
    pub fraction_denominator_shift_down: f64,
    pub fraction_denominator_display_style_shift_down: f64,
    pub fraction_numerator_gap_min: f64,
    pub fraction_num_display_style_gap_min: f64,
    pub fraction_rule_thickness: f64,
    pub fraction_denominator_gap_min: f64,
    pub fraction_denom_display_style_gap_min: f64,
    pub skewed_fraction_horizontal_gap: f64,
    pub skewed_fraction_vertical_gap: f64,
    pub overbar_vertical_gap: f64,
    pub overbar_rule_thickness: f64,
    pub overbar_extra_ascender: f64,
    pub underbar_vertical_gap: f64,
    pub underbar_rule_thickness: f64,
    pub underbar_extra_descender: f64,
    pub radical_vertical_gap: f64,
    pub radical_display_style_vertical_gap: f64,
    pub radical_rule_thickness: f64,
    pub radical_extra_ascender: f64,
    pub radical_kern_before_degree: f64,
    pub radical_kern_after_degree: f64,
    pub radical_degree_bottom_raise_percent: f64,
}

A math font's constants: the distances and percentages that say where each piece of a formula goes.

These are the numbers a font designer sets for formulas in their font: how far to raise a superscript, how thick to draw a fraction bar, how much room to leave over a root. A math layout reads them rather than guessing, so that a formula suits the font it is set in. Font::math_constants returns one with every field filled.

All but three fields are distances in font units, so a distance in pixels is value * px / f64::from(font.units_per_em()). The three are percentages: script_percent_scale_down, script_script_percent_scale_down and radical_degree_bottom_raise_percent. A height is measured up from the baseline, and a shift or a drop downward is a positive number. A value that places one element against a base, such as the shift of a superscript, is taken from the font of the base and scaled by the size of the base.

At a location of a variable font, each distance has its variation delta added and is not rounded, so it may carry a fraction. Five fields are plain numbers in the table and are the same at every location: the three percentages, delimited_sub_formula_min_height and display_operator_min_height.

Two terms come up in the fields. Display style is how a formula is set on a line of its own, with more room than one inside a paragraph. Cramped style is the tighter setting used where something lies overhead, as under a root sign or in a denominator.

The fields are named as the OpenType MATH table names its constants, and come in its order. The struct is #[non_exhaustive], so you read its fields and can't build one by literal.

use daegun::math::MathConstants;
use daegun::Location;

let constants: MathConstants =
    font.math_constants(&Location::default()).ok_or("the font has no MATH constants")?;

// A superscript on text of 20 px: the size to set it at, and how far to raise its baseline.
let px = 20.0;
let script_px = px * constants.script_percent_scale_down / 100.0;
let raise_px = constants.superscript_shift_up * px / f64::from(font.units_per_em());
// STIX Two Math sets scripts at 70 percent and raises them 360 units: 14 px text, 7.2 px up.
script_percent_scale_down: f64
The size to set a first-level script at, as a percentage of the size of the text it is attached to. A superscript or subscript on ordinary formula text is first level, and 70 means 70 percent. A percentage, not font units.
script_script_percent_scale_down: f64
The size to set a second-level script at, a script on a script, as a percentage. A percentage, not font units.
delimited_sub_formula_min_height: f64
The least height, in font units, of an expression inside delimiters such as parentheses for it to be treated as a sub-formula that the delimiters grow around.
display_operator_min_height: f64
The least height, in font units, of a big operator such as a sum or an integral in display style.
math_leading: f64
The white space, in font units, to leave between the bottom of one line of math and the top of the next, so that formulas set one under another keep their spacing.
axis_height: f64
How far the math axis lies above the baseline, in font units. The axis is the horizontal line that a minus sign, a fraction bar and a big operator are centered on.
accent_base_height: f64
The tallest a base may be, in font units, for an accent to sit over it at the height the font drew the accent. Over a taller base the accent has to be raised.
flattened_accent_base_height: f64
The tallest a base may be, in font units, and still take the ordinary form of an accent. A taller base takes the flattened form, a shallower drawing that some fonts keep for accents over capitals.
subscript_shift_down: f64
How far a subscript's baseline is set below the baseline of its base, in font units. Positive is down.
subscript_top_max: f64
The highest the top of a subscript may reach above the baseline, in font units. A subscript that would reach higher is moved further down.
subscript_baseline_drop_min: f64
The least distance, in font units, that a subscript's baseline is dropped below the bottom of its base. It is checked for a base that is a box or an extended shape, such as a tall delimiter.
superscript_shift_up: f64
How far a superscript's baseline is set above the baseline of its base, in font units.
superscript_shift_up_cramped: f64
How far a superscript's baseline is set above the baseline of its base in cramped style, in font units. It takes the place of superscript_shift_up there.
superscript_bottom_min: f64
The lowest the bottom of a superscript may sit above the baseline, in font units. A superscript that would sit lower is moved further up.
superscript_baseline_drop_max: f64
The most, in font units, that a superscript's baseline may lie below the top of its base. It is checked for a base that is a box or an extended shape, so that a superscript on a tall delimiter stays near its top.
sub_superscript_gap_min: f64
The least gap, in font units, between the bottom of a superscript and the top of a subscript on the same base.
superscript_bottom_max_with_subscript: f64
How high above the baseline, in font units, the bottom of a superscript may be pushed to open the gap to a subscript below it. Past that, the subscript is moved down instead.
space_after_script: f64
Extra white space, in font units, added after every superscript and subscript that follows its base, and before every one that is set before its base.
upper_limit_gap_min: f64
The least gap, in font units, between the bottom of an upper limit and the top of its operator. A limit is an expression set over or under a big operator, as the bounds of a sum are.
upper_limit_baseline_rise_min: f64
The least distance, in font units, from the top of an operator up to the baseline of its upper limit.
lower_limit_gap_min: f64
The least gap, in font units, between the top of a lower limit and the bottom of its operator.
lower_limit_baseline_drop_min: f64
The least distance, in font units, from the bottom of an operator down to the baseline of its lower limit.
stack_top_shift_up: f64
How far the baseline of a stack's top element is set above the baseline, in font units. A stack is one expression over another with no bar between, as in a binomial coefficient.
stack_top_display_style_shift_up: f64
How far the baseline of a stack's top element is set above the baseline in display style, in font units.
stack_bottom_shift_down: f64
How far the baseline of a stack's bottom element is set below the baseline, in font units. Positive is down.
stack_bottom_display_style_shift_down: f64
How far the baseline of a stack's bottom element is set below the baseline in display style, in font units. Positive is down.
stack_gap_min: f64
The least gap, in font units, between the bottom of a stack's top element and the top of its bottom element.
stack_display_style_gap_min: f64
The least gap between the two elements of a stack in display style, in font units.
stretch_stack_top_shift_up: f64
How far the element set over a stretched glyph is shifted up from the baseline, in font units. A stretch stack is a stretched glyph, such as a long arrow or a brace, with an expression over or under it.
stretch_stack_bottom_shift_down: f64
How far the element set under a stretched glyph is shifted down from the baseline, in font units. Positive is down.
stretch_stack_gap_above_min: f64
The least gap, in font units, between a stretched glyph and the bottom of the element set over it.
stretch_stack_gap_below_min: f64
The least gap, in font units, between a stretched glyph and the top of the element set under it.
fraction_numerator_shift_up: f64
How far a numerator's baseline is set above the baseline of its fraction, in font units.
fraction_numerator_display_style_shift_up: f64
How far a numerator's baseline is set above the baseline of its fraction in display style, in font units.
fraction_denominator_shift_down: f64
How far a denominator's baseline is set below the baseline of its fraction, in font units. Positive is down.
fraction_denominator_display_style_shift_down: f64
How far a denominator's baseline is set below the baseline of its fraction in display style, in font units. Positive is down.
fraction_numerator_gap_min: f64
The least gap, in font units, between the bottom of a numerator and the fraction bar.
fraction_num_display_style_gap_min: f64
The least gap between the bottom of a numerator and the fraction bar in display style, in font units.
fraction_rule_thickness: f64
How thick the fraction bar is, in font units.
fraction_denominator_gap_min: f64
The least gap, in font units, between the fraction bar and the top of a denominator.
fraction_denom_display_style_gap_min: f64
The least gap between the fraction bar and the top of a denominator in display style, in font units.
skewed_fraction_horizontal_gap: f64
The horizontal distance, in font units, between the numerator and the denominator of a skewed fraction: one set on a slant, the numerator raised before a slash and the denominator lowered after it.
skewed_fraction_vertical_gap: f64
The vertical distance, in font units, between the numerator and the denominator of a skewed fraction.
overbar_vertical_gap: f64
The gap, in font units, between an overbar and the top of the expression it is drawn over.
overbar_rule_thickness: f64
How thick an overbar is, in font units.
overbar_extra_ascender: f64
White space, in font units, kept clear above an overbar.
underbar_vertical_gap: f64
The gap, in font units, between an underbar and the bottom of the expression it is drawn under.
underbar_rule_thickness: f64
How thick an underbar is, in font units.
underbar_extra_descender: f64
White space, in font units, kept clear below an underbar.
radical_vertical_gap: f64
The gap, in font units, between the top of the expression under a root sign and the bar over it.
radical_display_style_vertical_gap: f64
The gap between the top of the expression under a root sign and the bar over it in display style, in font units.
radical_rule_thickness: f64
How thick the bar over a root is, in font units, which is the thickness of the bar drawn into the root sign glyphs.
radical_extra_ascender: f64
White space, in font units, kept clear above the bar of a root.
radical_kern_before_degree: f64
Horizontal space, in font units, added before the degree of a root. The degree is the small index, as the 3 of a cube root.
radical_kern_after_degree: f64
Horizontal space, in font units, added after the degree of a root. It is normally negative, which draws the root sign back under the degree.
radical_degree_bottom_raise_percent: f64
How high the bottom of a root's degree is raised, as a percentage of the height of the root sign. A percentage, not font units.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
math::MathGlyphConstruction
#[non_exhaustive]
pub struct MathGlyphConstruction {
    pub assembly: Option<GlyphAssembly>,
    pub variants: Vec<MathGlyphVariant>,
}

How one glyph stretches in one direction: its ready-made sizes, and the parts to build it larger.

What Font::math_glyph_variants returns. Try variants first: each is a whole glyph the designer drew at that size, so it looks best. Go to assembly for a size past the largest variant.

A font may give a glyph sizes alone, parts alone or both, so variants may be empty and assembly may be None.

It is #[non_exhaustive], so you read its fields and can't build one by literal.

use daegun::math::MathGlyphConstruction;
use daegun::{Location, Orientation};

let at = Location::default();
let brace = font.glyph_id('{').ok_or("no brace")?;
let stretch: MathGlyphConstruction =
    font.math_glyph_variants(brace, &at, Orientation::Vertical).ok_or("it does not stretch")?;

// STIX Two Math draws 13 sizes of the brace, the first of them the brace itself, and gives
// parts to go past the largest.
assert_eq!(stretch.variants.len(), 13);
assert_eq!(stretch.variants[0].glyph, brace);
assert!(stretch.assembly.is_some());

// Its summation sign comes in two sizes, with no parts.
let sum = font.glyph_id('∑').ok_or("no summation sign")?;
let sizes = font.math_glyph_variants(sum, &at, Orientation::Vertical).ok_or("it does not stretch")?;
assert_eq!(sizes.variants.len(), 2);
assert!(sizes.assembly.is_none());
assembly: Option<GlyphAssembly>
The parts to build the glyph at any size, a GlyphAssembly. None where the font gives ready-made sizes only.
variants: Vec<MathGlyphVariant>
The ready-made sizes, in the order the font lists them, which daegun does not sort. STIX Two Math lists the glyph itself first, then each larger size.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
math::MathGlyphVariant
#[non_exhaustive]
pub struct MathGlyphVariant {
    pub glyph: GlyphId,
    pub advance: f64,
}

One ready-made size of a glyph that stretches: the glyph to draw, and how much it covers along the stretch.

A variant is a glyph in its own right, with its own outline and metrics, so you draw it as you would any glyph. advance is what you compare with the size you need. They come in MathGlyphConstruction::variants.

It is #[non_exhaustive], so you read its fields and can't build one by literal.

use daegun::math::MathGlyphVariant;
use daegun::{Location, Orientation};

// A brace over a formula stretches sideways, so its sizes are widths.
let brace = font.glyph_id('⏞').ok_or("no brace")?;
let stretch = font
    .math_glyph_variants(brace, &Location::default(), Orientation::Horizontal)
    .ok_or("it does not stretch")?;

// To span terms 1600 units wide, take the first size that is wide enough.
let fit: Option<&MathGlyphVariant> = stretch.variants.iter().find(|variant| variant.advance >= 1600.0);
// STIX Two Math draws six widths, and the fourth, 1771 units wide, is the first past 1600.
if let Some(variant) = fit {
    // Draw variant.glyph.
}
glyph: GlyphId
The glyph that draws this size.
advance: f64
How much the glyph covers along the direction of the stretch, in font units: its height for a vertical stretch, its width for a horizontal one. It is the same at every location.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
math::MathKernCorner
pub enum MathKernCorner {
    TopRight,
    TopLeft,
    BottomRight,
    BottomLeft,
}

One of the four corners of a glyph where a subscript or superscript can meet it, for Font::math_kern.

A font can give each corner of a glyph its own kerns. The right-hand corners serve a glyph as a base: a superscript meets it at the top right, a subscript at the bottom right. The left-hand corners serve a glyph as a script: a superscript turns its bottom left corner to its base, and a subscript its top left. They also serve a base whose scripts are set before it.

To kern a base and a script, add the base's kern at its corner to the script's kern at the corner facing it.

The enum is complete. The MATH table has these four corners and no others, so a match on it needs no _ arm.

use daegun::math::MathKernCorner;
use daegun::Location;

let at = Location::default();
// An italic T as a base. Its scripts meet it at its right-hand corners.
let t = font.glyph_id('𝑇').ok_or("no italic T")?;

// A subscript set low slides in under the arm of the T. One that reaches up to the arm is
// pushed clear of it.
assert_eq!(font.math_kern(t, &at, MathKernCorner::BottomRight, 200.0)?, -100.0);
assert_eq!(font.math_kern(t, &at, MathKernCorner::BottomRight, 400.0)?, 114.0);
// A superscript is moved 30 units clear of the arm.
assert_eq!(font.math_kern(t, &at, MathKernCorner::TopRight, 400.0)?, 30.0);

// STIX Two Math gives this T nothing at its left-hand corners, so they answer 0.
assert_eq!(font.math_kern(t, &at, MathKernCorner::TopLeft, 400.0)?, 0.0);
assert_eq!(font.math_kern(t, &at, MathKernCorner::BottomLeft, 400.0)?, 0.0);
TopRight
The top right corner, where a superscript after the glyph meets it.
TopLeft
The top left corner, where a superscript set before the glyph meets it. It is also the corner the glyph turns to its base when it is itself a subscript.
BottomRight
The bottom right corner, where a subscript after the glyph meets it.
BottomLeft
The bottom left corner, where a subscript set before the glyph meets it. It is also the corner the glyph turns to its base when it is itself a superscript.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Tables

What a font offers and what can be made of it: the scripts, language systems and features its GSUB and GPOS tables offer, BASE baselines and extents, and subsetting with its glyph closure. The calls are on Font, and their types are in daegun::tables.

tables::BaseScript
#[non_exhaustive]
pub struct BaseScript {
    pub default_baseline: Option<Tag>,
    pub baselines: BTreeMap<Tag, f64>,
}

A script's baselines along one orientation, as the font's BASE table gives them.

What Font::base_script returns. baselines maps each baseline tag the font gives the script to its position, and default_baseline names the one the script's glyphs are made to sit on.

To line up text of two scripts, or of one script at two sizes, pick a baseline tag, most often the default baseline of the line's main script, and shift each run so that its position for that tag lands on the same line. Positions are in font units, so scale each by the size its run is set at.

It is #[non_exhaustive] and has no constructor: one comes from Font::base_script and is there to read.

use daegun::tables::BaseScript;
use daegun::{Location, Orientation, Tag};

let base: BaseScript = font
    .base_script(Tag::new(b"kana"), &Location::default(), Orientation::Vertical)
    .expect("Source Han Sans has vertical baselines");

// Kana sits on the ideographic baseline. Down a vertical line the positions are x values:
// that baseline is at 0, and the roman one 120 units to its right.
assert_eq!(base.default_baseline, Some(Tag::new(b"ideo")));
assert_eq!(base.baselines[&Tag::new(b"ideo")], 0.0);
assert_eq!(base.baselines[&Tag::new(b"romn")], 120.0);

for (tag, position) in &base.baselines {
    // In tag order: icfb 53, icft 947, ideo 0, romn 120.
}
default_baseline: Option<Tag>
The tag of the baseline the script's glyphs sit on, such as romn for Latin or ideo for Han. None where the table names none for the script.
baselines: BTreeMap<Tag, f64>
The position of each baseline by its tag, in font units: a y value for horizontal text, an x value for vertical text. A BTreeMap, so it iterates in tag order.
  • Implements: Clone, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
tables::Extents
#[non_exhaustive]
pub struct Extents {
    pub min: Option<f64>,
    pub max: Option<f64>,
}

How far a script's glyphs reach to either side of the line, as the font's BASE table states it.

What Font::base_extents returns. For horizontal text min is the lowest y the glyphs reach and max the highest. For vertical text they are the leftmost and the rightmost x. Both are in font units, in the glyphs' own coordinates, so a min below the baseline is negative.

Each side is an Option, since a font may state one and not the other. The type is #[non_exhaustive]: read its fields, and write .. when you take it apart in a pattern. Extents::default() is one with neither side.

use daegun::tables::Extents;
use daegun::{Location, Orientation, Tag};

let at = Location::default();
let extents = font.base_extents(Tag::new(b"hani"), &at, Orientation::Horizontal, None, None);
// Take each side from BASE where it states one, and from the font's line metrics where not.
let Extents { min, max, .. } = extents.unwrap_or_default();
let bottom = min.unwrap_or_else(|| font.descender(&at));
let top = max.unwrap_or_else(|| font.ascender(&at));
// Source Han Sans states no extents for Han, so these are its descender and ascender:
// -288 and 1160.
assert_eq!((bottom, top), (-288.0, 1160.0));
min: Option<f64>
The lowest point the glyphs reach: a y value in horizontal text, the leftmost x in vertical text. None where the font states no minimum.
max: Option<f64>
The highest point the glyphs reach: a y value in horizontal text, the rightmost x in vertical text. None where the font states no maximum.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
tables::Subset
pub struct Subset {
    pub font: Vec<u8>,
    /* private fields */
}

A subset font: the bytes of its font file, and where each glyph of the source went in it.

What Font::subset and Font::subset_text return. Subset::font is a complete font file in the flavor of its source: TrueType outlines stay TrueType, and CFF or CFF2 outlines stay what they were. Write it to disk, serve it as a web font, or open it again with Font::from_bytes.

The file is static. It holds one location of a variable font, the one the call was given, and no variation tables.

Its glyph ids are in most cases not the source's. Whatever you hold in source ids, such as the glyphs of a shaped run, goes through Subset::renumbered before you use it with the subset.

You get one from those two calls only. It has a private part, the renumbering, so it cannot be built by literal.

use daegun::tables::Subset;
use daegun::{Font, Location, Orientation, Tag};

let bold = font.location(&[(Tag::new(b"wght"), 700.0)]);
let subset: Subset = font.subset_text("Wave", &bold)?;

// The file is a static font: Inter at weight 700 and nowhere else.
let small = Font::from_bytes(&subset.font)?;
assert!(font.is_variable() && !small.is_variable());

// Read at its one location, its W is as wide as Inter's W at weight 700: 2125 units, where
// the regular weight has 2018.
let w = font.glyph_id('W').expect("Inter has a W");
let moved = subset.renumbered(w).expect("the W is kept");
let advance = small.advance(moved, &Location::default(), Orientation::Horizontal);
assert_eq!(advance, font.advance(w, &bold, Orientation::Horizontal));
font: Vec<u8>
The bytes of the subset font file. The field is public, so you can move the Vec out without a copy once you are done with Subset::renumbered.
  • Implements: Clone, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Raw tables

Font data at the byte level, for tools that read or write a table daegun has no call for: reads and writes that never panic, the structures several tables share, loca and glyf, and building a font file from its tables. In daegun::raw.

raw::format::AnchorPoint
pub struct AnchorPoint {
    pub x: i16,
    pub y: i16,
}

A point in font units, y up, as Apple's ankr table stores a glyph's anchor and a kerx action stores a control point.

An anchor is a spot on a glyph that another glyph is attached by, as a mark is hung on its base. Apple's fonts list the anchors of each glyph in ankr, and their kerx table attaches glyphs by them. Ankr::anchor_point returns one by glyph and index, and raw::format::control_point reads one from any four bytes.

It is a plain pair with public fields, so you can build one by literal and compare two with ==. AnchorPoint::default() is the origin. Both fields are whole font units, exactly as the font stores them.

use daegun::raw::format::{control_point, AnchorPoint};

// Four bytes hold a point: x then y, each a big-endian signed 16-bit number.
let stored = [0x01, 0x2C, 0xFF, 0x9C];
let point: AnchorPoint = control_point(&stored, 0).ok_or("cut short")?;
assert_eq!(point, AnchorPoint { x: 300, y: -100 });
x: i16
Across, in font units. A larger value is further right.
y: i16
Up, in font units. A larger value is higher.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::Ankr
pub struct Ankr<'a> {
    /* private fields */
}

Apple's ankr table: the anchor points of each glyph, which a kerx table attaches one glyph to another by.

An anchor point is a spot on a glyph, in font units with y up, where another glyph can be attached: the top of a letter where a mark sits, say. A kerx subtable that attaches by anchors names two of them by index, one on each glyph, and the glyph being attached is moved until the two meet.

The table is a header, an AAT lookup that maps each glyph to where its points are stored, and the points themselves. Ankr::parse reads the header, Ankr::point_count says how many points a glyph has, and Ankr::anchor_point returns one as an AnchorPoint.

Give it the whole table, as Font::table returns it for the tag ankr. An Ankr borrows those bytes and is Copy. To read one point at an offset you already know, in ankr or in a kerx action, there is raw::format::control_point.

use daegun::raw::format::{AnchorPoint, Ankr};
use daegun::Tag;

// A font's table comes from font.table(Tag::new(b"ankr")). Inter has none, so here is one written
// out by hand, as 16-bit words, for a font of 3 glyphs. Glyph 2 has two anchor points.
assert!(font.table(Tag::new(b"ankr")).is_none());
let words: [u16; 16] = [
    0, 0,         // version 0, flags 0
    0, 12, 0, 20, // the lookup is at byte 12, the points at byte 20
    8, 2, 1, 0,   // a lookup of format 8: from glyph 2, one glyph, its points 0 bytes in
    0, 2,         // two points
    100, 700,     // (100, 700)
    0xFFCE, 0,    // (-50, 0)
];
let table: Vec<u8> = words.iter().flat_map(|word| word.to_be_bytes()).collect();

let ankr = Ankr::parse(&table, 3)?;
assert_eq!(ankr.point_count(2), 2);
assert_eq!(ankr.anchor_point(2, 0), Some(AnchorPoint { x: 100, y: 700 }));
assert_eq!(ankr.anchor_point(2, 1), Some(AnchorPoint { x: -50, y: 0 }));
// Glyph 1 is not in the table.
assert_eq!(ankr.point_count(1), 0);
  • Implements: Clone, Copy, Debug.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::DeltaSetIndex
pub struct DeltaSetIndex {
    pub outer: u32,
    pub inner: u32,
}

Where an item's deltas lie in an ItemVariationStore: which of its subtables, and which row there.

A variable font keeps its deltas, the amounts its values change by as an axis moves, in a store of subtables, each a grid with a row per item. An item is whatever the table varies, such as the advance of a glyph in HVAR. This pair names one row.

raw::format::parse_delta_set_index_map reads the list of them a table holds, raw::format::delta_set_index_map_lookup picks the one for an item, and ItemVariationStore::delta turns it into the delta at a location.

It is a plain pair with public fields, so you can build one by literal where a table names a row without a map. In an HVAR that has no map, glyph g is DeltaSetIndex { outer: 0, inner: g }, which is also what raw::format::delta_set_index_map_lookup answers for an empty map.

use daegun::raw::bytes::read_u32_be;
use daegun::raw::format::{delta_set_index_map_lookup, parse_delta_set_index_map, DeltaSetIndex};
use daegun::Tag;

let hvar = font.table(Tag::new(b"HVAR")).ok_or("no HVAR")?;
// HVAR keeps the offset of its advance width map at byte 8.
let map_at = read_u32_be(hvar, 8).ok_or("HVAR cut short")? as usize;
let map = parse_delta_set_index_map(hvar, map_at)?;

let h = font.glyph_id('H').ok_or("no H")?;
let index: DeltaSetIndex = delta_set_index_map_lookup(&map, h.0 as usize);
// Inter keeps the deltas of the H's advance in row 136 of subtable 1.
assert_eq!(index, DeltaSetIndex { outer: 1, inner: 136 });

let (outer, inner): (usize, usize) = index.into();
assert_eq!((outer, inner), (1, 136));
outer: u32
Which subtable: an index into ItemVariationStore::ivd_data.
inner: u32
Which row of that subtable: the index Ivd::row takes.
impl From<DeltaSetIndex> for (usize, usize)
The pair as (outer, inner), each widened to usize, ready to index with.
  • Implements: Clone, Copy, Debug, Default, Eq, From<DeltaSetIndex> for (usize, usize), Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::Entry
pub struct Entry {
    pub new_state: u16,
    pub flags: u16,
    pub word1: u16,
    pub word2: u16,
}

One entry of an extended AAT state table: the state to go to next, flags, and up to two extra words.

A state table drives a small machine along the glyphs of a run, which is how Apple's morx and kerx tables substitute and kern. At each glyph the machine reads the entry for the state it is in and the class of the glyph, acts on it, and moves to new_state. StateTable::entry returns one.

daegun reads the fields and leaves their meaning to you, since each kind of table defines its own flags and its own extra words. How many extra words an entry has is the extra_words you gave StateTable::parse: in morx, none for a rearrangement subtable, one for a ligature subtable and two for a contextual or an insertion subtable, and one in a kerx state table.

It is a plain record with public fields, laid out as C reads it (#[repr(C)]). Entry::default() is all zeros.

use daegun::raw::bytes::read_u32_be;
use daegun::raw::format::{state, Entry, StateTable};
use daegun::Tag;

let morx = font.table(Tag::new(b"morx")).ok_or("no morx")?;
// This test font's one morx subtable starts at byte 48: a 12-byte header, then a contextual state
// table, whose entries carry two extra words.
let length = read_u32_be(morx, 48).ok_or("morx cut short")? as usize;
let body = morx.get(60..48 + length).ok_or("morx cut short")?;
let table = StateTable::parse(body, 2, font.glyph_count())?;

let a = font.glyph_id('A').ok_or("no A")?;
let entry: Entry = table.entry(state::START_OF_TEXT, table.class(a.0)).ok_or("no entry")?;
// Meeting an A in the start state: stay in state 0, with flags 0x4000 and the words 0xFFFF and 0.
assert_eq!(entry, Entry { new_state: 0, flags: 0x4000, word1: 0xFFFF, word2: 0 });
new_state: u16
The state the machine goes to after this entry, as a row of the state array. Pass it to StateTable::entry for the next glyph.
flags: u16
The entry's flags. Each kind of table defines its own bits, and one is the same in all of them: 0x4000 tells the machine not to advance, so it reads the same glyph again in its new state.
word1: u16
The first extra word after the flags. 0 where the table was parsed with no extra words.
word2: u16
The second extra word. 0 where the table was parsed with fewer than two.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::FeatureVariations
pub struct FeatureVariations<'a> {
    /* private fields */
}

A FeatureVariations table: the part of GSUB or GPOS that lets a variable font swap a feature for another in part of its design space.

A variable font sometimes needs different glyphs or spacing in one part of its design space, such as a simpler form of a letter once the weight gets heavy. FeatureVariations does that with the machinery the font already has. The table is a list of records. Each record has a set of conditions on the axes, and a list of substitutions that replace some of the layout table's features with alternate feature tables while the conditions hold.

Reading one takes three steps. FeatureVariations::parse finds the table from the header of a GSUB or GPOS table. FeatureVariations::find picks the record that applies at a location. FeatureVariations::substitute then says, for one feature, what that record puts in its place. Shaping does all of this by itself: the type is for a tool that inspects or rewrites the table.

It borrows the layout table's bytes and is Copy. Nothing is checked ahead of time. An offset that leads outside the table reads as nothing there, so a damaged table never panics: FeatureVariations::find answers None once it needs bytes that are missing. A record with a null condition set needs none past its own, so a table cut short after that record still finds it.

use daegun::raw::format::{FeatureVariations, Substitution};
use daegun::Tag;

// A font's table comes from font.table(Tag::new(b"GSUB")). Inter's has no FeatureVariations, so
// here is a GSUB header with one, written out by hand as 16-bit words. Its one record replaces
// feature 3 where the second axis is at 0.5 or more, in normalized coordinates.
let words: [u16; 30] = [
    1, 1, 0, 0, 0, 0, 14,     // version 1.1, no lists, and FeatureVariations at byte 14
    1, 0, 0, 1, 0, 16, 0, 30, // one record: its conditions 16 bytes on, its substitutions 30
    1, 0, 6,                  // one condition, 6 bytes on
    1, 1, 8192, 16384,        // axis 1 from 0.5 to 1
    1, 0, 1, 3, 0, 12,        // one substitution: feature 3, by the feature table 12 bytes on
    0, 0,                     // which has no lookups
];
let gsub: Vec<u8> = words.iter().flat_map(|word| word.to_be_bytes()).collect();
let variations = FeatureVariations::parse(&gsub).expect("a 1.1 header that names one");

// Inter's second axis is weight. At its heaviest the record applies.
let heavy = font.location(&[(Tag::new(b"wght"), 900.0)]);
let coords: Vec<i32> = heavy.normalized().iter().map(|&v| (v * 16384.0).round() as i32).collect();
let record = variations.find(&coords, None).expect("a record that holds at this weight");
// It swaps feature 3 for the feature table at byte 56 of the GSUB.
assert_eq!(variations.substitute(record, 3), Some(Substitution::Feature(56)));
// At the default weight no record applies, and the font's own features stand.
assert_eq!(variations.find(&[], None), None);
  • Implements: Clone, Copy, Debug.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::GlyphValue
pub struct GlyphValue {
    pub glyph: u32,
    pub value: u16,
}

A glyph and the 16-bit value an AAT lookup table maps it to.

Lookup::entries returns one for each glyph a lookup lists. What the value means depends on where the lookup sits: the replacement glyph in a non-contextual morx subtable, a class in the class table of a state table, an offset into the anchor data in ankr.

It is a plain pair with public fields, laid out as C reads it (#[repr(C)]).

use daegun::raw::bytes::read_u32_be;
use daegun::raw::format::{GlyphValue, Lookup};
use daegun::Tag;

let morx = font.table(Tag::new(b"morx")).ok_or("no morx")?;
// This test font's one morx subtable starts at byte 48: a 12-byte header, then a lookup that maps
// each glyph it lists to the glyph that replaces it.
let length = read_u32_be(morx, 48).ok_or("morx cut short")? as usize;
let body = morx.get(60..48 + length).ok_or("morx cut short")?;
let lookup = Lookup::parse(body, font.glyph_count())?;

let entries: Vec<GlyphValue> = lookup.entries();
// Glyph 2, the A, becomes glyph 5, an alternate A, and glyph 4, the C, becomes glyph 7.
assert_eq!(entries, [GlyphValue { glyph: 2, value: 5 }, GlyphValue { glyph: 4, value: 7 }]);
glyph: u32
The glyph id. A lookup stores ids in 16 bits, so it is never above 65,535.
value: u16
What the lookup maps the glyph to, the same value Lookup::value answers for it.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::ItemVariationStore
#[non_exhaustive]
pub struct ItemVariationStore {
    pub regions:    Vec<Vec<RegionAxis>>,
    pub ivd_data:   Vec<Ivd>,
    pub axis_count: usize,
}

An ItemVariationStore, decoded: the regions of a variable font's design space and, for each value that varies, how much it changes in each region.

A variable font stores most of its variation this way. A region is a part of the design space with a peak where its effect is whole, such as the heavy end of the weight axis. An item is one value that varies, such as a glyph's advance, and it has a row of deltas, one for each region it responds to. At a location each region has a scalar from 0 to 1 for how strongly it applies there, and the item's change is its deltas, each weighted by its region's scalar, added up.

The same structure sits in several tables, among them HVAR and VVAR for advances, MVAR for the metrics of the font as a whole, GDEF for what GPOS positions, and COLR. Each says in its own header where its store starts, and each has its own way to name an item. In the store an item is a pair, a DeltaSetIndex: the outer index picks a subtable and the inner index a row in it. HVAR and VVAR may go from a glyph to its pair through a map, which raw::format::parse_delta_set_index_map reads and raw::format::delta_set_index_map_lookup looks a glyph up in. One with no map uses outer 0 and the glyph id as the inner index.

ItemVariationStore::parse decodes the whole store into memory. Unlike Lookup, StateTable, Ankr and FeatureVariations, it borrows nothing, and owns what it read. Then ItemVariationStore::region_scalars works out the scalars once for a location, and ItemVariationStore::delta reads any number of items with them.

The type is #[non_exhaustive]. Read its fields as you like, but get one from ItemVariationStore::parse, or start from ItemVariationStore::default(), which is empty, and set the fields.

use daegun::raw::bytes::read_u32_be;
use daegun::raw::format::{delta_set_index_map_lookup, parse_delta_set_index_map, ItemVariationStore};
use daegun::{Location, Orientation, Tag};

// HVAR varies the advances. Its header holds the offset of its store at byte 4, and at byte 8
// the offset of the map from a glyph to its item.
let hvar = font.table(Tag::new(b"HVAR")).expect("Inter is variable");
let store = ItemVariationStore::parse(hvar, read_u32_be(hvar, 4).expect("a header") as usize)?;
let map = parse_delta_set_index_map(hvar, read_u32_be(hvar, 8).expect("a header") as usize)?;

// How far the advance of A moves at Inter's heaviest weight.
let a = font.glyph_id('A').expect("an A");
let heavy = font.location(&[(Tag::new(b"wght"), 900.0)]);
let scalars = store.region_scalars(heavy.normalized());
let delta = store.delta(delta_set_index_map_lookup(&map, a.0 as usize), &scalars);
// 215 units: its advance is 1413 at the default weight and 1628 at the heaviest.
assert_eq!(delta, 215.0);
regions: Vec<Vec<RegionAxis>>
Every region of the store. A region is a list of one RegionAxis for each axis, in the order of the font's fvar table. An axis the region does not depend on has a peak of 0.
ivd_data: Vec<Ivd>
The store's ItemVariationData subtables, each an Ivd. The outer half of a DeltaSetIndex is an index into this list. A subtable the store names but that could not be read is here as an empty one, so the indices still line up.
axis_count: usize
How many axes each region has, as the store's list of regions states it. It is 0 where that list could not be read.
  • Implements: Clone, Debug, Default.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::Ivd
pub struct Ivd {
    pub region_indices: Vec<usize>,
    /* private fields */
}

One ItemVariationData subtable of a store: a grid of deltas with a row for each item and a column for each region the subtable uses.

A store splits its items among subtables so that each can list only the regions its own items respond to. You reach one through ItemVariationStore::ivd_data, by the outer half of a DeltaSetIndex. The inner half is the row.

Ivd::rows is how many items it holds, and Ivd::row returns one item's deltas, which line up with region_indices entry for entry. To turn a row into a change at a location you don't have to read it yourself: ItemVariationStore::delta does the weighting.

The deltas are widened to i32, whatever width the font stored them in. A subtable comes from parsing a store. The only one you can make yourself is Ivd::default(), which is empty.

use daegun::raw::bytes::read_u32_be;
use daegun::raw::format::{ItemVariationStore, Ivd};
use daegun::Tag;

// The store of Inter's HVAR table, whose offset is at byte 4 of the table.
let hvar = font.table(Tag::new(b"HVAR")).expect("Inter is variable");
let store = ItemVariationStore::parse(hvar, read_u32_be(hvar, 4).expect("a header") as usize)?;

// Subtable 3 has 148 rows, and its columns are regions 2, 0, 1, 3 and 4 of the store.
let ivd: &Ivd = &store.ivd_data[3];
assert_eq!(ivd.rows(), 148);
assert_eq!(ivd.region_indices, [2, 0, 1, 3, 4]);

// Row 46 is the advance of A. Its first delta is for region 2, the heavy side of weight: 215.
assert_eq!(ivd.row(46), Some(&[215, -75, -103, -17, 12][..]));
region_indices: Vec<usize>
For each column, the index of its region in ItemVariationStore::regions. Column j of every row is the delta for region region_indices[j].
  • Implements: Clone, Debug, Default.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::Lookup
pub struct Lookup<'a> {
    /* private fields */
}

An AAT lookup table: the structure Apple's layout tables use to map a glyph to a 16-bit value.

AAT is Apple's family of layout tables, morx and kerx among them, and many of them hold lookups. A morx substitution maps a glyph to the glyph that replaces it, a state table maps a glyph to its class, and ankr maps a glyph to where its anchor points are stored. A font may store a lookup in any of six formats, numbered 0, 2, 4, 6, 8 and 10, and this type reads them all.

daegun has no call that finds a lookup for you. Take the bytes of the table from Font::table, work out from its headers where the lookup starts, and hand Lookup::parse the bytes from there on. Lookup::value then answers for one glyph, and Lookup::entries lists every glyph the lookup covers.

A Lookup is a view of the bytes: it borrows them, copies nothing and is Copy. Little is checked up front. Bytes that are cut short or out of order show up later, as a glyph that reads None.

use daegun::raw::format::Lookup;
use daegun::{GlyphId, Tag};

// TestMORXOne.ttf has one morx subtable, a substitution with no context, and its body is a lookup.
// The body starts 60 bytes into morx: past the table's header (8 bytes), the chain's (16), two
// feature entries (12 each) and the subtable's header (12).
let morx = font.table(Tag::new(b"morx")).expect("an AAT font");
let lookup = Lookup::parse(&morx[60..], font.glyph_count())?;

// It maps A to the glyph that replaces it, and has nothing for B.
let a = font.glyph_id('A').expect("an A");
let b = font.glyph_id('B').expect("a B");
let replacement = lookup.value(a.0).expect("A is listed");
assert_eq!(font.glyph_name(GlyphId(replacement.into())), Some("A.alt"));
assert_eq!(lookup.value(b.0), None);
  • Implements: Clone, Copy, Debug.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::RegionAxis
pub struct RegionAxis {
    pub start: f64,
    pub peak: f64,
    pub end: f64,
}

One axis of a variation region: where along the axis the region's influence starts, peaks and ends, in normalized coordinates.

A region is the part of a variable font's design space that one column of deltas applies in. It has one RegionAxis for each axis of the font, in the font's axis order. Along an axis the influence rises from 0 at start to 1 at peak and falls back to 0 at end, and the scalar of the whole region at a location is the product over its axes, which ItemVariationStore::region_scalars works out.

Normalized coordinates run from -1 at the minimum of an axis through 0 at its default to 1 at its maximum. Location::normalized gives those of a location.

ItemVariationStore::regions holds them: regions[r][a] is axis a of region r. The values are the font's 2.14 fixed-point numbers as f64. It is a plain record with public fields, laid out as C reads it (#[repr(C)]).

use daegun::raw::bytes::read_u32_be;
use daegun::raw::format::{ItemVariationStore, RegionAxis};
use daegun::Tag;

let hvar = font.table(Tag::new(b"HVAR")).ok_or("no HVAR")?;
// HVAR keeps the offset of its ItemVariationStore at byte 4.
let store_at = read_u32_be(hvar, 4).ok_or("HVAR cut short")? as usize;
let store = ItemVariationStore::parse(hvar, store_at)?;

// Inter has two axes, opsz then wght. Region 2 leaves opsz out and covers the heavy side of wght:
// no influence at the default weight, all of it at the heaviest.
let region: &[RegionAxis] = &store.regions[2];
assert_eq!(region[0], RegionAxis { start: 0.0, peak: 0.0, end: 0.0 });
assert_eq!(region[1], RegionAxis { start: 0.0, peak: 1.0, end: 1.0 });
start: f64
The coordinate where its influence starts to rise from 0.
peak: f64
The coordinate where its influence is whole, a scalar of 1. A peak of 0 means the region does not depend on this axis.
end: f64
The coordinate where its influence has fallen back to 0.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::StateTable
pub struct StateTable<'a> {
    /* private fields */
}

An extended AAT state table: the machine that a morx or kerx subtable runs over a line of glyphs.

Apple's contextual tables are written as state machines. A machine walks the glyphs in order. Every glyph has a class, a small number that groups the glyphs the machine treats alike. The machine is always in one state, and begins in raw::format::state::START_OF_TEXT. For the state it is in and the class of the glyph it is on, the table gives an entry: the state to go to next, flags, and up to two more words that say what to do, such as which substitution to apply.

This type reads those parts and no more. StateTable::class gives a glyph's class and StateTable::entry the entry for a state and a class, as an Entry. Running the machine and acting on the flags, whose meaning each kind of subtable defines, is yours to do.

The format fixes the first classes. raw::format::class::END_OF_TEXT, 0, is what a machine is handed once it is past the last glyph. Class 1 is a glyph the class table doesn't list, known as out of bounds. raw::format::class::DELETED_GLYPH, 2, is glyph 0xFFFF, the mark a deleted glyph leaves behind.

It reads the extended form, whose header is four 32-bit words, as morx and kerx hold it. The older 16-bit form in Apple's kern table is laid out differently, and this type does not read it. A StateTable borrows the bytes it was parsed from and is Copy.

use daegun::raw::format::{state, StateTable};
use daegun::Tag;

// TestMORXThirtythree.ttf has one morx subtable, an insertion that turns "ha" into "haha". Its
// body opens with the state table, 60 bytes into morx. An insertion entry has 2 extra words.
let morx = font.table(Tag::new(b"morx")).expect("an AAT font");
let table = StateTable::parse(&morx[60..], 2, font.glyph_count())?;
let h = font.glyph_id('h').expect("an h");
let a = font.glyph_id('a').expect("an a");

// From the start state an h sends the machine to state 1 and does nothing else.
let on_h = table.entry(state::START_OF_TEXT, table.class(h.0)).expect("an entry");
assert_eq!((on_h.new_state, on_h.flags), (1, 0));

// In state 1 an a meets the entry that inserts. Its flags hold a count of 2 and its first extra
// word an index of 0: put the first two glyphs of the subtable's insertion list after the a.
let on_a = table.entry(on_h.new_state, table.class(a.0)).expect("an entry");
assert_eq!(((on_a.flags & 0x03E0) >> 5, on_a.word1), (2, 0));
// Then the machine goes back to the start state.
assert_eq!(on_a.new_state, state::START_OF_TEXT);
  • Implements: Clone, Copy, Debug.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raw::format::Substitution
pub enum Substitution {
    Feature(usize),
    Empty,
}

What a FeatureVariations record puts in place of one of a layout table's features: another feature table, or the empty feature.

A variable font can swap a feature for another as its axes move, such as a simpler dollar sign once the weight gets heavy. FeatureVariations::find gives the record that holds at a location, and FeatureVariations::substitute says what that record does to one feature index. None from it means the feature stays as the table lists it, and Some carries one of these.

The set is closed, so a match needs no _ arm: an offset in the font is either null or it is not.

use daegun::raw::format::{FeatureVariations, Substitution};

// A FeatureVariations table of one record that always holds. It swaps feature 3 for the feature
// table at byte 34, and feature 5 for the empty feature.
let layout = [
    0, 1, 0, 0, 0, 0, 0, 1, // version 1.0, one record
    0, 0, 0, 0, 0, 0, 0, 16, // record 0: no conditions, its substitutions at byte 16
    0, 1, 0, 0, 0, 2, // the substitutions: version 1.0, two of them
    0, 3, 0, 0, 0, 18, // feature 3: the table 18 bytes on from 16
    0, 5, 0, 0, 0, 0, // feature 5: a null offset
    0, 0, 0, 0, // byte 34, the alternate feature table: no lookups
];
let variations = FeatureVariations::at(&layout, 0);
let record = variations.find(&[], None).ok_or("no record holds")?;

for feature in [3, 4, 5] {
    match variations.substitute(record, feature) {
        Some(Substitution::Feature(at)) => { /* read the feature table at &layout[at..] */ }
        Some(Substitution::Empty) => { /* the feature applies no lookups here */ }
        None => { /* the feature stays as the table lists it */ }
    }
}
assert_eq!(variations.substitute(record, 3), Some(Substitution::Feature(34)));
assert_eq!(variations.substitute(record, 5), Some(Substitution::Empty));
assert_eq!(variations.substitute(record, 4), None);
Feature(usize)
The feature table to use in its place, as a byte offset from the start of the GSUB or GPOS table you parsed. It is laid out as any feature table is.
Empty
A null offset in the font: the feature is replaced by an empty one, which applies no lookups.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.

Rasterizing

daegun's own rasterizer, which turns glyphs and paths into pixels, and what any rasterizer needs beyond outlines: subpixel layouts with their filters, and an atlas packer. In daegun::raster.

raster::Bitmap
#[non_exhaustive]
pub struct Bitmap {
    pub left: i32,
    pub top: i32,
    pub width: u32,
    pub height: u32,
    pub channels: u8,
    pub pixels: Vec<u8>,
}

An image that owns its pixels, with its rows packed one after another.

Image::to_bitmap makes one from an image a rasterizer lent, and it lives for as long as you keep it. It carries what the image did: left and top to place it from the origin, its size and the bytes a pixel. Bitmap::image views it as an Image again, to read it row by row.

It is Clone, and compares and hashes by all of its fields, pixels included. It is #[non_exhaustive], so to build one of your own start from Bitmap::default(), an empty bitmap, and set its fields.

use daegun::raster::{Bitmap, RasterOptions, Rasterizer};
use daegun::{GlyphId, Location};
use std::collections::HashMap;

// A glyph cache of your own: each glyph of a text drawn once and kept.
let mut rasterizer = Rasterizer::new();
let mut drawn: HashMap<GlyphId, Bitmap> = HashMap::new();
for letter in "hello".chars() {
    let glyph = font.glyph_id(letter).expect("the font maps it");
    if !drawn.contains_key(&glyph) {
        let image = rasterizer.glyph(&font, glyph, &Location::default(), 16.0, &RasterOptions::DEFAULT)?;
        drawn.insert(glyph, image.to_bitmap());
    }
}
// Four bitmaps for five letters: the l was drawn once.
assert_eq!(drawn.len(), 4);

let h = &drawn[&font.glyph_id('h').expect("the font maps h")];
assert_eq!(h.pixels.len(), (h.width * h.height) as usize);
left: i32
How many pixels the left edge lies to the right of the origin.
top: i32
How many pixels the top edge lies above the origin, counting upward.
width: u32
Pixels across.
height: u32
Pixels down.
channels: u8
Bytes a pixel: 1 for coverage or a single-channel distance field, 3 for a subpixel layout or a multi-channel distance field, 4 for premultiplied RGBA.
pixels: Vec<u8>
The rows, the top one first, each width * channels bytes with nothing between them, so the length is width * height * channels.
  • Implements: Clone, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::Field
#[non_exhaustive]
pub enum Field {
    Sdf {
        spread: f32,
    },
    Msdf {
        spread: f32,
    },
}

Which kind of distance field Rasterizer::distance_field draws, and how far it reaches.

Both kinds store, for each pixel, the distance from its center to the outline, positive inside the glyph, as the byte 127.5 + 127.5 * distance / spread, rounded and kept within 0 to 255. The value runs out at spread pixels on either side of the outline, which is as far as an effect drawn from the field can reach.

A single-channel field is the plain one and the smaller. Scaled up, its corners round off, as a distance alone cannot say which of two edges a pixel is near. The multi-channel field splits the edges of the outline over three channels so that the median of the three, which the shader takes, keeps a corner sharp.

It is #[non_exhaustive]: build a variant by name, and give a match on it a _ arm.

use daegun::raster::{Field, Rasterizer};
use daegun::Location;

let mut rasterizer = Rasterizer::new();
let glyph = font.glyph_id('I').expect("the font maps I");
let at = Location::default();
let single = rasterizer.distance_field(&font, glyph, &at, 128.0, Field::Sdf { spread: 4.0 })?.to_bitmap();
let multi = rasterizer.distance_field(&font, glyph, &at, 128.0, Field::Msdf { spread: 4.0 })?;

// The same image, with three bytes a pixel in place of one.
assert_eq!((single.channels, multi.channels), (1, 3));
assert_eq!((multi.width, multi.height), (single.width, single.height));

// Across the middle of the stem, far from any corner, the median of the three is the plain distance.
let median = |p: &[u8]| p[0].min(p[1]).max(p[0].max(p[1]).min(p[2]));
let y = multi.height / 2;
let medians: Vec<u8> = multi.row(y).chunks_exact(3).map(median).collect();
assert_eq!(medians, single.image().row(y));
Sdf { spread: f32 }
A signed distance field: one byte a pixel, the distance to the outline.
spread: f32
How far the field reaches on each side of the outline, in pixels of the image. A distance of that much or more reads 0 outside and 255 inside. It must be finite and above 0.
Msdf { spread: f32 }
A multi-channel signed distance field: three bytes a pixel, whose median is the distance. Each channel measures to its own share of the outline's edges, which is what keeps corners sharp when the image is scaled up. Away from corners the three agree with Sdf. Where overlapping contours meet too closely for the rasterizer to merge them, the corner they make rounds off as in Sdf.
spread: f32
How far the field reaches on each side of the outline, in pixels of the image, as for Sdf.
  • Implements: Clone, Copy, Debug, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::Gamma
#[non_exhaustive]
pub enum Gamma {
    Linear,
    Srgb {
        text: Rgba,
        contrast: f32,
    },
}

How coverage becomes the alpha a compositor blends with.

Set it with RasterOptions::with_gamma. Pick by how your compositor blends. One that converts colors to linear light, blends there and converts back wants Linear. One that blends sRGB bytes as they are, out = text * a + back * (1 - a) on the encoded values, wants Srgb, which hands it the alpha that makes that blend, of the text over a ground of its opposite color, come out as the linear one would.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::color::Rgba;
use daegun::raster::{Gamma, RasterOptions, Rasterizer};
use daegun::Location;

let mut rasterizer = Rasterizer::new();
let glyph = font.glyph_id('o').expect("the font maps o");
let at = Location::default();
let draw = |rasterizer: &mut Rasterizer, gamma: Gamma| {
    let options = RasterOptions::DEFAULT.with_gamma(gamma);
    rasterizer.glyph(&font, glyph, &at, 12.0, &options).map(|image| image.to_bitmap())
};

let coverage = draw(&mut rasterizer, Gamma::Linear)?;
let half = coverage.pixels.iter().position(|&level| level == 128).expect("a pixel half covered");

// Black text, for a compositor that blends sRGB bytes: the half covered pixel gets an alpha of 68.
let black = Rgba::opaque(0, 0, 0);
assert_eq!(draw(&mut rasterizer, Gamma::Srgb { text: black, contrast: 0.0 })?.pixels[half], 68);
// Full contrast thickens it to 119.
assert_eq!(draw(&mut rasterizer, Gamma::Srgb { text: black, contrast: 1.0 })?.pixels[half], 119);
// White text is corrected the other way, to 188, and contrast does nothing for it.
let white = Rgba::opaque(255, 255, 255);
assert_eq!(draw(&mut rasterizer, Gamma::Srgb { text: white, contrast: 0.0 })?.pixels[half], 188);
assert_eq!(draw(&mut rasterizer, Gamma::Srgb { text: white, contrast: 1.0 })?.pixels[half], 188);
Linear
Coverage as it is: each byte is the share of the pixel the glyph covers. For a compositor that blends in linear light. The default.
Srgb { text: Rgba, contrast: f32 }
Alpha for a compositor that blends sRGB values as they are. Each coverage level becomes the alpha whose plain sRGB blend of the text color over its opposite, the color with every channel inverted, lands on the color that blending by coverage in linear light would give. So black text is corrected for a white ground and white text for a black one, and a half covered pixel becomes 68 for black text and 188 for white. In a one-channel image the text counts by its luminance, as a gray. In the three channels of a subpixel layout, each channel is corrected for the text's own red, green or blue.
text: Rgba
The color of the text. Its alpha is not read.
contrast: f32
How much to thicken the coverage before it is corrected, from 0 for none to 1. A coverage a becomes a + k * a * (1 - a), where k is the contrast times the linear light of the ground, so it weighs fully on dark text over a white ground and not at all on white text over black. Values above 1 count as 1, and a value that is 0, negative or not a number as none.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::Image
#[non_exhaustive]
pub struct Image<'a> {
    pub left: i32,
    pub top: i32,
    pub width: u32,
    pub height: u32,
    pub stride: usize,
    pub channels: u8,
    pub pixels: &'a [u8],
}

Pixels a rasterizer lends: a rectangle of rows, with where it sits from the origin of what was drawn.

Every drawing call that does not take a Target returns one. It borrows the rasterizer, so it is valid until the rasterizer's next call, and Image::to_bitmap copies it into a Bitmap you own. It is Copy, and a Bitmap hands out the same view of its own pixels through Bitmap::image.

left and top place the image. They are measured from the origin, which for a glyph is the point on the baseline where the pen stands: the image starts left pixels to the right of it and top pixels above it, and its rows run downward from there. An image is as large as what was drawn and no larger, and it has a width and height of 0 when nothing was, as for a space.

Read the pixels a row at a time with Image::row. channels says what a pixel is: one byte of coverage or of distance, three bytes for a subpixel layout or a multi-channel distance field, or four bytes of premultiplied RGBA for a color glyph.

It is #[non_exhaustive], so you cannot build one with a struct literal. Image::default() is an empty one.

use daegun::raster::{Image, RasterOptions, Rasterizer};
use daegun::Location;

let mut rasterizer = Rasterizer::new();
let glyph = font.glyph_id('L').expect("the font maps L");
let at = Location::default();
let image: Image = rasterizer.glyph(&font, glyph, &at, 12.0, &RasterOptions::DEFAULT)?;

// Inter's L at 12 px: 6 by 9 pixels, starting 1 pixel right of the origin and 9 above the baseline,
// so it stands on the line.
assert_eq!((image.left, image.top, image.width, image.height), (1, 9, 6, 9));
// The top row comes first: the tip of the stem. The foot is in the last row.
assert_eq!(image.row(0), [176, 31, 0, 0, 0, 0]);
assert_eq!(image.row(8), [241, 252, 251, 251, 251, 53]);
left: i32
How many pixels the left edge of the image lies to the right of the origin. Negative where the image starts left of it.
top: i32
How many pixels the top edge of the image lies above the origin, which for a glyph is on the baseline. It counts upward: an image wholly below the baseline has a top of 0 or less.
width: u32
Pixels across.
height: u32
Pixels down, which is the number of rows.
stride: usize
Bytes from the start of one row to the start of the next. In an image a rasterizer lends, and in one from Bitmap::image, it is width * channels, with no padding.
channels: u8
Bytes a pixel: 1 for coverage and for a single-channel distance field, 3 for a subpixel layout (red, green, blue) and for a multi-channel distance field, 4 for a color glyph (red, green, blue, alpha, premultiplied).
pixels: &'a [u8]
The bytes of the rows, the top row first.
  • Implements: Clone, Copy, Debug, Default, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::Rasterizer
pub struct Rasterizer {
    /* private fields */
}

Draws glyphs, color glyphs, distance fields and paths into images of pixels, keeping its buffers from one draw to the next.

Make one with Rasterizer::new and keep it for as long as you draw. Rasterizer::glyph gives a glyph as coverage, a byte for each pixel that says how much of the pixel the glyph covers. Rasterizer::color_glyph gives a color glyph as RGBA, Rasterizer::distance_field a distance field for a GPU, and Rasterizer::path fills a Path of your own.

Each of those lends an Image that points into the rasterizer and is valid until its next call, which the borrow checker enforces. Image::to_bitmap copies one out. The calls that end in _into draw into a Target instead, pixels you own, and take any size, where a lent image stops at MAX_SIDE and MAX_DRAW_BYTES.

Coverage is an area, not a count of sample points. Each byte is the share of its pixel that the outline covers, from 0 for none to 255 for all, worked out from the edges of the outline once its curves are cut into straight pieces that stay within a 32nd of a pixel of them. It is exact where contours overlap too. A rasterizer that adds up what each contour covers counts such a place twice. This one resolves the overlap, so a pixel that two contours each half cover in the same place reads 128, not 255.

daegun means a draw to give the same bytes on every CPU, with or without std, and the source is written for it: curves are cut into straight pieces by comparisons and integer square roots so that every build cuts them alike, sRGB levels come from tables, and the test suite pins one hash over 1,986 images of every kind listed here.

It keeps every buffer between calls, so drawing a glyph again allocates nothing. It also keeps what it learns of each glyph at its first draw, its outline and where its contours overlap, under the budget of Rasterizer::set_cache_budget. The images themselves are kept only when the font's Cache::Raster has a budget, which Font::set_cache_budget gives it: the same request is then lent from that cache, to any rasterizer.

A rasterizer holds no font. You pass the font to each call, and one rasterizer draws from any number of fonts. It is Send, and every drawing call takes it by &mut, so give each thread its own.

use daegun::raster::{RasterOptions, Rasterizer};
use daegun::shape::ShapeOptions;
use daegun::Location;

// Set "Wave" at 32 px into a canvas of one byte a pixel, with the baseline on row 30.
let (px, baseline) = (32.0, 30);
let (width, height) = (96, 40);
let mut canvas = vec![0u8; width * height];
let scale = f64::from(px) / f64::from(font.units_per_em());
let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT);

let mut rasterizer = Rasterizer::new();
let mut pen = 2.0;
for ((&glyph, advance), offset) in run.glyphs.iter().zip(&run.advances).zip(&run.offsets) {
    // Whole pixels place the image, and the fraction moves the glyph within its pixel.
    let (x, y) = (pen + offset.x * scale, offset.y * scale);
    let options = RasterOptions::DEFAULT.with_offset(x.fract() as f32, y.fract() as f32);
    let image = rasterizer.glyph(&font, glyph, &Location::default(), px, &options)?;
    let (left, top) = (x as i32 + image.left, baseline - y as i32 - image.top);
    for row in 0..image.height {
        let start = (top + row as i32) as usize * width + left as usize;
        for (dst, &src) in canvas[start..].iter_mut().zip(image.row(row)) {
            *dst = dst.saturating_add(src);
        }
    }
    pen += advance * scale;
}
// The word is inked across 82 by 25 pixels of the canvas.
  • Implements: Debug, Default.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::RasterOptions
#[non_exhaustive]
pub struct RasterOptions<'a> {
    pub outline: OutlineOptions,
    pub offset: [f32; 2],
    pub layout: &'a SubpixelLayout,
    pub darken: bool,
    pub gamma: Gamma,
}

How Rasterizer::glyph draws: the outline options, the subpixel offset, the layout of the pixels, stem darkening and gamma.

Start from RasterOptions::DEFAULT and change what you need with the with_ methods, each of which returns the changed options. The defaults draw the glyph as the font holds it, as plain coverage. The struct is #[non_exhaustive], so there is no struct literal for it, but its fields are public to read and to set.

The lifetime is that of the SubpixelLayout the options borrow. Two sets of options are equal when their fields are, the layouts compared by SubpixelLayout::key.

Rasterizer::glyph reads every field. Rasterizer::glyph_into reads them too but refuses a subpixel layout. Rasterizer::color_glyph and Rasterizer::color_glyph_into read the offset and the outline's transform and oblique, refuse a subpixel layout, hinting, a stroke and an embolden above 0, and pass over the rest. Rasterizer::distance_field and Rasterizer::path take no options.

use daegun::outline::{HintMode, OutlineOptions};
use daegun::raster::{RasterOptions, Rasterizer, StripeOrder, SubpixelLayout};
use daegun::Location;

// Small text for an LCD: hinted, its thin stems darkened, filtered for stripes in the order RGB.
let layout = SubpixelLayout::horizontal(StripeOrder::Rgb);
let options = RasterOptions::DEFAULT
    .with_outline(OutlineOptions::DEFAULT.with_hinting(HintMode::Auto))
    .with_darken(true)
    .with_layout(&layout);

let mut rasterizer = Rasterizer::new();
let glyph = font.glyph_id('g').expect("the font maps g");
let image = rasterizer.glyph(&font, glyph, &Location::default(), 12.0, &options)?;
// Three bytes a pixel now: red, green and blue.
assert_eq!(image.channels, 3);

// The fields are public, so options can be changed in place too.
let mut options = RasterOptions::DEFAULT;
options.offset = [0.5, 0.0];
assert_eq!(options, RasterOptions::DEFAULT.with_offset(0.5, 0.0));
outline: OutlineOptions
What happens to the outline before it is filled: hinting, a transform, a stroke, an embolden or an oblique lean, in an OutlineOptions, with the meaning each has in Font::prepared_outline. OutlineOptions::DEFAULT by default: the outline as the font holds it.
offset: [f32; 2]
How far the glyph moves right and up before it is drawn, in pixels, as [x, y]. It is for the fraction of a pen position, so that text set between whole pixels keeps its spacing. [0.0, 0.0] by default, which puts the glyph's origin on a pixel corner.
layout: &'a SubpixelLayout
How samples become the bytes of a pixel. The default, SubpixelLayout::grayscale, is one byte of coverage a pixel. A layout for the color stripes of a display gives three bytes a pixel.
darken: bool
Whether thin stems are widened at small sizes, where text otherwise reads too light. Off by default. RasterOptions::with_darken says by how much.
gamma: Gamma
How coverage becomes the alpha you blend with. Gamma::Linear by default: the coverage itself.
  • Implements: Clone, Copy, Debug, Default, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::Rect
pub struct Rect {
    pub x: usize,
    pub y: usize,
    pub w: usize,
    pub h: usize,
}

Where a rectangle landed in an atlas, in pixels: its left and top edges, its width and its height.

ShelfPacker::insert returns one for each glyph it places. x and y count from the top left corner of the atlas, with y running down, the way rows of pixels are stored. w and h are the size you asked for, unchanged.

It is a plain value whose fields are all it is, so you can build one by literal, compare two, copy it and use it as a key.

use daegun::raster::{Rect, ShelfPacker};

let side = 256;
let mut packer = ShelfPacker::new(side, side);
let rect = packer.insert(12, 17).expect("an empty atlas has room");
assert_eq!(rect, Rect { x: 0, y: 0, w: 12, h: 17 });

// Copy a glyph's rows into the atlas at the rect, one byte a pixel here.
let glyph = vec![255u8; rect.w * rect.h];
let mut atlas = vec![0u8; side * side];
for row in 0..rect.h {
    let at = (rect.y + row) * side + rect.x;
    atlas[at..at + rect.w].copy_from_slice(&glyph[row * rect.w..][..rect.w]);
}
x: usize
The left edge: pixels from the left side of the atlas.
y: usize
The top edge: pixels down from the top of the atlas.
w: usize
The width, in pixels.
h: usize
The height, in pixels.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::ShelfPacker
pub struct ShelfPacker {
    /* private fields */
}

Packs rectangles into an atlas of a fixed size, in rows called shelves.

An atlas is one large image that holds many glyphs, so a renderer can draw text from a single texture. The packer decides where each glyph goes. It holds no pixels: you give it sizes, it answers with places, and you copy the pixels there yourself.

A shelf is a band across the atlas, as tall as the rectangle that opened it and filled from the left. The first shelf is at the top, and each new one opens right below the last. ShelfPacker::insert puts a rectangle on the shortest shelf that can take it, and opens a new shelf where none can.

Rectangles sit edge to edge, with no gap between them, and there is no setting for one. If your renderer samples the atlas with filtering, add the gutter you need to the width and height you ask for.

A placed rectangle never moves, and no call frees one. When ShelfPacker::insert returns None for a glyph, start another atlas, or call ShelfPacker::reset and draw the glyphs of this one again.

use daegun::raster::{RasterOptions, Rasterizer, Rect, ShelfPacker};
use daegun::Location;

let side = 40;
let mut atlas = vec![0u8; side * side];
let mut packer = ShelfPacker::new(side, side);
let mut rasterizer = Rasterizer::new();

let mut placed = Vec::new();
for c in "glyph".chars() {
    let id = font.glyph_id(c).expect("Inter maps these letters");
    let image = rasterizer.glyph(&font, id, &Location::default(), 20.0, &RasterOptions::DEFAULT)?;
    if image.width == 0 || image.height == 0 {
        continue; // Nothing to draw, as for a space.
    }
    let Some(rect) = packer.insert(image.width as usize, image.height as usize) else {
        break; // Full: start another atlas, or reset this one and draw again.
    };
    for row in 0..image.height {
        let at = (rect.y + row as usize) * side + rect.x;
        atlas[at..at + rect.w].copy_from_slice(image.row(row));
    }
    placed.push((c, rect));
}

// The g opened a shelf 17 pixels tall at the top left, and l, y and p went on it to its right.
assert_eq!(placed[0], ('g', Rect { x: 0, y: 0, w: 10, h: 17 }));
assert_eq!(placed[3], ('p', Rect { x: 24, y: 0, w: 11, h: 17 }));
// The h found no room left across, so it opened a second shelf below.
assert_eq!(placed[4], ('h', Rect { x: 0, y: 17, w: 10, h: 15 }));
// A rectangle larger than the atlas never fits.
assert_eq!(packer.insert(41, 8), None);
  • Implements: Clone, Debug.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::StripeOrder
#[non_exhaustive]
pub enum StripeOrder {
    Rgb,
    Bgr,
}

The order of the red, green and blue stripes in a pixel of a display.

A pixel of an LCD is three stripes, one red, one green and one blue. Most panels run them red, green, blue from left to right, which is Rgb. Some run them the other way, and so does an Rgb panel turned upside down: that is Bgr. Subpixel text gives each stripe its own coverage, so it has to know which stripe is where. With the wrong order the edges of every stem show as color.

Pass it to SubpixelLayout::horizontal, SubpixelLayout::vertical or SubpixelLayout::unfiltered. It changes which samples each channel reads, not the order of the bytes: a pixel of the image is red, green, blue either way.

It is #[non_exhaustive], so a match on it needs a _ arm.

use daegun::raster::{RasterOptions, Rasterizer, StripeOrder, SubpixelLayout};
use daegun::Location;

let mut rasterizer = Rasterizer::new();
let g = font.glyph_id('g').expect("Inter maps g");

let rgb = SubpixelLayout::horizontal(StripeOrder::Rgb);
let options = RasterOptions::DEFAULT.with_layout(&rgb);
let for_rgb = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?.to_bitmap();

let bgr = SubpixelLayout::horizontal(StripeOrder::Bgr);
let options = RasterOptions::DEFAULT.with_layout(&bgr);
let for_bgr = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?.to_bitmap();

// Both are red, green, blue a pixel. The red and the blue bytes trade places, as their stripes do.
let traded: Vec<u8> = for_bgr.pixels.chunks_exact(3).flat_map(|p| [p[2], p[1], p[0]]).collect();
assert_eq!(for_rgb.pixels, traded);
Rgb
Red, green, blue: from left to right for stripes side by side, from top to bottom for stacked ones.
Bgr
Blue, green, red, in the same directions.
  • Implements: Clone, Copy, Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::SubpixelLayout
pub struct SubpixelLayout {
    /* private fields */
}

How a glyph drawn at several samples per pixel becomes one value per channel: plain coverage, the stripes of a display, or a filter of your own.

Plain text rendering gives each pixel one number, its coverage: the share of the pixel the glyph covers. That is the grayscale layout, one byte a pixel.

A pixel of an LCD is three stripes, one red, one green and one blue, most often side by side. Each is lit on its own, so across the stripes a display shows three times the detail it does in whole pixels. Subpixel text uses that: the glyph is drawn three times as fine, and each stripe gets the coverage of its own third of the pixel. Small text comes out sharper, at the price of an image of three bytes a pixel that is right for one arrangement of stripes only.

A layout holds what that takes. SubpixelLayout::oversample is how many samples the glyph is drawn at for each pixel, across and down. Each channel of a pixel is then a weighted sum of the samples in a small window around it: SubpixelLayout::taps is the size of that window, SubpixelLayout::origin where it starts and SubpixelLayout::weights the weights.

Make one with SubpixelLayout::grayscale, which is also what SubpixelLayout::default() gives, with SubpixelLayout::horizontal or SubpixelLayout::vertical for a display's stripes, with SubpixelLayout::unfiltered for the stripes with no filter, or with SubpixelLayout::from_weights for a filter you state yourself.

Hand it to daegun's rasterizer with RasterOptions::with_layout, and Rasterizer::glyph returns an Image of SubpixelLayout::channels bytes a pixel, already grown by SubpixelLayout::pad. With the stripe layouts the three bytes of a pixel are red, green, blue whichever way the stripes run, and each is a coverage: the alpha to blend that channel of the text color with. The options borrow the layout, so keep it in a variable. Rasterizer::glyph_into, Rasterizer::color_glyph and Rasterizer::color_glyph_into take the grayscale layout only, and answer ErrorKind::InvalidArgument for any other.

A rasterizer of your own reads the same numbers through the methods here, to sample and filter the way daegun does.

use daegun::raster::{RasterOptions, Rasterizer, StripeOrder, SubpixelLayout};
use daegun::Location;

let mut rasterizer = Rasterizer::new();
let g = font.glyph_id('g').expect("Inter maps g");

// Grayscale, the default: one byte a pixel.
let gray = rasterizer.glyph(&font, g, &Location::default(), 20.0, &RasterOptions::DEFAULT)?;
assert_eq!((gray.width, gray.height, gray.channels), (10, 17, 1));

// For an LCD with RGB stripes side by side: three bytes a pixel, and a pixel more on the left and right.
let lcd = SubpixelLayout::horizontal(StripeOrder::Rgb);
let options = RasterOptions::DEFAULT.with_layout(&lcd);
let image = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?;
assert_eq!((image.width, image.height, image.channels), (12, 17, 3));

for y in 0..image.height {
    for pixel in image.row(y).chunks_exact(3) {
        let (red, green, blue) = (pixel[0], pixel[1], pixel[2]);
        // Blend each channel of the text color over the background by its own coverage.
    }
}
  • Implements: Clone, Copy, Debug, Default.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin, UnwindSafe.
raster::Target
#[non_exhaustive]
pub struct Target<'a> {
    pub left: i32,
    pub top: i32,
    pub width: u32,
    pub height: u32,
    pub stride: usize,
    pub pixels: &'a mut [u8],
}

Pixels you own, described for a rasterizer to draw into: a rectangle of rows and where it lies from the origin of what is drawn.

The _into calls take one: Rasterizer::glyph_into, Rasterizer::path_into and Rasterizer::color_glyph_into. Where a lent Image tells you which rectangle a glyph fell in, a target tells the rasterizer which rectangle you want. A call that draws writes every pixel of it, the drawing where it falls inside and zeros elsewhere, and cuts off whatever lies outside.

left and top are read as those of an image are: the left edge of the rectangle is left pixels to the right of the origin, and its top edge top pixels above it. So for the origin to sit at column ox of row oy in your pixels, with rows counted down from the top, left is -ox and top is oy.

A pixel is one byte for a glyph or a path and four for a color glyph, and the stride lets the rectangle be part of a larger buffer: bytes of a row past the width are not touched. A target can be of any size, which is why the calls that take one have no limit where a lent image stops at MAX_SIDE.

It borrows the pixels mutably and is used up by the call it is passed to. Make one with Target::new: the struct is #[non_exhaustive], so it has no struct literal.

use daegun::raster::{RasterOptions, Rasterizer, Target};
use daegun::Location;

let mut rasterizer = Rasterizer::new();
let glyph = font.glyph_id('g').expect("the font maps g");

// A tile 16 pixels wide and 24 tall for one glyph, its origin at column 2 of row 16.
let mut tile = [0u8; 16 * 24];
let target = Target::new(-2, 16, 16, 24, 16, &mut tile);
rasterizer.glyph_into(&font, glyph, &Location::default(), 20.0, &RasterOptions::DEFAULT, target)?;

// Inter's g at 20 px starts 1 pixel right of its origin and 12 above it: column 3 of row 4.
assert!(tile[4 * 16 + 3..4 * 16 + 13].iter().any(|&coverage| coverage != 0));
left: i32
How many pixels the left edge of the rectangle lies to the right of the origin. -ox puts the origin at column ox.
top: i32
How many pixels the top edge of the rectangle lies above the origin, counting upward. oy puts the origin at row oy from the top.
width: u32
Pixels across.
height: u32
Pixels down.
stride: usize
Bytes from the start of one row to the start of the next. At least the width times the bytes a pixel takes in the call.
pixels: &'a mut [u8]
The bytes to draw into, the top row first. At least (height - 1) * stride bytes and one full row more.
  • Implements: Debug, Eq, Hash, PartialEq.
  • Auto traits: RefUnwindSafe, Send, Sync, Unpin.

Type to search.