Rust methods and functions
323 methods and functions in daegun 2.0.0, as the compiler exports them, filed by area. Each says what it does, what comes back and what happens when it can't, with 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, so ? has somewhere to go. Every number is in font units unless its entry says pixels, and every position in text is a byte offset.
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.
daegun::release_threadpub fn release_thread()Lets go of what the calling thread keeps between daegun calls.
To make repeated calls fast, each thread keeps some working state of its own: the locations it last read at and the scratch memory it reuses, and with the
threadingfeature its hinters and its recent runs as well. Without that feature the font keeps those two itself, and they go when the font is dropped.A location the thread last read at holds on to its font's bytes, and under
threadingso may a hinter it last used. So the memory of a font you dropped may stay until the thread works with other fonts, ends, or calls this.Call it from a pool's worker as it goes idle, or once a font is dropped and you want its memory back. It touches the calling thread alone, so other threads keep theirs, and nothing breaks afterward: the thread's next call builds again what it needs.
Without the
stdfeature no thread keeps anything, and the call does nothing.use daegun::shape::ShapeOptions; use daegun::Location; let width = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT).width(); drop(font); // This thread is done with fonts for now, so it gives back what it kept. daegun::release_thread();Error::kindpub const fn kind(&self) -> ErrorKindWhat kind of failure this is.
Branch on this, not on the message: the
ErrorKindsays what to do about the failure, and the text is there to be read.use daegun::{ErrorKind, Tag}; let error = "no such tag".parse::<Tag>().unwrap_err(); assert_eq!(error.kind(), ErrorKind::InvalidArgument);Error::messagepub fn message(&self) -> &strThe message: what went wrong, most often led by the table or step where it happened.
Text for a log or an error dialog, such as
glyf: glyph index out of range.Displaywrites the same text, so{error}in a format string prints it. The string borrows from the error.use daegun::Font; let error = Font::from_bytes(b"not a font").unwrap_err(); assert_eq!(error.message(), "TTF/OTF: file too short"); // Display writes the same text. assert_eq!(format!("cannot open: {error}"), "cannot open: TTF/OTF: file too short");Tag::newpub const fn new(bytes: &[u8; 4]) -> TagThe tag these four bytes spell.
Write it with a byte string:
Tag::new(b"wght"). It is aconst fn, so a tag can be a constant.It takes exactly four bytes and checks nothing about them, so pad a shorter name with spaces yourself, as in
Tag::new(b"lao "). To read a tag from text that may be wrong, parse the text instead, which returns an error for what is no tag.use daegun::Tag; const WEIGHT: Tag = Tag::new(b"wght"); // A place on the weight axis of a variable font. let black = font.location(&[(WEIGHT, 900.0)]); assert_eq!(WEIGHT.to_bytes(), *b"wght");Tag::to_bytespub const fn to_bytes(self) -> [u8; 4]The tag's four bytes, first to last.
The reverse of
Tag::new. The bytes include any padding spaces, and they need not be printable, since a font may hold any bytes in a tag.use daegun::Tag; let tag: Tag = "lao".parse()?; assert_eq!(tag.to_bytes(), *b"lao "); assert_eq!(Tag::new(&tag.to_bytes()), tag);
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.
CachePool::newpub fn new(bytes: usize) -> CachePoolMakes a pool with a budget in bytes.
bytesis the most that the caches in the pool may hold together. Nothing is set aside: a new pool holds nothing until a cache joins it withFont::set_cache_pool.A budget of 0 keeps every cache in the pool empty, except that each font's instance cache still keeps its newest location.
use daegun::{Cache, CachePool}; // 16 MiB for what three of this font's caches hold, shared with any other font that joins. let pool = CachePool::new(16 << 20); for cache in [Cache::Shape, Cache::Instance, Cache::Outline] { font.set_cache_pool(cache, Some(&pool)); } assert_eq!(pool.stats().entries, 0);CachePool::set_budgetpub fn set_budget(&self, bytes: usize)Changes the pool's budget in bytes.
A lower budget applies at once: the least recently used entries across the pool's caches are dropped until the rest fit. A higher one lets the caches grow again as they are used. The budget each cache has of its own applies beside it as before.
use daegun::shape::ShapeOptions; use daegun::{Cache, CachePool, Location}; let pool = CachePool::new(1 << 20); font.set_cache_pool(Cache::Shape, Some(&pool)); let _ = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); assert_eq!(pool.stats().entries, 1); // The app went to the background, so give the memory back. pool.set_budget(0); assert_eq!(pool.stats().entries, 0); assert_eq!(font.cache_stats(Cache::Shape).entries, 0);CachePool::statspub fn stats(&self) -> CacheStatsHow many entries the caches in the pool hold together, and how many bytes they count for.
The sum over every cache that has joined, across all fonts, as a
CacheStats. Itsbytesare the figure the pool's budget is held against.Font::cache_statsgives the figures of one cache.use daegun::shape::ShapeOptions; use daegun::{Cache, CachePool, Location}; let pool = CachePool::new(1 << 20); font.set_cache_pool(Cache::Shape, Some(&pool)); let _ = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); let stats = pool.stats(); // With one cache in the pool, the pool's figures are that cache's. assert_eq!(stats, font.cache_stats(Cache::Shape)); assert_eq!(stats.entries, 1);Font::axespub fn axes(&self) -> Vec<Axis>The font's variation axes, in the order its
fvartable lists them.Each
Axisgives the tag you pass toFont::location, the range of values the axis takes and its default. The values are user coordinates: the numbers a designer works in, such as 400 and 700 for weight.The list is empty for a font that is not variable, and for one whose
fvartable does not parse. Its order is the orderLocation::normalizedandNamedInstance::coordsfollow.The table is read at each call, so keep the list if you need it often.
use daegun::{Location, Tag}; let axes = font.axes(); // Inter Variable has two: optical size from 14 to 32, then weight from 100 to 900, 400 by default. assert_eq!(axes.len(), 2); let weight = &axes[1]; assert_eq!(weight.tag, Tag::new(b"wght")); assert_eq!((weight.min, weight.default, weight.max), (100.0, 400.0, 900.0)); // What to call the axis in a user interface is in the name table. assert_eq!(font.name(weight.name_id, &Location::default()).as_deref(), Some("Weight"));Font::cache_statspub fn cache_stats(&self, cache: Cache) -> CacheStatsHow many entries one of the font's caches holds now, and how many bytes they count for.
Returns a
CacheStats. Itsbytesare the cache's own count of what its entries cost, which is the figure the budget is held against.An entry is a shaped run in
Cache::Shape, a location inCache::Instance, an outline inCache::Outlineand an image inCache::Raster. The shape cache also counts the shaping plans it holds past the first 32. A cache that has not been used reports zeros.For
Cache::Instancethe bytes also count tables that dropped locations left for the next one to reuse, at most one location's worth. They are outside the budget and outside a pool's count, so the figure can read above both, and they go when the budget is set or the cache is cleared.use daegun::shape::ShapeOptions; use daegun::{Cache, CacheStats, Location}; assert_eq!(font.cache_stats(Cache::Shape), CacheStats::default()); let _ = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); let stats = font.cache_stats(Cache::Shape); // One run is kept now, and it counts for some bytes of the budget. assert_eq!(stats.entries, 1); assert!(stats.bytes > 0);Font::clear_cachepub fn clear_cache(&self, cache: Cache)Empties one of the font's caches.
Everything the cache holds is dropped, and its budget stays as it was, so it fills again as the font is used. For
Cache::Instancethat includes the newest location, which a budget alone never drops.What you already hold stays valid, such as the
Arcof a run or of an instance: it is yours. Use this to give memory back after a burst of work, as when a document closes.use daegun::shape::ShapeOptions; use daegun::{Cache, CacheStats, Location}; use std::sync::Arc; let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); font.clear_cache(Cache::Shape); assert_eq!(font.cache_stats(Cache::Shape), CacheStats::default()); // The run you hold is still good, and the next call shapes the text again. let again = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); assert!(!Arc::ptr_eq(&run, &again)); assert_eq!(run.glyphs, again.glyphs);Font::face_countpub fn face_count(bytes: &[u8]) -> usizeHow many fonts a slice of bytes holds: the faces of a collection, 1 for a font file, 0 for anything else.
An associated function, called on the bytes before any font is open. Each face then opens at its index, from 0 up to one less than the count, with
Font::from_collection,Font::from_vecorFont::from_static.It reads the file's header and no table. For a collection the answer is the number of face offsets the file really holds, which is fewer than its header states when the file ends before the last of them. For other bytes it is 1 when they start with a font signature and are at least 12 long, which does not promise that the font opens.
use daegun::Font; assert_eq!(Font::face_count(&bytes("inter")), 1); assert_eq!(Font::face_count(b"not a font"), 0); // Open every face of a file, whichever kind of file it is. let data = bytes("collection"); let count = Font::face_count(&data); let faces: Vec<Font> = (0..count).map(|index| Font::from_collection(&data, index)).collect::<Result<_, _>>()?; assert_eq!(faces.len(), 2);Font::family_namepub fn family_name(&self, location: &Location) -> Option<String>The font's family name, such as
Inter Variable: the typographic family name if the font has one, else the family name.Fonts carry two family names. Name ID 1 is the one older software groups by, with at most four styles to a family (regular, italic, bold and bold italic), so a larger family is split into several there. Name ID 16 names the family as a whole. This call returns ID 16 where the font has it and ID 1 otherwise, each read as
Font::namereads it, andNoneif the font has neither.The name is that of the instance at
location. That matters at a named instance whose style is not one of the four: there the instance's name ID 1 takes the style into it, and this call still returns the family.use daegun::{Location, NameId, Tag}; assert_eq!(font.family_name(&Location::default()).as_deref(), Some("Inter Variable")); // At Inter's SemiBold instance, name ID 1 takes the style into it. The family stays whole. let semibold = font.location(&[(Tag::new(b"wght"), 600.0)]); assert_eq!(font.name(NameId::FAMILY_NAME, &semibold).as_deref(), Some("Inter Variable SemiBold")); assert_eq!(font.family_name(&semibold).as_deref(), Some("Inter Variable"));Font::from_bytespub fn from_bytes(bytes: &[u8]) -> Result<Font>Opens the TrueType or OpenType font in a slice of bytes, copying them.
The font keeps its own copy, so the slice is free to go once the call returns. For a file already in a
Vecyou don't need afterward,Font::from_vecskips the copy, andFont::from_staticdoes the same for bytes that live as long as the program.The bytes must be one font file. For a collection (a
.ttcfile) useFont::from_collection. Opening checks the table directory, theheadtable's units per em and themaxptable's glyph count, and the rest of the font is read as calls need it.ErrorKind::Malformedmeans the bytes are no font file: there are fewer than 12 of them, they do not start with a font signature (a collection does not: it starts withttcf), or the table directory runs past their end.ErrorKind::Missingmeans the font has noheadtable with a units per em above 0, or nomaxptable long enough to hold a glyph count. Abhedtable, which Apple's bitmap-only fonts carry in place ofhead, serves as well. Amaxpin a version daegun does not read is not refused: the font opens with a glyph count of 0.A table whose bytes run past the end of the file is treated as absent, not as an error. The metrics tables
hmtxandvmtxare cut to what is there instead. So a file cut short after its directory still opens as long asheadandmaxpare whole, and the tables that were cut off read as missing from then on.use daegun::{ErrorKind, Font}; let data = bytes("inter"); let font = Font::from_bytes(&data)?; // The font has its own copy. drop(data); assert_eq!(font.units_per_em(), 2048); // Bytes that are no font are refused, with a kind to act on. let error = Font::from_bytes(b"not a font at all").unwrap_err(); assert_eq!(error.kind(), ErrorKind::Malformed);Font::from_collectionpub fn from_collection(bytes: &[u8], index: usize) -> Result<Font>Opens one face of a TrueType or OpenType collection, copying that face's tables.
A collection (a
.ttcor.otcfile) is one file holding several fonts, which may share tables.indexcounts from 0, andFont::face_countgives how many faces there are.The font keeps its own copy of the face's tables, so the slice is free to go afterward. For an ordinary collection that copy is the bytes those tables cover and no more, not the whole file.
Bytes that are a plain font file work too, as a collection of one: index 0 opens them as
Font::from_bytesdoes, copying the whole file.ErrorKind::InvalidArgumentmeans there is no face atindex: the index is at or pastFont::face_countfor a collection, or is anything but 0 for bytes that are not a collection.ErrorKind::Malformedmeans a collection whose header is cut short, or a face that is no font file.ErrorKind::Missingmeans the face lacks the units per em or the glyph count, asFont::from_bytestells it.use daegun::{ErrorKind, Font, Location}; let data = bytes("collection"); // This file holds two faces: EB Garamond, then Inter Variable. assert_eq!(Font::face_count(&data), 2); let garamond = Font::from_collection(&data, 0)?; let inter = Font::from_collection(&data, 1)?; assert_eq!(garamond.family_name(&Location::default()).as_deref(), Some("EB Garamond")); assert_eq!(inter.family_name(&Location::default()).as_deref(), Some("Inter Variable")); // There is no face 2. let error = Font::from_collection(&data, 2).unwrap_err(); assert_eq!(error.kind(), ErrorKind::InvalidArgument);Font::from_staticpub fn from_static(bytes: &'static [u8], index: usize) -> Result<Font>Opens a font from bytes that live for the whole program, reading them where they lie with nothing copied.
For a font built into the binary with
include_bytes!, or a file mapped into memory and never unmapped. The font's tables are windows onto your bytes, so opening copies none of the file, however large it is.indexis 0 for a font file, or the face's number in a collection.A mapped file comes this way once its mapping is leaked, so that it lasts for the life of the program. The bytes must not change while a font reads them, so nothing may rewrite the file under the mapping.
Bytes with a shorter life go through
Font::from_bytesorFont::from_vec.The errors are those of
Font::from_vec:ErrorKind::InvalidArgumentfor anindexwith no face,ErrorKind::Malformedfor bytes that are no font, andErrorKind::Missingfor a face without the units per em or the glyph count.use daegun::Font; // Bytes kept for the life of the program. In a program of your own this is // include_bytes!("Inter.ttf"), or a memory map that is never unmapped. let data: &'static [u8] = Box::leak(bytes("inter").into_boxed_slice()); let font = Font::from_static(data, 0)?; assert_eq!(font.units_per_em(), 2048);Font::from_vecpub fn from_vec(bytes: Vec<u8>, index: usize) -> Result<Font>Opens a font from a
Vecof bytes, keeping theVecin place of copying it.The font takes the
Vecand reads its tables where they lie in it, so nothing is copied.indexpicks the face: 0 for a font file, or the face's number in a collection.For a collection the whole file stays in memory for as long as the font does, since the face reads its tables out of it.
Font::from_collectioncopies the one face's tables instead, which holds less when you want one face of a large collection.ErrorKind::InvalidArgumentmeans there is no face atindex: the index is at or pastFont::face_countfor a collection, or is anything but 0 for bytes that are not a collection.ErrorKind::Malformedmeans a collection whose header is cut short, or a face that is no font file, asFont::from_bytestells it.ErrorKind::Missingmeans the face lacks the units per em or the glyph count. TheVecis consumed either way, and dropped on an error.use daegun::{Font, Location}; let data: Vec<u8> = bytes("inter"); let font = Font::from_vec(data, 0)?; assert_eq!(font.glyph_count(), 2937); // The second face of a collection. let second = Font::from_vec(bytes("collection"), 1)?; assert_eq!(second.family_name(&Location::default()).as_deref(), Some("Inter Variable"));Font::glyph_countpub fn glyph_count(&self) -> u32How many glyphs the font has.
Glyph ids run from 0 to one less than this. The count comes from the
maxptable when the font opens, and is the same at every location. Amaxpwhose version is neither 0.5 nor 1.x counts 0 glyphs.It is a
u32because daegun also reads theMAXPtable of fonts with more than 65,535 glyphs, whose count is 24 bits wide. That count is used where the font's outline tables (GLYFandLOCA, orglyfandloca, orCFF2) hold at least that many glyphs. Otherwise the count is the one inmaxp.use daegun::GlyphId; let count = font.glyph_count(); // Inter Variable has 2937 glyphs, with ids 0 to 2936. assert_eq!(count, 2937); for id in 0..count { let glyph = GlyphId(id); // Measure or draw the glyph. }Font::has_tablepub fn has_table(&self, tag: Tag) -> boolWhether the font has a table with that tag.
The same answer as
font.table(tag).is_some(). It tells you what kind of font you hold before you ask for more:glyffor TrueType outlines,CFForCFF2for PostScript ones,COLRfor color glyphs,MATHfor math layout.use daegun::Tag; // Inter has TrueType outlines and OpenType layout, and no color glyphs. assert!(font.has_table(Tag::new(b"glyf"))); assert!(font.has_table(Tag::new(b"GSUB"))); assert!(!font.has_table(Tag::new(b"COLR")));Font::index_allowancepub fn index_allowance(&self) -> usizeHow many bytes the font may still spend on the indexes it builds over its tables.
What is left, not what is used. It starts at 4 MiB plus eight times the bytes of the font's tables, falls as indexes are built, and rises again where the shape cache drops a shaping plan that drew on it. Compare two readings to see what a piece of work drew, or read it after
Font::set_index_allowanceto see what remains.use daegun::shape::ShapeOptions; use daegun::Location; let before = font.index_allowance(); let _ = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); let spent = before - font.index_allowance(); // Shaping built indexes over the font's tables, and they came out of the allowance. assert!(spent > 0);Font::instancepub fn instance(&self, location: &Location) -> Result<Arc<[u8]>>Builds a static font file from a variable font at one location.
The result is the bytes of a whole font with the variation applied: outlines, metrics, kerning and names as they are at
location, and no variation tables. Write it to disk, hand it to software that can't read variable fonts, or open it again withFont::from_bytes.For a variable font the file at the default location is an instance all the same. Its names are written as for any instance, so they can differ from the font's own names, which
Font::namesgives at&Location::default().It comes back as an
Arc<[u8]>and is kept in the instance cache,Cache::Instance, where its bytes count toward that cache's budget. Asking again for the same location returns the sameArcwithout building anything, for as long as the cache keeps that location.A font with no
fvartable, or one whosefvartable does not parse, is its own instance: you get its tables written out as a file, whatever the location.An error means the instance could not be put together:
ErrorKind::Missingfor a table it is made of and the font lacks, such ashmtx,glyforloca,ErrorKind::Malformedfor a table it has to read and cannot, such as aheadtable or aCFF2table cut short, andErrorKind::LimitExceededfor a font that asks for more work or memory than daegun allows. The error is kept with the location too, so a location that fails is not built again at each call.A variation table that does not read is not an error. Where
gvar,cvar,MVARor the side bearings inHVARcannot be read, what that table would have varied stays as the font stores it, and the call still succeeds. So a file can come back for a bold weight with the outlines of the default design.use daegun::{Font, Location, NameId, Tag}; use std::sync::Arc; let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); let file = font.instance(&bold)?; // A whole static font at weight 700, ready for std::fs::write. let fixed = Font::from_bytes(&file)?; assert!(!fixed.is_variable()); assert_eq!(fixed.name(NameId::FULL_NAME, &Location::default()).as_deref(), Some("Inter Variable Bold")); // Asking again hands back the same bytes without building them. assert!(Arc::ptr_eq(&file, &font.instance(&bold)?));Font::instance_tablespub fn instance_tables(&self, location: &Location) -> Result<BTreeMap<Tag, Cow<'_, [u8]>>>The tables of the instance at a location, by tag, without putting them together into a file.
These are the tables
Font::instancewrites, as a map from tag to bytes. A table the location leaves as stored is borrowed from the font (Cow::Borrowed), and one it changes is built and owned (Cow::Owned). Use it to read one table of an instance, or to write the file your own way.Unlike
Font::instance, nothing is kept: each call on a variable font builds the tables again.A font with no
fvartable, or one whosefvartable does not parse, gives its own tables, all borrowed.The errors are those of
Font::instance.use daegun::Tag; use std::borrow::Cow; let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); let tables = font.instance_tables(&bold)?; // The instance has no variation tables left. assert!(!tables.contains_key(&Tag::new(b"fvar"))); assert!(!tables.contains_key(&Tag::new(b"gvar"))); // Its outlines were built for this weight, and its character map is the font's own. assert!(matches!(tables[&Tag::new(b"glyf")], Cow::Owned(_))); assert!(matches!(tables[&Tag::new(b"cmap")], Cow::Borrowed(_)));Font::is_variablepub fn is_variable(&self) -> boolWhether the font is a variable font: its
fvartable states at least one axis.A variable font holds a range of designs along its axes, such as weight, and
Font::locationpicks a point in that range. For a font that is not variable this is false,Font::axesis empty, and everyLocationmeans the font as it is.It reads only the axis count in the header of
fvar. A font whosefvarstates axes but does not parse answers true here whileFont::axesis empty and every location is the default, so test!font.axes().is_empty()where you need axes you can set.use daegun::Font; // Inter Variable has axes. Scheherazade New is a static font. assert!(font.is_variable()); let fixed = Font::from_bytes(&bytes("arabic"))?; assert!(!fixed.is_variable()); assert!(fixed.axes().is_empty());Font::localized_namespub fn localized_names(&self, name_id: NameId, location: &Location) -> Vec<LocalizedName>One name by its ID in every language the name table records it in.
Returns a
LocalizedNamefor each language, sorted by language tag: a BCP 47 tag such asenorja, and the name in that language. Use it to show a font's family in the user's own language, which fonts for Chinese, Japanese and Korean usually record.The list is empty where the table has no readable record for the ID. A record that names no language daegun knows comes under
und, and one whose name is empty once trimmed is left out. Where two records give one language, as a Windows record and a Mac record both do for English, the oneFont::namewould prefer is used.The limit of
Font::namesapplies here too. The languages are read in tag order until their stored bytes pass four times the size of the table, and the ones after that are left out, thoughFont::namestill reads the name. Only a table that points many records at one long string reaches it.At any location but the default, count on one language only for each ID: the record
Font::namereads there. daegun reads the names of a location from a table it builds for that location, which for any ordinary font it cuts down to that one record for each ID. A file fromFont::instancekeeps the other languages of the names it does not rewrite, but no call at a location reads them. Ask at&Location::default()for a name in every language.use daegun::{Font, Location, NameId, Tag}; let font = Font::from_bytes(&bytes("cjk"))?; let names = font.localized_names(NameId::FAMILY_NAME, &Location::default()); // Source Han Sans names its family in English and in Japanese. assert_eq!(names.len(), 2); assert_eq!((names[0].language.as_str(), names[0].name.as_str()), ("en", "Source Han Sans JP VF")); assert_eq!((names[1].language.as_str(), names[1].name.as_str()), ("ja", "源ノ角ゴシック JP VF")); // At any other location only the record Font::name reads comes back: here the English one. let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); let at_bold = font.localized_names(NameId::FAMILY_NAME, &bold); assert_eq!(at_bold.len(), 1); assert_eq!(at_bold[0].language, "en");Font::locationpub fn location(&self, coords: &[(Tag, f64)]) -> LocationMakes the
Locationthat a set of axis values names on this font.coordspairs each axis tag with a value in user coordinates, the scaleFont::axesreports: a weight of 700, a width of 85. An axis you leave out stays at its default.There is no error to handle. A value past the range of its axis is clamped to it. A tag the font has no axis for is ignored, and so is a value that is not finite. Where a tag is named twice the last one wins. On a font that is not variable every location is the font as it is.
Make a location once and keep it. The call resolves the values into the font's normalized coordinates, which each later call reads from the
Locationwithout working them out again.The result can be handed to another font, which resolves the same values against its own axes.
use daegun::shape::ShapeOptions; use daegun::{Location, Tag}; let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); let run = font.shape("Wave", &bold, &ShapeOptions::DEFAULT); // Inter sets "Wave" 5572 units wide at weight 700, against 5339 at its default weight. assert_eq!(run.width(), 5572.0); // Past the range of the axis the value is clamped: Inter's weight stops at 900. let heaviest = font.location(&[(Tag::new(b"wght"), 2000.0)]); assert_eq!(heaviest.coords(), [(Tag::new(b"wght"), 900.0)]);Font::namepub fn name(&self, name_id: NameId, location: &Location) -> Option<String>One name from the name table by its ID, such as the family name or the version string.
Nonewhere the name table has no record for the ID that daegun can read, or the name is empty once trimmed.A name is often recorded several times. This returns one of them, the first found in this order: an English record for Windows, another Windows record, an English Mac record in Mac Roman, another Mac Roman record, a record for the Unicode platform. Among equals the first in the table wins. Records in other encodings, such as the older East Asian ones, are passed over. NULs and white space around the name are trimmed off.
For the name in a given language use
Font::localized_names. At a location other than the default the name is the instance's, asFont::namesdescribes.use daegun::{Location, NameId}; let version = font.name(NameId::VERSION_STRING, &Location::default()); assert_eq!(version.as_deref(), Some("Version 4.001;git-9221beed3")); // A font's own names start at 256. Inter has none numbered 999. assert_eq!(font.name(NameId(999), &Location::default()), None);Font::named_instancespub fn named_instances(&self) -> Vec<NamedInstance>The instances the font's designer named, such as Light or Bold, in the order
fvarlists them.A named instance is a point in the design space with a name of its own: the styles a font menu lists for a variable font. Pass an instance's
coordstoFont::locationto get there.The list is empty for a font with no
fvartable, and for one whosefvartable does not parse. The names are thoseFont::namesgives at the default location, so its limit applies to them too.use daegun::Tag; let instances = font.named_instances(); // Inter Variable names nine, from Thin to Black. assert_eq!(instances.len(), 9); let bold = instances.iter().find(|i| i.name.as_deref() == Some("Bold")).expect("Inter has a Bold"); let location = font.location(&bold.coords); // The place the designer called Bold is a weight of 700. assert_eq!(location.coords(), [(Tag::new(b"wght"), 700.0)]);Font::namespub fn names(&self, location: &Location) -> BTreeMap<NameId, String>Every name in the font's name table, keyed by name ID.
The
nametable holds the font's strings: family, style, version, copyright, designer, license, and the names of its axes, instances and features. A string is often recorded several times, for different platforms and languages. This picks one per ID, the wayFont::namepicks it, andFont::localized_namesgives the other languages.IDs below 256 have fixed meanings, which the constants on
NameIdspell out. IDs from 256 up are the font's own.The names are those of the instance at
location. At the default location they are the names as the font stores them. Elsewhere they are the names a file fromFont::instancewould carry: at a named instance the family, subfamily, full name, PostScript name and unique ID are written for that instance, and at any other place the PostScript name and unique ID are made from the axis values. Name ID 25 is left out in both cases.The typographic names follow a named instance too. Where its style is made of the words Regular, Bold, Italic and Oblique alone, IDs 16 and 17 are left out, even from a font that stores them. Where it has another word, such as SemiBold, ID 1 takes that word into it and IDs 16 and 17 are written with the family and the style.
A name that is empty once NULs and white space are trimmed off is left out. The map is built at each call.
Font::visit_namesreads the same names without aStringfor each.There is one limit. The names are read in order of ID until their stored bytes pass four times the size of the table, and the IDs after that are left out, though
Font::namestill reads each of them. Only a table that points many records at one long string reaches it.use daegun::{Location, NameId}; let names = font.names(&Location::default()); assert_eq!(names[&NameId::FAMILY_NAME], "Inter Variable"); assert_eq!(names[&NameId::SUBFAMILY_NAME], "Regular"); assert_eq!(names[&NameId::DESIGNER], "Rasmus Andersson"); // The map is in order of ID, so the font's own names, from 256 up, come last. let own: Vec<&str> = names.range(NameId(256)..).map(|(_, name)| name.as_str()).collect(); // Inter's first two name its axes. assert_eq!(own[..2], ["Optical size", "Weight"]);Font::prewarmpub fn prewarm(&self, glyphs: impl IntoIterator<Item: Borrow<GlyphId>>, location: &Location) -> usizeDraws glyphs ahead of time into the font's outline cache, so that drawing them later replays a kept outline.
For each glyph it decodes the outline at
locationand keeps it inCache::Outline. From then onFont::outlinereplays the kept copy in place of decoding the glyph, and so do the other calls that draw an unhinted outline, such asFont::glyph_boundsandFont::prepared_outlinewhen it does not hint. This is the only call that fills that cache: drawing a glyph that was not prewarmed keeps nothing.Returns how many outlines it put in. A glyph adds none if it is already there, if it draws nothing (as a space does), if it fails to draw or is past the font's last glyph, or if its outline alone costs more than the cache's budget. The count is of what went in, not of what is left: where the glyphs together cost more than the budget, the earlier ones are dropped again to make room for the later.
glyphsis anything that yields glyph ids, by value or by reference, so&run.glyphsof aShapedRunserves as it is. Outlines are kept by location, so prewarm at each location you draw at.use daegun::outline::Path; use daegun::shape::ShapeOptions; use daegun::{Cache, Location}; let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); // Draw the run's four glyphs once, ahead of the frame that needs them. let added = font.prewarm(&run.glyphs, &Location::default()); assert_eq!(added, 4); assert_eq!(font.cache_stats(Cache::Outline).entries, 4); // Later, when the frame draws them. let mut path = Path::default(); font.outline(run.glyphs[0], &Location::default(), &mut path)?; // Glyphs already there add nothing. assert_eq!(font.prewarm(&run.glyphs, &Location::default()), 0);Font::set_cache_budgetpub fn set_cache_budget(&self, cache: Cache, bytes: usize)Sets how many bytes one of the font's caches may hold.
A budget is a ceiling the cache grows toward as the font is used, never memory set aside. When an entry would take the cache past it, the least recently used entries are dropped until the rest fit, and an entry that alone costs more than the budget is not kept. Lowering a budget applies at once, by the same rule.
The budgets start at 8 MiB for
Cache::Shape, 64 MiB forCache::Instance, 4 MiB forCache::Outlineand 0 forCache::Raster, which is therefore off until you give it one.A budget of 0 turns a cache off: it holds nothing, and each call does its work afresh. The results are the same. The exception is
Cache::Instance, which keeps the location used last whatever its budget, since otherwise every call at that location would build it again. So a font used at one location runs well on an instance budget of 0. Apart from the cache, and counted neither by its budget nor byFont::cache_stats, each thread in a build withstdholds on to the locations it last read at, two at most, until it reads at others, ends or callsrelease_thread.The shape cache keeps a run only if it is small beside the budget: a run that costs more than 64 KiB, and more than an eighth of the room the budget gives runs, is shaped at each call. A font keeps its first 32 shaping plans for good, a plan being the set of font lookups worked out for one script, direction, language and set of features. Any others are held under the shape budget too: once there are some, they get a sixteenth of it and the runs the rest.
Under
threadinga shape budget of 4 MiB or more is split evenly over 16 lists, each with its own lock and its own share to keep to, which is also the share a long run is measured against. A budget of 0 sets the lists aside, so threads shaping meet at no lock. The shape cache then evicts by a looser rule than strict order of use: a run read again since it came in outlives the runs that were not. Each thread also keeps up to 32 runs it read lately to itself, outside any budget.use daegun::shape::ShapeOptions; use daegun::{Cache, Location}; // Text that never repeats gains nothing from kept runs, so turn the shape cache off. font.set_cache_budget(Cache::Shape, 0); let _ = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); assert_eq!(font.cache_stats(Cache::Shape).entries, 0); // A megabyte for rasterized glyphs, in a cache that is off until it has a budget. font.set_cache_budget(Cache::Raster, 1 << 20);Font::set_cache_poolpub fn set_cache_pool(&self, cache: Cache, pool: Option<&CachePool>)Puts one of the font's caches into a
CachePool, a budget shared with the caches of other fonts, or takes it out again.With
Some(&pool)the cache joins the pool, and what it already holds comes with it. A cache is in one pool at a time: joining another moves it, with what it holds, out of the first. WithNoneit leaves, keeps what it holds and answers to its own budget alone again.In a pool a cache keeps to two limits. Past its own budget it drops its own least recently used entries, as before. Past the pool's budget the least recently used entry across every cache in the pool goes, whichever font it belongs to. Give a cache a budget of
usize::MAXwithFont::set_cache_budgetto leave the pool alone in charge.Cache::Rasterstarts with a budget of 0, and joining a pool does not change that: give it a budget of its own as well, or it stays off.The instance cache keeps each font's newest location past the pool's budget, as it does past its own. A font that is dropped gives its bytes back to the pool. Joining with the shape cache brings its shaping plans past the first 32 into the pool too, under a sixteenth of the shape budget, which leaves the runs the rest.
Under
threadinga pooled cache evicts by a looser rule than strict order of use: an entry read again since it came in outlives the entries that were not.use daegun::shape::ShapeOptions; use daegun::{Cache, CachePool, Font, Location}; // One megabyte for the shaped runs of every font in the pool. 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); } // The pool counts one run from each font. assert_eq!(pool.stats().entries, 2); // A font that leaves keeps its run, and takes it out of the pool's count. fonts[0].set_cache_pool(Cache::Shape, None); assert_eq!(pool.stats().entries, 1); assert_eq!(fonts[0].cache_stats(Cache::Shape).entries, 1);Font::set_index_allowancepub fn set_index_allowance(&self, bytes: usize)Sets how many bytes the font may still spend on the indexes it builds over its tables.
As a font is shaped, daegun builds indexes over its tables: one for the character map, and others for the glyph sets and classes its layout lookups test. They turn searches into direct lookups. The allowance caps what they may take in all, so a hostile font can't make them grow without bound.
It is not a budget like a cache's. It is an amount left to spend: building an index draws it down, and nothing is evicted to make room. Where too little is left for an index, that index is not built and its lookups read the table directly, with the same results.
It starts at 4 MiB plus eight times the bytes of the font's tables. This call replaces what is left with
bytes. At 0 no new index is built until bytes come back, which happens when the shape cache drops a shaping plan, past the font's first 32, that drew some, as an Indic script's plan can. The indexes themselves belong to the font, whichever location first needed them, so dropping a location gives nothing back.use daegun::shape::ShapeOptions; use daegun::Location; // No indexes for this font: its lookups read the tables directly. font.set_index_allowance(0); let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); // The run is the one the indexes would have given. assert_eq!(run.width(), 5339.0); assert_eq!(font.index_allowance(), 0);Font::stylepub fn style(&self, location: &Location) -> FontStyleWhether the font is upright, italic or oblique at a location.
It reads the flags the font sets about itself. The answer is
FontStyle::Obliqueif thefsSelectionfield of theOS/2table has its oblique bit set. Failing that it isFontStyle::ItaliciffsSelectionor theheadtable'smacStylehas its italic bit set, andFontStyle::Normalif neither does. It reports what the font says of itself, not the shape of its glyphs.At the default location the flags are the font's own, as stored. At any other location of a variable font they are the flags daegun would write into the instance there, which it sets by rule. A slant axis (
slnt) off 0 makes the instance oblique, if theOS/2table is version 4 or later, the first to define that bit, and at 0 it is not. A font without that axis keeps its own oblique flag. With an older table a slant off 0 reads as italic at a named instance and changes nothing elsewhere.At a named instance the font is italic where an italic axis (
ital) is at 0.5 or more or the slant is off 0. A font with neither axis keeps the italic flag of itsOS/2table there, and the one inheadis not read, so a font flagged italic inheadalone answersFontStyle::Normalat a named instance. At a location that is no named instance the italic flag follows the font's own subfamily name, name ID 2: it is set if that name has the word Italic or Oblique, whatever the axes are set to.use daegun::{Font, FontStyle, Location}; assert_eq!(font.style(&Location::default()), FontStyle::Normal); // The italic face of Irianis ADF says so in its tables. let italic = Font::from_collection(&bytes("Irianisadfstd/IrianisadfstdItalic.ttc"), 0)?; assert_eq!(italic.style(&Location::default()), FontStyle::Italic);Font::tablepub fn table(&self, tag: Tag) -> Option<&[u8]>The bytes of one of the font's tables as the file stores them, or
Noneif it has no table with that tag.The slice is borrowed from the font, with nothing parsed or copied. It is the table of the font as opened: for a table as an instance of a variable font would carry it, use
Font::instance_tables.Some entries of the directory count as absent: one with a length of 0 (except
glyf, which may be empty), one whose bytes run past the end of the file, one whose tag is not printable ASCII, and every entry under a tag after the first one that lies inside the file. In a file that carries both kinds of outline, the kind its signature does not name is absent too:CFFandCFF2under a TrueType signature,glyfandlocaunderOTTO.The metrics tables
hmtxandvmtxare the exception to the rule about the end of the file: one that starts inside the file and runs past it is cut to what is there.Font::has_tableandFont::table_tagsgo by the same rules.use daegun::Tag; let head = font.table(Tag::new(b"head")).expect("a font that opens has a head table"); // The units per em sit at byte 18 of head. assert_eq!(u16::from_be_bytes([head[18], head[19]]), font.units_per_em()); // Inter has TrueType outlines, so it has no CFF table. assert!(font.table(Tag::new(b"CFF ")).is_none());Font::table_tagspub fn table_tags(&self) -> impl ExactSizeIterator<Item = Tag> + DoubleEndedIterator + FusedIterator + CloneThe tag of every table the font has, in tag order.
Tag order is the order of the tags' bytes, so uppercase tags such as
GSUBcome before lowercase ones such ascmap. The iterator knows its length and can be walked from either end. Pass a tag toFont::tablefor the bytes.let tags: Vec<String> = font.table_tags().map(|tag| tag.to_string()).collect(); // Inter Variable has 19 tables, from GDEF to post. assert_eq!(tags.len(), 19); assert_eq!((tags[0].as_str(), tags[18].as_str()), ("GDEF", "post")); // How many bytes the font's tables take. let total: usize = font.table_tags().filter_map(|tag| font.table(tag)).map(<[u8]>::len).sum();Font::units_per_empub fn units_per_em(&self) -> u16How many font units make one em, from the font's
headtable.Every metric, advance and outline daegun returns is in these units, so this is the number to scale by: a value in pixels is
value * px / f64::from(font.units_per_em()), wherepxis the size of the em in pixels.It is never 0, since a font without it does not open, and it is the same at every location. A font with a
bhedtable in place ofhead, as Apple's bitmap-only fonts have, is read the same way.use daegun::shape::ShapeOptions; use daegun::Location; assert_eq!(font.units_per_em(), 2048); let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); let pixels = run.width() * 16.0 / f64::from(font.units_per_em()); // The run is 5339 units wide, which is about 41.7 pixels at 16 px.Font::visit_namespub fn visit_names(&self, location: &Location, visit: impl FnMut(NameId, &str))Calls a closure with each name in the name table, in order of name ID, without building a map.
It walks the names
Font::namesreturns, at the same location, and lends each tovisitas a&strthat is valid only for that call. One buffer is reused for every name, so no name takes aStringof its own. Use it to search the names or to copy out a few.use daegun::{Location, NameId}; // Which names hold a URL. let mut urls: Vec<NameId> = Vec::new(); font.visit_names(&Location::default(), |id, name| { if name.starts_with("http") { urls.push(id); } }); assert_eq!(urls, [NameId::VENDOR_URL, NameId::DESIGNER_URL, NameId::LICENSE_URL]);Location::coordspub fn coords(&self) -> &[(Tag, f64)]The axis values this location sets, as the font that made it resolved them.
One pair of tag and value for each axis that is off its default, in the order of the font's
fvartable, each value clamped to the range of its axis. An axis at its default is not listed, nor is a tag the font lacks or a value that was not finite. So the default location gives an empty slice, and so does any location made by a font that is not variable.These are user coordinates, the scale
Font::locationtakes. The list is the location in one fixed form, so two locations made by one font are the same place when theircoordsare equal.The slice is how the font that made the location sees it. Another font handed the same location resolves the values for itself, and this slice does not change.
use daegun::{Location, Tag}; // Asked for out of order, with optical size at its default and weight past its range. let location = font.location(&[(Tag::new(b"wght"), 2000.0), (Tag::new(b"opsz"), 14.0)]); // Only weight is off its default, clamped to Inter's 900. assert_eq!(location.coords(), [(Tag::new(b"wght"), 900.0)]); assert!(Location::default().coords().is_empty());Location::normalizedpub fn normalized(&self) -> &[f64]The location in normalized coordinates: one value for each axis, from -1 to 1, as the font's variation tables count them.
One value for each axis in the order of the font's
fvartable: 0 at the default of the axis, -1 at its minimum and 1 at its maximum, after the font'savartable has reshaped the scale in between. Variation data is stored against these numbers, so you need them only to read variation tables yourself.The slice is empty wherever every value is 0: at the default location, for a font that is not variable, and at a place so near the default that every value rounds to 0. Otherwise it has an entry for every axis, those at their default included.
These are the coordinates of the font that made the location. Another font handed the same location works out its own, and this slice does not change.
use daegun::{Location, Tag}; let heaviest = font.location(&[(Tag::new(b"wght"), 900.0)]); // Inter's axes are optical size, then weight: size at its default, weight at its maximum. assert_eq!(heaviest.normalized(), [0.0, 1.0]); let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); // 700 is three fifths of the way from 400 to 900, and Inter's avar table makes that 0.54. assert!((bold.normalized()[1] - 0.54).abs() < 0.001); assert!(Location::default().normalized().is_empty());
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.
Font::ascenderpub fn ascender(&self, location: &Location) -> f64The font's ascender at a location: how far above the baseline its
hheatable says its letters reach.In font units, y up. For pixels, multiply by
px / f64::from(font.units_per_em()).This is the
ascenderfield ofhheaand nothing else. OS/2's ascenders are not consulted, so it may not be the ascent that lines should be spaced with.Font::line_metricsweighs the tables against each other and is the call for that.A font with no usable
hheatable gives 0. The one exception is a font that holds only bitmaps: it takes the ascender of its largest strike, the set of bitmaps drawn for one size, scaled to font units.A variable font can move the field with its
MVARtable. At a location other than the default you get the number a file fromFont::instancewould hold there, and&Location::default()reads the table as stored. Where daegun can't build that instance, as for a font whoseheadtable is cut short, the call answers as at the default location, thoughFont::instancethere fails.use daegun::Location; let ascender = font.ascender(&Location::default()); // Inter's ascender is 1984 units, in an em of 2048. assert_eq!(ascender, 1984.0); // At 16 px that is 15.5 pixels above the baseline. let px = ascender * 16.0 / f64::from(font.units_per_em()); assert_eq!(px, 15.5);Font::boundspub fn bounds(&self) -> Option<Bounds>The box the font states around all of its glyphs, from its
headtable, orNonewhere the table is too short to hold one.A
Boundsin font units, y up: thexMin,yMin,xMaxandyMaxthe file stores. daegun reads the four numbers and measures nothing, so the box is as good as the font's maker left it. Use it for a rough clip, or to size a buffer that any glyph fits. For the true box of one glyph, useFont::glyph_bounds.It takes no location. A variable font stores one box, so away from its default a glyph may reach outside it.
Noneis rare. A font cannot open without the table, so it means the table stops before the box. In an Apple bitmap font the table is namedbhed, and is read alike.use daegun::Bounds; if let Some(Bounds { x_min, y_min, x_max, y_max }) = font.bounds() { // Inter states a box from (-1513, -660) to (5290, 2269), far wider than its em of 2048. assert_eq!((x_min, y_min, x_max, y_max), (-1513.0, -660.0, 5290.0, 2269.0)); }Font::cap_heightpub fn cap_height(&self, location: &Location) -> f64The height of the font's capital letters at a location, from the
sCapHeightfield ofOS/2.In font units above the baseline. Use it to size or align text by its capitals, as when a label has to sit centered beside an icon.
OS/2holds the field from version 2 of the table on. Where the font has noOS/2table, the table is older or cut short, or the field is 0, you getFont::ascenderinstead: a stand-in, not a measured cap height.A variable font can move the field with its
MVARtable. At a location other than the default you get the number a file fromFont::instancewould hold there. Where daegun can't build that instance, as for a font whoseheadtable is cut short, the call answers as at the default location, thoughFont::instancethere fails.use daegun::Location; let cap = font.cap_height(&Location::default()); // Inter's capitals stand 1490 units tall. assert_eq!(cap, 1490.0); // The font size at which a capital is 20 px tall: about 27.5 px. let size = 20.0 * f64::from(font.units_per_em()) / cap;Font::descenderpub fn descender(&self, location: &Location) -> f64The font's descender at a location: how far below the baseline its
hheatable says its letters reach, as a negative number.In font units, y up, so a font that reaches below the baseline has a descender below 0, and the height from descender to ascender is the ascender minus the descender.
It is the
descenderfield ofhhea, read by the same rules asFont::ascender: 0 for a font with no usablehhea, the value of the largest strike (a strike being the set of bitmaps drawn for one size) for a bitmap-only font without one, and moved byMVARat a location of a variable font. Where daegun can't build the instance at that location, as for a font whoseheadtable is cut short, the call answers as at the default location, thoughFont::instancethere fails. To space lines, useFont::line_metrics.use daegun::Location; let descender = font.descender(&Location::default()); // Negative, since it lies below the baseline: -494 for Inter. assert_eq!(descender, -494.0); // The height from the descender up to the ascender. let height = font.ascender(&Location::default()) - descender; assert_eq!(height, 2478.0);Font::italic_anglepub fn italic_angle(&self, location: &Location) -> f64The slant of the font at a location, in degrees counterclockwise from upright, from the
posttable.An upright font answers 0. A face that leans to the right, as an italic does, has a negative angle: -13 for a slant of 13 degrees. A font with no
posttable, or one cut short, answers 0 too.On a variable font with a slant axis,
slnt, a location other than the default answers the value of that axis there, held within 90 degrees either way.MVARhas no way to vary the angle, so the axis stands in for it. A variable font without that axis has one angle at every location. Where daegun can't build the instance at a location, as for a font whoseheadtable is cut short, the call answers as at the default location, thoughFont::instancethere fails.It is what the font says of itself, not a measure of its glyphs.
Font::pdf_flagssetsPdfFlags::ITALICfrom it.use daegun::{Font, Location}; // Inter is upright. assert_eq!(font.italic_angle(&Location::default()), 0.0); // The italic face of Irianis ADF leans 13 degrees to the right, which reads as -13. let italic = Font::from_collection(&bytes("Irianisadfstd/IrianisadfstdItalic.ttc"), 0)?; let angle = italic.italic_angle(&Location::default()); assert_eq!(angle, -13.0); // How far a caret that follows the slant moves right for each unit it rises: about 0.23. let lean = (-angle).to_radians().tan();Font::line_metricspub fn line_metrics(&self, location: &Location, orientation: Orientation) -> LineMetricsThe font's line spacing at a location: ascent, descent and line gap, picked from the tables that state them.
Returns a
LineMetricsin font units, y up, so itsdescentis negative below the baseline. This is the call to space lines with.Font::layoutreads the same numbers, and spaces its lines byLineMetrics::line_heightunlessLayoutOptions::line_heightnames another.A font states its line spacing in up to three places, which often disagree. For horizontal text the call takes the first of these that states a height above zero. First, the typographic metrics of
OS/2, if the font sets theUSE_TYPO_METRICSbit offsSelectionto ask for them. Then the ascender, descender and line gap ofhhea, or of the largest strike in a bitmap-only font withouthhea(a strike being the set of bitmaps drawn for one size). Then the typographic metrics ofOS/2without the bit. Last, the Windows metrics ofOS/2, with a gap of 0. If none does, the answer is 0.8 of the em above the baseline and 0.2 below it, with no gap.For
Orientation::Verticalthe numbers are those ofvhea, andOS/2is not consulted. They measure across a column of vertical text from its center line: the ascent to the right, and the descent, negative, to the left. Without a usablevhea, a bitmap-only font takes the vertical line metrics of its largest strike. Failing both, or where the numbers state no height above zero, the answer is half an em to each side and no gap.A variable font can move all of these with its
MVARtable. At a location other than the default you get the numbers a file fromFont::instancewould hold there. The first read at a new location builds that instance's tables, which the font keeps in its instance cache,Cache::Instance. Where daegun can't build them, as for a font whoseheadtable is cut short, the call answers as at the default location, thoughFont::instancethere fails.use daegun::{Location, Orientation}; let line = font.line_metrics(&Location::default(), Orientation::Horizontal); // Inter: 1984 above the baseline, 494 below it and no gap, so baselines sit 2478 units apart. assert_eq!((line.ascent, line.descent, line.line_gap), (1984.0, -494.0, 0.0)); assert_eq!(line.line_height(), 2478.0); // From one baseline to the next at 16 px: about 19.4 pixels. let px = line.line_height() * 16.0 / f64::from(font.units_per_em()); // Vertical text measures across the column. Inter has no vhea table, so half an em each way. let column = font.line_metrics(&Location::default(), Orientation::Vertical); assert_eq!((column.ascent, column.descent), (1024.0, -1024.0));Font::os2pub fn os2(&self, location: &Location) -> Option<Os2>What the font's
OS/2table says of its style and vertical metrics at a location, orNoneif the font has no such table.OS/2is where a font records its weight and width, its style bits, the embedding its license allows and two sets of vertical metrics. The call returns them as anOs2, with the metrics in font units.Nonemeans the font has noOS/2table, or one too short to hold its version. A field of the result isNonewhere the table stops before that field.At the default location the fields are the table as stored. At another location of a variable font they are those of the instance there, as
Font::instancewould write them: the weight class follows thewghtaxis and the width class thewdthaxis, the bold, italic, regular and oblique bits are rewritten to describe the instance, andMVARmoves the metrics. Where daegun can't build that instance, as for a font whoseheadtable is cut short, the call answers as at the default location, thoughFont::instancethere fails.The first read at a new location builds that instance's tables, which the font keeps in its instance cache,
Cache::Instance. After that the call is a lookup.use daegun::{Location, Tag}; if let Some(os2) = font.os2(&Location::default()) { // Inter's default instance: weight 400, normal width, marked regular. assert_eq!((os2.weight_class, os2.width_class), (Some(400), Some(5))); assert!(os2.is_regular() && !os2.is_bold()); } // At a weight of 700 the answer is that of the bold instance. let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); let os2 = font.os2(&bold).expect("Inter has an OS/2 table"); assert_eq!(os2.weight_class, Some(700)); assert!(os2.is_bold());Font::pdf_flagspub fn pdf_flags(&self, location: &Location) -> PdfFlagsThe flags a PDF font descriptor would carry for the font at a location.
A PDF that embeds a font describes it in a font descriptor, whose
Flagsentry is a set of bits saying what kind of font it is. This call works that set out from the font's tables and returns it as aPdfFlags.PdfFlags::bitsis the integer to write.Six flags can come back. One of
PdfFlags::SYMBOLICandPdfFlags::NONSYMBOLICis always set, and never both, so the result is never empty.PdfFlags::FIXED_PITCHcomes frompost,PdfFlags::SERIFandPdfFlags::SCRIPTfrom the family class ofOS/2, andPdfFlags::ITALICfromFont::italic_angle. PDF's other flags, for all capitals, small capitals and forced bold, are never set.The location matters only to
PdfFlags::ITALIC, and only on a variable font with aslntaxis, where the angle follows the axis. Where daegun can't build the instance at a location, as for a font whoseheadtable is cut short, the call answers as at the default location, thoughFont::instancethere fails.To tell symbolic from nonsymbolic the call walks the font's whole character map each time, so keep the answer when you need it more than once.
use daegun::metrics::PdfFlags; use daegun::Location; let flags = font.pdf_flags(&Location::default()); // Inter maps characters beyond the standard Latin set, so PDF counts it as symbolic. assert!(flags.contains(PdfFlags::SYMBOLIC)); assert!(!flags.contains(PdfFlags::NONSYMBOLIC)); // The integer for the /Flags entry of the font descriptor. assert_eq!(flags.bits(), 4);Font::statpub fn stat(&self, location: &Location) -> Option<Stat>The font's
STATtable at a location: its design axes and the names it gives to values on them, orNoneif it has none.STAT, the style attributes table, is how a font says what its styles are called. It lists the axes of its design, such as weight and width, and names for places on them, such asBoldat a weight of 700. An app reads it to put style names together and to group the fonts of a family in a menu. A font need not be variable to have one.Nonemeans the font has noSTATtable, or one too short to hold its header. A value that does not read is left out and the rest still comes back: one of a format the table does not define, one that runs past the table, or one naming an axis the table does not list.At the default location you get the table as stored, with every value the font names. At another location of a variable font you get the table of the instance there, as
Font::instancewould write it: every axis, but only the values that describe that location. A value on an axis the font varies stays only if it names the coordinate there or its range holds it, and where several do, one is kept for that axis, as OpenType picks it: at Source Serif 4's weight 650, Bold, from 650 to 750, stays and Semibold, from 550 to 650, goes. A value markedolder_siblingstays whenever it holds, and a combination only where all its pairs hold. Values on an axis the font does not vary all stay. Where daegun can't build that instance, as for a font whoseheadtable is cut short, the call answers as at the default location, thoughFont::instancethere fails.The names are read from the name table of that same instance, so a name the instance rewrites reads as rewritten. Each call parses the table and copies its names into new strings. Keep the
Statif you need it often.use daegun::metrics::StatAxisValue; use daegun::{Location, Tag}; let stat = font.stat(&Location::default()).expect("Inter has a STAT table"); // Inter describes three axes and names twelve values on them. assert_eq!((stat.axes.len(), stat.values.len()), (3, 12)); // At a weight of 700 only the values that describe that instance are left. let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); let stat = font.stat(&bold).expect("and at every location"); let names: Vec<&str> = stat .values .iter() .filter_map(|value| match value { StatAxisValue::Single { name, .. } | StatAxisValue::Linked { name, .. } => name.as_deref(), _ => None, }) .collect(); assert_eq!(names, ["Text", "Bold", "Roman"]);Font::trackingpub fn tracking(&self, point_size: f64, orientation: Orientation) -> f64What the font's
traktable adds between glyphs at a point size, in font units, or 0 if it has none.trakis a table of Apple's that tightens or loosens the spacing of a font depending on the size the text is set at. The answer is the amount to add to the advance of each glyph, negative to tighten.point_sizeis the size of the text in points. A size between two the table lists is interpolated in a straight line, and a size past either end takes the value at that end. A size that is not finite and above zero is read asmetrics::DEFAULT_POINT_SIZE.Only the normal track is read, the one whose track value is 0. A table without one answers from the tracks nearest 0: a straight line between the two either side of it, or the nearest alone where all lie to one side.
Orientation::Verticalreads the data the table keeps for vertical text. 0 comes back where the font has notraktable, the table is not version 1, or it holds no data for that orientation.It takes no location, since the table is the same at every one.
Shaping applies tracking by itself, at the size
ShapeOptions::with_point_sizenames. For a font that has aSTATtable as well,Font::shapeadds this amount, rounded to a whole unit, to each glyph that starts a grapheme. A base with its marks gets it once, and so does a ligature, however many characters it joins. So do not add it to a shaped run again.use daegun::{Orientation, Tag}; let tracking = font.tracking(9.0, Orientation::Horizontal); // Inter has no trak table, so nothing is added at any size. assert!(!font.has_table(Tag::new(b"trak"))); assert_eq!(tracking, 0.0);Font::typographic_metricspub fn typographic_metrics(&self, location: &Location) -> TypographicMetricsThe font's measures for setting text at a location: x-height, underline, strikeout, subscript and superscript.
Returns a
TypographicMetricsin font units. Every field is anOption, andNonemeans the font has no table or no field to read it from. The underline comes frompost. The rest comes fromOS/2: the x-height from a table of version 2 or later long enough to hold the cap height after it, the others from any version.Noneonly says the font has no place for the number. A field that is there may still hold a 0: Noto Color Emoji answersSome(0.0)for its x-height.A variable font can move every one of them with its
MVARtable. At a location other than the default you get the numbers a file fromFont::instancewould hold there. In Inter the underline thickens with the weight, and the x-height drops as the optical size grows. Where daegun can't build that instance, as for a font whoseheadtable is cut short, the call answers as at the default location, thoughFont::instancethere fails.use daegun::{Location, Tag}; let metrics = font.typographic_metrics(&Location::default()); // Inter's lowercase is 1118 units tall, and its underline sits 348 units below the baseline. assert_eq!(metrics.x_height, Some(1118.0)); if let Some(underline) = metrics.underline { assert_eq!((underline.position, underline.thickness), (-348.0, 140.0)); } // At a weight of 700 the underline is thicker and closer. let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); let underline = font.typographic_metrics(&bold).underline.expect("Inter has a post table"); assert_eq!((underline.position, underline.thickness), (-323.0, 190.0));metrics::LineMetrics::line_heightpub fn line_height(&self) -> f64The distance from one baseline to the next: the ascent minus the descent, plus the line gap.
In font units, so multiply by
px / f64::from(font.units_per_em())for pixels. The descent is negative below the baseline, which is why it is subtracted.This is the font's own line height, the one
Font::layoutuses when its options name none.use daegun::{Location, Orientation}; let line = font.line_metrics(&Location::default(), Orientation::Horizontal); // STIX Two Math: 762 up, 238 down and a gap of 250 put baselines 1250 units apart. assert_eq!((line.ascent, line.descent, line.line_gap), (762.0, -238.0, 250.0)); assert_eq!(line.line_height(), 1250.0);metrics::Os2::is_boldpub fn is_bold(&self) -> boolWhether the font marks itself bold: bit 5 of
selection.False where the table is too short to hold
fsSelection.The bit names a style, not a weight. It says this is the bold of a family of regular, italic, bold and bold italic. To ask how heavy a face is, read
weight_class.On an
Os2read at a location of a variable font, the bit is the oneFont::instancewould write there. At a named instance of a font with awghtaxis, it is set where the weight is 700 or more and the style name says nothing beyond Bold, Italic, Regular and Oblique. Where no named instance sits, it follows the font's own subfamily name. So Inter is marked bold at its Bold instance, weight 700, but not at Black, weight 900, nor at 650, which no instance names.use daegun::{Location, Tag}; let regular = font.os2(&Location::default()).expect("Inter has an OS/2 table"); assert!(!regular.is_bold()); let bold = font.os2(&font.location(&[(Tag::new(b"wght"), 700.0)])).expect("at every location"); assert!(bold.is_bold()); // Black is heavier, but its style is not named Bold. let black = font.os2(&font.location(&[(Tag::new(b"wght"), 900.0)])).expect("at every location"); assert!(!black.is_bold()); assert_eq!(black.weight_class, Some(900));metrics::Os2::is_italicpub fn is_italic(&self) -> boolWhether the font marks itself italic: bit 0 of
selection.False where the table is too short to hold
fsSelection. It is what the font says of itself, not a measure of its glyphs. For the angle of the slant, seeFont::italic_angle.On an
Os2read at a location of a variable font, the bit is the oneFont::instancewould write for that instance.use daegun::{Font, Location}; let upright = font.os2(&Location::default()).expect("Inter has an OS/2 table"); assert!(!upright.is_italic()); let italic = Font::from_collection(&bytes("Irianisadfstd/IrianisadfstdItalic.ttc"), 0)?; let os2 = italic.os2(&Location::default()).expect("so does the italic of Irianis ADF"); assert!(os2.is_italic());metrics::Os2::is_obliquepub fn is_oblique(&self) -> boolWhether the font marks itself oblique: bit 9 of
selection.An oblique face is an upright design slanted, where an italic is drawn as a style of its own.
OS/2defines the bit from version 4 on, but daegun reads it in any version, since fonts set it in older tables. False where the table is too short to holdfsSelection.On an
Os2read at a location of a variable font with aslntaxis, the bit is set where that axis is off 0 and the table is version 4 or later, and cleared where the axis is at 0.use daegun::{Font, Location}; let os2 = font.os2(&Location::default()).expect("Inter has an OS/2 table"); assert!(!os2.is_oblique()); // An italic is not an oblique: the italic of Irianis ADF sets the italic bit alone. let italic = Font::from_collection(&bytes("Irianisadfstd/IrianisadfstdItalic.ttc"), 0)?; let os2 = italic.os2(&Location::default()).expect("it has the table too"); assert!(os2.is_italic() && !os2.is_oblique());metrics::Os2::is_regularpub fn is_regular(&self) -> boolWhether the font marks itself regular: bit 6 of
selection.A font sets the bit to say it is neither bold nor italic. False where the table is too short to hold
fsSelection.On an
Os2read at a location of a variable font, the bit is set whenever neither the bold bit nor the italic bit is. It says nothing of the weight: Inter's Black instance, weight 900, reads as regular.use daegun::{Location, Tag}; let os2 = font.os2(&Location::default()).expect("Inter has an OS/2 table"); assert!(os2.is_regular()); // At the Bold instance the bold bit is set in its place. let bold = font.os2(&font.location(&[(Tag::new(b"wght"), 700.0)])).expect("at every location"); assert!(!bold.is_regular() && bold.is_bold());metrics::Os2::uses_typo_metricspub fn uses_typo_metrics(&self) -> boolWhether the font asks for its typographic metrics to space lines: bit 7 of
selection,USE_TYPO_METRICS.When it is true,
Font::line_metricstakestypo_metricsahead of the numbers inhhea. When it is false,hheacomes first.OS/2defines the bit from version 4 on, but daegun reads it in any version. False where the table is too short to holdfsSelection.use daegun::{Location, Orientation}; let os2 = font.os2(&Location::default()).expect("Inter has an OS/2 table"); // Inter asks for its typographic metrics, and line_metrics answers with them. assert!(os2.uses_typo_metrics()); assert_eq!(os2.typo_metrics, Some(font.line_metrics(&Location::default(), Orientation::Horizontal)));metrics::PdfFlags::bitspub const fn bits(self) -> u32The flags as the integer a PDF writes in the
Flagsentry of a font descriptor.Each flag is one bit: 1 for
PdfFlags::FIXED_PITCH, 2 forPdfFlags::SERIF, 4 forPdfFlags::SYMBOLIC, 8 forPdfFlags::SCRIPT, 32 forPdfFlags::NONSYMBOLICand 64 forPdfFlags::ITALIC. The integer is their sum. It is aconst fn.use daegun::metrics::PdfFlags; use daegun::Location; let flags = font.pdf_flags(&Location::default()); let entry = format!("/Flags {}", flags.bits()); // Inter is symbolic and nothing else, so the entry reads "/Flags 4". assert_eq!(entry, "/Flags 4"); assert_eq!((PdfFlags::SERIF | PdfFlags::ITALIC).bits(), 2 + 64);metrics::PdfFlags::containspub const fn contains(self, other: PdfFlags) -> boolWhether every flag in
otheris set in this set.Pass one constant to test one flag, or several joined with
|to ask for all of them at once. An emptyotheris contained in every set. It is aconst fn.use daegun::metrics::PdfFlags; use daegun::Location; let flags = font.pdf_flags(&Location::default()); // STIX Two Math is serif and symbolic, and not italic. assert!(flags.contains(PdfFlags::SERIF)); assert!(flags.contains(PdfFlags::SERIF | PdfFlags::SYMBOLIC)); // Both must be set, and italic is not. assert!(!flags.contains(PdfFlags::SERIF | PdfFlags::ITALIC));metrics::PdfFlags::emptypub const fn empty() -> PdfFlagsThe set with no flags in it.
The same value as
PdfFlags::default(), as aconst fn. Start from it to collect flags with|=.Font::pdf_flagsnever returns it, since a font is always either symbolic or nonsymbolic.use daegun::metrics::PdfFlags; // The flags a search for a slanted serif face asks for. let mut wanted = PdfFlags::empty(); wanted |= PdfFlags::SERIF; wanted |= PdfFlags::ITALIC; assert_eq!(wanted.bits(), 66); assert_eq!(PdfFlags::empty(), PdfFlags::default());metrics::PdfFlags::is_emptypub const fn is_empty(self) -> boolWhether no flag is set.
Its main use is on what
&returns, to ask whether two sets share any flag. It is aconst fn.use daegun::metrics::PdfFlags; use daegun::Location; let flags = font.pdf_flags(&Location::default()); // What a font reports is never empty: it is symbolic or nonsymbolic. assert!(!flags.is_empty()); // Is it flagged as a serif or a script face? Inter is neither. let styled = flags & (PdfFlags::SERIF | PdfFlags::SCRIPT); assert!(styled.is_empty());
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.
Font::advancepub fn advance(&self, glyph: GlyphId, location: &Location, orientation: Orientation) -> f64How far a glyph moves the pen: its width along a horizontal line, or its height down a vertical one.
The glyph's own advance in font units, at the given location of a variable font. For pixels, multiply by
px / f64::from(font.units_per_em()).It is the advance of the glyph alone, with no kerning against its neighbors. To measure or set a string, use
Font::shape, whose advances already hold the kerning.With
Orientation::Horizontalthe advance comes from the font'shmtxtable, or in a font of bitmaps alone that has none, from the metrics its bitmaps state. Where neither gives one, the glyph advances by half an em.With
Orientation::Verticalit comes from the font'svmtxtable, or in a font of bitmaps alone that has none, from the metrics its bitmaps state. Where neither gives one, the glyph advances by the height of the font's line, the same for every glyph. That height is the typographic ascender less the typographic descender of theOS/2table where the font asks for those to be used (its USE_TYPO_METRICS flag), else the ascender less the descender of thehheatable, or for a font of bitmaps alone without one, of its largest bitmap size. A font with none of these takes one em. Where the font asks for the typographic pair, this is notFont::ascenderlessFont::descender, which readhhea.A glyph id past the font's last glyph is not an error. Where the font has the metrics table for that direction it advances 0 at the default instance, though at another location a variable font may move it by what its variations add. Where the font has no such table it takes the amount above.
For many glyphs at once,
Font::advancesfills a list in one call.use daegun::{GlyphId, Location, Orientation, Tag}; let glyph = font.glyph_id('A').unwrap_or(GlyphId::NOTDEF); let width = font.advance(glyph, &Location::default(), Orientation::Horizontal); // Inter's A advances 1413 units, which is about 11 pixels at 16 px. let pixels = width * 16.0 / f64::from(font.units_per_em()); // At weight 900, the heaviest Inter has, it is wider. let black = font.location(&[(Tag::new(b"wght"), 900.0)]); assert_eq!(font.advance(glyph, &black, Orientation::Horizontal), 1628.0); // Inter has no vertical metrics, so down a line every glyph advances by the height of the line. assert_eq!(font.advance(glyph, &Location::default(), Orientation::Vertical), 2478.0);Font::advancespub fn advances(&self, glyphs: &[GlyphId], location: &Location, orientation: Orientation, out: &mut Vec<f64>)The advance of each glyph in a list, written into a
Vecyou keep.Each advance is what
Font::advancegives for that glyph, in font units, in the order ofglyphs.outis cleared first and then holds one advance per glyph. What it held is gone but its capacity stays, so a buffer kept between calls allocates only when a list is longer than any before it.It reads the location once for the whole list, which makes it the call for a line of glyphs. Like
Font::advance, it gives the glyphs' own advances with no kerning.use daegun::{GlyphId, Location, Orientation}; let glyphs: Vec<GlyphId> = font.glyph_ids("Wave").flatten().collect(); let mut advances = Vec::new(); font.advances(&glyphs, &Location::default(), Orientation::Horizontal, &mut advances); // One advance a glyph. Inter's add up to 5513 units, the width of "Wave" before kerning. assert_eq!(advances.len(), glyphs.len()); assert_eq!(advances.iter().sum::<f64>(), 5513.0); // The same buffer again: cleared, then filled for the next list. font.advances(&glyphs[..2], &Location::default(), Orientation::Horizontal, &mut advances); assert_eq!(advances, [2018.0, 1150.0]);Font::coveragepub fn coverage(&self) -> impl DoubleEndedIterator<Item = (char, GlyphId)> + FusedIterator + use<>Every character the font maps to a glyph, in code point order, each with its glyph.
It walks the font's
cmaptable, the oneFont::glyph_idlooks characters up in, and yields each(char, GlyphId)pair in rising order of code point. Use it to list what a font supports, or to build a table for font fallback.A code point that is not a
char, such as a lone surrogate, is left out, and so is a character the font maps to glyph 0. No pair holdsGlyphId::NOTDEF.Each call reads the whole table into a list before it returns, and the iterator owns that list, so it does not borrow the font. Collect it once and keep the result, instead of calling it for every question.
use daegun::GlyphId; let coverage: Vec<(char, GlyphId)> = font.coverage().collect(); // Inter maps 2852 characters. assert_eq!(coverage.len(), 2852); // The pairs come in code point order, so the list can be binary searched. let found = coverage.binary_search_by_key(&'A', |&(c, _)| c).map(|i| coverage[i].1); assert_eq!(found, Ok(GlyphId(2)));Font::default_vertical_originpub fn default_vertical_origin(&self) -> f64The vertical origin a font's
VORGtable gives every glyph it does not list.A
VORGtable says where glyphs sit in vertical text: one default height for the font, and a height of its own for each glyph that differs. This is that default, in font units up from the baseline.It is 0 for a font without the table or with one in a version daegun does not read, and for any font with TrueType outlines. So 0 means there is no default, not that the origin is on the baseline. For the origin of a glyph, whatever the font holds, call
Font::vertical_origin.// In Source Han Sans a vertical origin is 880 units above the baseline unless the font lists // another for the glyph. Inter, which has no such table, answers 0. assert_eq!(font.default_vertical_origin(), 880.0);Font::glyph_boundspub fn glyph_bounds(&self, glyph: GlyphId, location: &Location) -> Option<Bounds>The box a glyph's outline covers, or
Nonefor a glyph that draws nothing.The box is tight: it fits the curves themselves, not their control points, so it is the extent of the ink. It is in font units, y up, measured from the glyph's origin on the baseline, at the given location of a variable font.
Nonemeans there is no outline to measure. The glyph is empty, as a space is, or the id is past the last glyph, or the outline can't be decoded, or the font holds no outline for it, as a font of bitmap emoji holds none. That differs from a box of zero size, so handle it and do not read it asBounds::default().It decodes the outline to measure it, so it is more than a table lookup. Keep the box if you need it often.
For the box a font states around all of its glyphs, see
Font::bounds.use daegun::{GlyphId, Location}; let glyph = font.glyph_id('A').unwrap_or(GlyphId::NOTDEF); if let Some(b) = font.glyph_bounds(glyph, &Location::default()) { let (width, height) = (b.x_max - b.x_min, b.y_max - b.y_min); // Inter's A is 1309 units wide and 1490 tall, and stands on the baseline. } // A space draws nothing, so it has no box. let space = font.glyph_id(' ').unwrap_or(GlyphId::NOTDEF); assert_eq!(font.glyph_bounds(space, &Location::default()), None);Font::glyph_classpub fn glyph_class(&self, glyph: GlyphId) -> Option<GlyphClass>The class a font's
GDEFtable gives a glyph: base, ligature, mark or component.Use it to tell marks from the letters they sit on, or to find the ligatures in a run.
Nonewhere the font has noGDEFtable, or has one daegun cannot read, or the table gives the glyph no class. Plenty of glyphs have none, Inter's space among them, so don't readNoneas a base.The class belongs to the glyph, so it is the same at every location of a variable font.
use daegun::shape::ShapeOptions; use daegun::{GlyphClass, Location}; // An Arabic letter with a vowel mark above it. let run = font.shape("بَ", &Location::default(), &ShapeOptions::DEFAULT); let is_mark = |glyph| font.glyph_class(glyph) == Some(GlyphClass::Mark); // Two glyphs, one of them a mark. assert_eq!(run.glyphs.len(), 2); assert_eq!(run.glyphs.iter().filter(|&&glyph| is_mark(glyph)).count(), 1);Font::glyph_idpub fn glyph_id(&self, c: char) -> Option<GlyphId>The glyph the font maps a character to, or
Noneif it has none.A lookup in the font's
cmaptable, its map from characters to glyphs.Nonemeans the font can't draw the character, which is the cue to try another font or to drawGlyphId::NOTDEF. A character the font maps to glyph 0 counts as unmapped too, so the answer is never glyph 0.This is one character to one glyph and nothing more. It knows nothing of ligatures, of the forms a letter takes inside a word, or of marks, so the glyphs of real text come from
Font::shape.The answer is the same at every location of a variable font.
use daegun::GlyphId; // Inter keeps its A at index 2. assert_eq!(font.glyph_id('A'), Some(GlyphId(2))); // It has no Japanese, so there is nothing to draw this character with. assert_eq!(font.glyph_id('語'), None);Font::glyph_idspub fn glyph_ids(&self, text: &str) -> impl DoubleEndedIterator<Item = Option<GlyphId>> + FusedIterator + CloneThe glyph for each character of a string,
Nonefor a character the font has no glyph for.An iterator that yields one item per
charoftext, in order, each whatFont::glyph_idgives for that character. It looks each character up as you ask for it.It maps characters and does not shape them: no ligatures, no kerning, no reordering and no joined forms for a script such as Arabic. Use it to check what a font covers, or to get glyphs for
Font::advances. For text you mean to draw, useFont::shape.Items come one per character, not one per byte, so pair them with
text.chars()ortext.char_indices()to know which character each belongs to.use daegun::GlyphId; let text = "a語b"; let ids: Vec<Option<GlyphId>> = font.glyph_ids(text).collect(); // One per character. Inter has no glyph for the middle one. assert_eq!(ids.len(), 3); assert!(ids[0].is_some() && ids[1].is_none() && ids[2].is_some()); // To draw anyway, put the font's missing glyph where there is none. let glyphs: Vec<GlyphId> = font.glyph_ids(text).map(|id| id.unwrap_or(GlyphId::NOTDEF)).collect(); assert_eq!(glyphs[1], GlyphId::NOTDEF);Font::glyph_namepub fn glyph_name(&self, glyph: GlyphId) -> Option<&str>A glyph's name, such as
Aoracutecomb, orNoneif the font does not name it.The name comes from the font's
posttable, or, where that gives none, from the glyph names a CFF font carries. It is what the designer called the glyph, useful in a debugger, a glyph inspector or an error message. It is not text: for the character a glyph stands for, go by the text you shaped.Nonewhere neither source names the glyph. A font may ship without names: Source Han Sans and Noto Color Emoji name none of their glyphs. A name the font stores as empty, as longer than 63 bytes or as bytes that are not UTF-8 counts as none too.The string borrows from the font. The first name you ask for makes the font index where its names lie, and it keeps that index, so later calls are lookups.
use daegun::GlyphId; let glyph = font.glyph_id('A').unwrap_or(GlyphId::NOTDEF); assert_eq!(font.glyph_name(glyph), Some("A")); // U+0301, the combining acute accent. let accent = font.glyph_id('\u{301}').unwrap_or(GlyphId::NOTDEF); assert_eq!(font.glyph_name(accent), Some("acutecomb")); assert_eq!(font.glyph_name(GlyphId::NOTDEF), Some(".notdef"));Font::glyph_namespub fn glyph_names( &self, ) -> impl ExactSizeIterator<Item = Option<&str>> + DoubleEndedIterator + FusedIterator + CloneEvery glyph's name in glyph id order,
Nonefor a glyph the font does not name.An iterator with one item per glyph of the font: item
iis whatFont::glyph_namegives forGlyphId(i), and itslen()isFont::glyph_count. The names borrow from the font.A font without glyph names still yields an item for every glyph, each of them
None.let names: Vec<Option<&str>> = font.glyph_names().collect(); // One entry a glyph: Inter has 2937 of them. assert_eq!(names.len(), 2937); assert_eq!(names[..3], [Some(".notdef"), Some(".null"), Some("A")]); // Find a glyph by its name. The position is its glyph id. let position = font.glyph_names().position(|name| name == Some("acutecomb")); assert_eq!(position, Some(1770));Font::has_glyphpub fn has_glyph(&self, c: char) -> boolWhether the font has a glyph for a character.
True exactly when
Font::glyph_idanswersSome. A character the font maps to glyph 0,.notdef, counts as one it lacks.It is the test font fallback turns on: go through your fonts and take the first that has the character.
assert!(font.has_glyph('A')); // Inter has no Japanese, so this character needs another font. assert!(!font.has_glyph('語'));Font::ligature_caretspub fn ligature_carets(&self, glyph: GlyphId, location: &Location, orientation: Orientation) -> Vec<Option<f64>>Where the font says a text cursor may sit inside a ligature: one position for each caret its
GDEFtable lists.A ligature draws several characters as one glyph, so a cursor moving through the text has to stop inside the glyph. A font can say where: for an ffi ligature, two carets, one after each f. This returns them in the order the font lists them, in font units, at the given location of a variable font.
With
Orientation::Horizontaleach is an x in the glyph's own coordinates. WithOrientation::Verticaleach is a y, for a ligature set in a vertical line. A vertical caret that the font ties to a point of the outline is measured from the glyph's vertical origin, so it is negative below that origin.The list is empty where the font has no
GDEFtable, or has one daegun cannot read, or lists no carets for the glyph. Many fonts list none, even for their ligatures: EB Garamond gives none for its fi. An entry isNonewhere the font lists a caret that can't be resolved, such as one tied to an outline point the glyph does not have.Font::caret_positionsuses these already, and spaces carets evenly where the font gives none. Call this when you place carets yourself.use daegun::shape::ShapeOptions; use daegun::{Location, Orientation}; // A font that draws "ffi" as one ligature glyph. let run = font.shape("ffi", &Location::default(), &ShapeOptions::DEFAULT); let carets = font.ligature_carets(run.glyphs[0], &Location::default(), Orientation::Horizontal); // Two carets for three letters: after the first f at x = 300, and after the second at x = 600. assert_eq!(carets, [Some(300.0), Some(600.0)]); // A glyph that is no ligature has none. let f = font.shape("f", &Location::default(), &ShapeOptions::DEFAULT).glyphs[0]; assert!(font.ligature_carets(f, &Location::default(), Orientation::Horizontal).is_empty());Font::mark_attachment_classpub fn mark_attachment_class(&self, glyph: GlyphId) -> Option<core::num::NonZeroU32>The mark attachment class a font's
GDEFtable gives a glyph, orNoneif it gives none.A font can sort its marks into numbered classes, for example marks that sit above a letter and marks that sit below it. Its layout rules use the classes to work on one kind of mark and pass over the rest. The numbers are the font's own and mean nothing in another font.
Nonewhere the font has noGDEFtable, or has one daegun cannot read, or gives the glyph no class, which the table stores as class 0. The class comes as aNonZeroU32, andget()gives the number. A font with the wider 24-bit class tables can use numbers past 65,535.// U+0300 is the combining grave accent, which sits above a letter. U+0326 is a comma below one. let class_of = |c: char| font.glyph_id(c).and_then(|glyph| font.mark_attachment_class(glyph)); // Source Serif puts them in classes 1 and 2. assert_eq!(class_of('\u{300}').map(|class| class.get()), Some(1)); assert_eq!(class_of('\u{326}').map(|class| class.get()), Some(2)); // A letter is in no class. assert_eq!(class_of('A'), None);Font::variation_glyph_idpub fn variation_glyph_id(&self, c: char, selector: char) -> Option<GlyphId>The glyph for a character followed by a variation selector, or
Noneif the font lists no such pair.A variation selector is an invisible character that asks for one particular form of the character before it: U+FE0F asks for the emoji form of a symbol, and U+E0100 onward pick among the registered forms of a CJK ideograph. The font's
cmaptable lists the pairs it knows, and this looks one up.Where the font lists the pair with a glyph of its own, you get that glyph. Where it lists the pair as the character's usual form, you get what
Font::glyph_idgives for the character.Nonemeans the font does not list the pair, and the plain glyph of the character is then the one to draw. It is alsoNonewhere the font lists the pair as the usual form of a character it has no glyph for. A pair the font maps to glyph 0 counts as unlisted, so the answer is never glyph 0.Font::shapeapplies variation selectors already. Call this when you map characters to glyphs yourself.// U+E0100 and U+E0101 are variation selectors, each asking for one form of the character before it. let plain = font.glyph_id('葛'); let variant = font.variation_glyph_id('葛', '\u{E0100}'); // Source Han Sans has a glyph of its own for the first form. assert!(variant.is_some() && variant != plain); // For the second it uses the usual glyph of the character. assert_eq!(font.variation_glyph_id('葛', '\u{E0101}'), plain); // And it lists no such form of A. assert_eq!(font.variation_glyph_id('A', '\u{E0100}'), None);Font::vertical_originpub fn vertical_origin(&self, glyph: GlyphId, location: &Location) -> f64Where a glyph's origin lies for vertical text, as a height above its baseline.
Horizontal text sets each glyph on the baseline. Vertical text hangs each glyph from a point at its top instead, its vertical origin. This is how far above the baseline that point lies, in font units, at the given location of a variable font.
The font decides it in one of three ways. A font with a
VORGtable states it, glyph by glyph or by its default. Failing that, a font with TrueType outlines and vertical metrics, avmtxtable, puts it at the top of the glyph's box plus the glyph's top side bearing. Any other font centers the glyph's box in a span as tall as its line and answers the top of that span: the top of the box plus half of what the line's height has left over, rounded down to a whole unit. The line's height is the oneFont::advancefalls back to down a line, which is not alwaysFont::ascenderlessFont::descender. The box is the outline's, or for a color glyph the box of its image or its clip box, so it can exist whereFont::glyph_boundsgivesNone.Every glyph id gets an answer. A glyph that draws nothing, such as a space, answers half the line's height where boxes are centered, and its top side bearing alone under the
vmtxrule. A glyph id past the font's last glyph answers the default ofVORG, 0 under thevmtxrule, and the top of the line, its ascender, where boxes are centered.Shaping uses it already: in a run shaped with
Direction::TopToBottom, the offsets place each glyph by its vertical origin. Call this when you set vertical glyphs yourself.use daegun::shape::{Direction, ShapeOptions}; use daegun::{GlyphId, Location}; let glyph = font.glyph_id('日').unwrap_or(GlyphId::NOTDEF); let origin = font.vertical_origin(glyph, &Location::default()); // Source Han Sans hangs this glyph from a point 880 units above its baseline. assert_eq!(origin, 880.0); // A vertical run has it in its offsets: the glyph is drawn that far below the pen. let down = ShapeOptions::DEFAULT.with_direction(Direction::TopToBottom); let run = font.shape("日", &Location::default(), &down); assert_eq!(run.offsets[0].y, -origin);
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.
Font::caret_positionspub fn caret_positions(&self, text: &str, location: &Location, orientation: Orientation) -> Vec<f64>Where the text cursor sits before each byte of a string, for hit testing and for drawing a caret.
Returns
text.len() + 1positions in font units, measured from the left edge of the text, or from its top withOrientation::Vertical. Index the result with a byte offset:carets[i]is the caret before the grapheme that byteibelongs to, a grapheme being a character as a reader sees it, and the last entry is the text's trailing edge. Every byte of a grapheme holds its leading edge, the bytes of a combining mark too, so any offset is safe to index and no caret falls between a letter and its marks.Horizontal text is shaped the way
Font::shape_bidishapes it withBaseDirection::AutoandShapeOptions::DEFAULT, so the carets match what those runs draw, right-to-left parts included. Vertical text is shaped as one run from top to bottom. The call takes no base direction and no options: text you drew with another base direction, or with features, a language or any other option, may sit elsewhere than these carets say.Inside a ligature the caret moves through the glyph: to the positions the font's own caret table gives, or evenly spaced where it gives none.
use daegun::{Location, Orientation}; let text = "fit"; let carets = font.caret_positions(text, &Location::default(), Orientation::Horizontal); assert_eq!(carets.len(), text.len() + 1); // EB Garamond draws "fi" as one ligature glyph, and carets[1] still falls inside it, between // the f and the i: [0.0, 259.0, 518.0, 832.0].Font::shapepub fn shape(&self, text: &str, location: &Location, options: &ShapeOptions) -> Arc<ShapedRun>Shapes a string into positioned glyphs, applying the font's ligatures, kerning, mark placement and reordering.
The call most text starts from. It works out the script and direction of the text, runs the shaping model for that script, applies the font's substitution and positioning tables (
GSUBandGPOS, or Apple'smorxandkerx) and returns aShapedRun. Advances and offsets are in font units, so a pen position in pixels isadvance * px / f64::from(font.units_per_em()).locationpicks the instance of a variable font.&Location::default()is the default instance, and works for any font.There is no failure to handle. A character the font has no glyph for becomes
ShapeOptions::not_found_glyph, which is.notdefunless you set it. Three kinds are drawn another way where the font can. An accented letter is built from a letter and a mark it has. A space of a set width, an em space for one, is its plain space at that width. A non-breaking hyphen is its hyphen, U+2010. Invisible characters followIgnorablesinstead.ShapedRun::completeis false only where a hostile font made shaping stop short.The run comes back in an
Arc. A request with plain options comes from the font's shape cache, so asking again for the same text is as a rule a lookup that returns the sameArc:ShapeOptionssays which requests are kept. A very long run is not kept, and is shaped again on every call: one that takes more than an eighth of the cache's budget, or 64 KB where that is more. At the default budget of 8 MB that is roughly 30,000 glyphs, or roughly 1,900 in a build with thethreadingfeature, which splits a budget of 4 MB or more over 16 lists and counts an eighth of one. Threads shaping on one font never wait on that cache: one that finds it busy shapes the run itself.It shapes the whole string as one run in one direction. Control characters get no special treatment: a line feed or a tab is looked up in the font like a letter and becomes the not-found glyph where the font has none for it, and nothing breaks the line or moves to a tab stop. For text that may mix directions use
Font::shape_bidi, and for a paragraph that wraps, or text with line breaks or tabs in it, useFont::layout.use daegun::shape::ShapeOptions; use daegun::Location; let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); let mut x = 0.0; for ((glyph, advance), offset) in run.glyphs.iter().zip(&run.advances).zip(&run.offsets) { // Draw `glyph` at (x + offset.x, offset.y), in font units. x += advance; } // With Inter: 4 glyphs, and x ends at 5339.0, the run's width. Kerning is already in the advances.Font::shape_bidipub fn shape_bidi( &self, text: &str, location: &Location, base: BaseDirection, options: &ShapeOptions, ) -> Vec<BidiRun>Shapes text that may mix directions, such as Arabic inside English, and returns its runs in the order they are drawn.
It runs the Unicode bidirectional algorithm over the text, cuts each directional run again wherever the script changes, and shapes every piece with its own direction and script. Each piece is shaped with the text around it as context, so letters still join across the cuts. You get one
BidiRunper piece, in visual order from the left.baseis the direction of the paragraph.BaseDirection::Autolets the first strongly directional character decide.The options apply to every run, with three exceptions. Their
directionis not read, since each run takes the direction the algorithm gave it. Theirbeforeandafterare not read either: the context of each run is the rest of the string around it, so the string is shaped as if nothing came before or after it. And options that name ascriptstop the cutting by script, so each directional run stays whole. Aseed_scriptstands in for a run whose text has no script to take, such as digits and punctuation alone, since digits and spaces beside letters take the letters' script. When the options also name ascript, the seed script is used for every run.A
Featureover a byte range counts its bytes from the start of each run, not of the string, so the same range lands in every run. Use features that cover the whole text here.No line is broken, and a string with no paragraph separator in it is treated as a single line. A paragraph ends at a line feed, a carriage return, the two together, or another character Unicode classes as a paragraph separator, such as U+0085 or U+2029. The line separator U+2028 and a vertical tab do not end one. Each paragraph is put in visual order on its own, takes its own direction under
BaseDirection::Auto, and its runs follow those of the paragraph before it, with the separator shaped as a glyph in its run. Split the text into paragraphs before you call this, or useFont::layout, which does the same work line by line for a paragraph that wraps.use daegun::shape::ShapeOptions; use daegun::unicode::BaseDirection; use daegun::Location; let text = "Read مرحبا aloud"; let runs = font.shape_bidi(text, &Location::default(), BaseDirection::Auto, &ShapeOptions::DEFAULT); let mut pen = 0.0; for bidi in &runs { let right_to_left = bidi.level % 2 == 1; // Draw bidi.run at `pen`. It shows &text[bidi.bytes]. pen += bidi.run.width(); }Font::shape_intopub fn shape_into(&self, text: &str, location: &Location, options: &ShapeOptions, run: &mut ShapedRun)Shapes a string as
Font::shapedoes, into aShapedRunyou already own, reusing its memory.For a loop that shapes many strings. The run's lists keep their capacity between calls, so shaping one string after another into the same run allocates only when a string needs more room than any before it.
What the run held is replaced. The call always shapes afresh: it doesn't read the shape cache and adds nothing to it.
use daegun::shape::{ShapeOptions, ShapedRun}; use daegun::Location; let mut run = ShapedRun::default(); for word in ["three", "one", "two"] { font.shape_into(word, &Location::default(), &ShapeOptions::DEFAULT, &mut run); // `run` now holds this word's glyphs. The first word made the room, and the shorter ones reuse it. }shape::ClusterLevel::is_graphemespub const fn is_graphemes(self) -> boolWhether a cluster spans a whole grapheme at this level.
True for
MonotoneGraphemesandGraphemes, false forMonotoneCharactersandCharacters.use daegun::shape::ClusterLevel; assert!(ClusterLevel::Graphemes.is_graphemes()); assert!(!ClusterLevel::MonotoneCharacters.is_graphemes());shape::ClusterLevel::is_monotonepub const fn is_monotone(self) -> boolWhether clusters stay in text order at this level.
True for
MonotoneGraphemesandMonotoneCharacters, false forCharactersandGraphemes.use daegun::shape::ClusterLevel; assert!(ClusterLevel::MonotoneGraphemes.is_monotone()); assert!(!ClusterLevel::Characters.is_monotone());shape::Feature::newpub const fn new(tag: Tag, value: u32) -> SelfA feature that applies to all of the text.
A
valueof 0 turns the feature off and 1 turns it on. For a byte range, build on it with struct update syntax:Feature { bytes: (3..5).into(), ..Feature::new(tag, 1) }.use daegun::shape::{Feature, ShapeOptions}; use daegun::{Location, Tag}; // Tabular figures, so a column of numbers lines up. let features = [Feature::new(Tag::new(b"tnum"), 1)]; let options = ShapeOptions::DEFAULT.with_features(&features); let run = font.shape("1,204.50", &Location::default(), &options); // Every digit now has the same advance.shape::ShapedRun::widthpub fn width(&self) -> f64The sum of the run's advances: its width, or its height for vertical text.
In font units, so multiply by
px / f64::from(font.units_per_em())for pixels. Kerning is already in the advances, so this is the length the run takes on its line.use daegun::shape::ShapeOptions; use daegun::Location; let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); let pixels = run.width() * 16.0 / f64::from(font.units_per_em()); // Inter sets "Wave" 5339 units wide, which is about 41.7 pixels at 16 px.shape::ShapeOptions::with_beginning_of_textpub const fn with_beginning_of_text(mut self, beginning: bool) -> SelfThese options with whether the run is the very start of the text.
At the start of the text a combining mark has nothing to sit on. With this set, and no text before the run, shaping puts a dotted circle before such a mark where the font has that glyph, unless
ShapeOptions::suppress_dotted_circleis set.use daegun::shape::ShapeOptions; use daegun::Location; // A lone vowel mark, with nothing before it. let mark = "\u{064E}"; let plain = font.shape(mark, &Location::default(), &ShapeOptions::DEFAULT); assert_eq!(plain.glyphs.len(), 1); let options = ShapeOptions::DEFAULT.with_beginning_of_text(true); let run = font.shape(mark, &Location::default(), &options); // A dotted circle now carries the mark. assert_eq!(run.glyphs.len(), 2);shape::ShapeOptions::with_cluster_levelpub const fn with_cluster_level(mut self, cluster_level: ClusterLevel) -> SelfThese options with how clusters are formed.
See
ClusterLevelfor the four levels. The default isClusterLevel::MonotoneGraphemes.use daegun::shape::{ClusterLevel, ShapeOptions}; use daegun::Location; let options = ShapeOptions::DEFAULT.with_cluster_level(ClusterLevel::Characters); let run = font.shape("कि", &Location::default(), &options); // The vowel sign is drawn first and keeps its own cluster, byte 3. assert_eq!(run.clusters, [3, 0]);shape::ShapeOptions::with_contextpub const fn with_context(mut self, before: &'a str, after: &'a str) -> SelfThese options with the text before and after the run.
When you shape a piece of a longer text, pass what surrounds it. An Arabic letter takes a different form depending on its neighbors, and without context a piece shaped alone gets the wrong form at its edges. Shaping reads the 5 characters nearest the run on each side, and reads them for joining only: a kerning pair or a ligature across the edge needs both characters inside the run.
use daegun::shape::ShapeOptions; use daegun::Location; // The letter beh alone takes its isolated form. let alone = font.shape("ب", &Location::default(), &ShapeOptions::DEFAULT); // The same letter in the middle of a word joins on both sides. let options = ShapeOptions::DEFAULT.with_context("ب", "ب"); let joined = font.shape("ب", &Location::default(), &options); assert_ne!(alone.glyphs, joined.glyphs);shape::ShapeOptions::with_directionpub const fn with_direction(mut self, direction: Direction) -> SelfThese options with the direction to shape in.
Without one, shaping takes left to right or right to left from the text's script.
Direction::TopToBottomsets the text vertically.use daegun::shape::{Direction, ShapeOptions}; use daegun::Location; let options = ShapeOptions::DEFAULT.with_direction(Direction::TopToBottom); let run = font.shape("日本語", &Location::default(), &options); // Three glyphs set down the page, each 1000 units below the last in this font. assert_eq!(run.advances, [1000.0, 1000.0, 1000.0]);shape::ShapeOptions::with_featurespub const fn with_features(mut self, features: &'a [Feature]) -> SelfThese options with OpenType features to turn on, off or set.
The slice replaces any features set before. Each
Featurecovers all of the text or a byte range of it.use daegun::shape::{Feature, ShapeOptions}; use daegun::{Location, Tag}; // Standard ligatures off. let features = [Feature::new(Tag::new(b"liga"), 0)]; let options = ShapeOptions::DEFAULT.with_features(&features); let run = font.shape("fi", &Location::default(), &options); // The f and the i stay two glyphs, where the default joins them into one. assert_eq!(run.glyphs.len(), 2);shape::ShapeOptions::with_ignorablespub const fn with_ignorables(mut self, ignorables: Ignorables) -> SelfThese options with what to do with default ignorables, the invisible characters such as joiners.
See
Ignorablesfor the three choices. They are hidden by default.use daegun::shape::{Ignorables, ShapeOptions}; use daegun::Location; let options = ShapeOptions::DEFAULT.with_ignorables(Ignorables::Remove); // An "a", a zero width joiner and a "b". let run = font.shape("a\u{200D}b", &Location::default(), &options); // The joiner leaves no glyph behind. assert_eq!(run.glyphs.len(), 2);shape::ShapeOptions::with_invisible_glyphpub const fn with_invisible_glyph(mut self, glyph: GlyphId) -> SelfThese options with the glyph that hidden ignorables are drawn with.
It applies under
Ignorables::Hide, the default, where each ignorable stays in the run as a glyph with an advance of 0. Without one that glyph is the font's space. Glyph 0 means no choice, as it is.notdef.use daegun::shape::ShapeOptions; use daegun::{GlyphId, Location}; let options = ShapeOptions::DEFAULT.with_invisible_glyph(GlyphId(5)); // An "a", a zero width joiner and a "b". let run = font.shape("a\u{200D}b", &Location::default(), &options); // The joiner is glyph 5 now, still 0 wide. assert_eq!(run.glyphs[1], GlyphId(5)); assert_eq!(run.advances[1], 0.0);shape::ShapeOptions::with_languagepub const fn with_language(mut self, language: &'a str) -> SelfThese options with the language of the text, as a BCP 47 tag.
Some fonts draw a script differently by language. Turkish keeps its dotted and dotless i apart, so a font that joins f and i into a ligature leaves them separate for
tr. Serbian and Bulgarian use different Cyrillic forms from Russian. Without a language the font uses its default forms.use daegun::shape::ShapeOptions; use daegun::Location; let plain = font.shape("fi", &Location::default(), &ShapeOptions::DEFAULT); // EB Garamond joins f and i into one ligature glyph. assert_eq!(plain.glyphs.len(), 1); let turkish = ShapeOptions::DEFAULT.with_language("tr"); let run = font.shape("fi", &Location::default(), &turkish); // In Turkish it keeps them apart, so the dot of the i stays. assert_eq!(run.glyphs.len(), 2);shape::ShapeOptions::with_not_found_glyphpub const fn with_not_found_glyph(mut self, glyph: GlyphId) -> SelfThese options with the glyph drawn for a character the font has no glyph for.
The default is glyph 0,
.notdef, which most fonts draw as an empty box. Name another to mark missing characters your own way, or to find them in the run so another font can draw them. A few missing characters never become this glyph, as the font draws them another way:Font::shapelists them.use daegun::shape::ShapeOptions; use daegun::{GlyphId, Location}; // Inter has no glyph for the middle character. let plain = font.shape("a語b", &Location::default(), &ShapeOptions::DEFAULT); assert_eq!(plain.glyphs[1], GlyphId::NOTDEF); let options = ShapeOptions::DEFAULT.with_not_found_glyph(GlyphId(7)); let run = font.shape("a語b", &Location::default(), &options); assert_eq!(run.glyphs[1], GlyphId(7));shape::ShapeOptions::with_not_found_variation_selector_glyphpub const fn with_not_found_variation_selector_glyph(mut self, glyph: GlyphId) -> SelfThese options with the glyph drawn for a variation selector the font can't apply.
A variation selector asks for a particular form of the character before it. Where the font has no such form, the selector is normally treated as a default ignorable. With this set it becomes the glyph you name instead, so you can tell that the form was missing.
The glyph takes no advance and no offset, so it draws on top of whatever comes next along the line unless you give it room. With the default cluster level it shares the cluster of the character before it. It stays in the run under
Ignorables::Removetoo.use daegun::shape::ShapeOptions; use daegun::{GlyphId, Location}; // An "a" and a variation selector Inter has no form for. let options = ShapeOptions::DEFAULT.with_not_found_variation_selector_glyph(GlyphId(9)); let run = font.shape("a\u{FE00}", &Location::default(), &options); assert_eq!(run.glyphs[1], GlyphId(9));shape::ShapeOptions::with_point_sizepub const fn with_point_size(mut self, point_size: f64) -> SelfThese options with the point size to read the font's tracking at.
Fonts with a
traktable, mostly Apple's, space their glyphs tighter or looser depending on the size the text is set at. This is that size, in points. daegun tracks only a font that also has aSTATtable. Any other font shapes the same at any size, and a size that isn't finite and above zero falls back tometrics::DEFAULT_POINT_SIZE.use daegun::shape::ShapeOptions; use daegun::Location; let caption = ShapeOptions::DEFAULT.with_point_size(9.0); let run = font.shape("Wave", &Location::default(), &caption); // Inter has no trak table, so the size changes nothing here. assert_eq!(caption.point_size, Some(9.0));shape::ShapeOptions::with_report_tatweel_positionspub const fn with_report_tatweel_positions(mut self, report: bool) -> SelfThese options with
ShapedRun::safe_to_insert_tatweelfilled, or not.A tatweel is the stroke that stretches an Arabic word to justify a line. With this set, the run says which glyphs one may go before in the text, which in a right-to-left run is on the right of the glyph as drawn. Left off, the list stays empty.
use daegun::shape::ShapeOptions; use daegun::Location; let options = ShapeOptions::DEFAULT.with_report_tatweel_positions(true); let run = font.shape("مرحبا", &Location::default(), &options); // An entry per glyph: true where a tatweel may go before it. assert_eq!(run.safe_to_insert_tatweel, [true, true, false, true, false]);shape::ShapeOptions::with_report_unsafe_to_concatpub const fn with_report_unsafe_to_concat(mut self, report: bool) -> SelfThese options with
ShapedRun::unsafe_to_concatfilled, or not.Ask for it when you shape text in pieces and join the runs, and want to know where that is safe. The list then has an entry per glyph. Left off, it stays empty.
use daegun::shape::ShapeOptions; use daegun::Location; let options = ShapeOptions::DEFAULT.with_report_unsafe_to_concat(true); let run = font.shape("Wave", &Location::default(), &options); assert_eq!(run.unsafe_to_concat.len(), run.glyphs.len()); let plain = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT); assert!(plain.unsafe_to_concat.is_empty());shape::ShapeOptions::with_scriptpub const fn with_script(mut self, script: Tag) -> SelfThese options with an OpenType script tag whose lookups to apply.
It names the script whose lookups to take from the font, by its tag, such as
latnorarab. Where the font has no script by that tag, the lookups come from its default script,DFLT, or fromlatnwhere it has none. The direction still comes from the text, but the shaping model can change with the tag. When the lookups end up coming fromDFLTorlatn, whether you named it or the font fell back to it, text of scripts such as the Indic ones and Myanmar is shaped by the general model, with no syllables and no reordering. The tagQaagasks for the Zawgyi model.To shape text as another script, use
ShapeOptions::with_seed_script. InFont::shape_bidi, naming a script also keeps each directional run whole.use daegun::shape::ShapeOptions; use daegun::{Location, Tag}; let options = ShapeOptions::DEFAULT.with_script(Tag::new(b"latn")); let run = font.shape("Wave", &Location::default(), &options); assert_eq!(options.script, Some(Tag::new(b"latn")));shape::ShapeOptions::with_seed_scriptpub const fn with_seed_script(mut self, script: Script) -> SelfThese options with the script to shape the run as.
Normally shaping scans the text for its script. Digits, spaces and punctuation have none of their own, so a run of only those is shaped as plain left-to-right text. Naming a script gives the run the shaping model daegun picks for that script in this font, and that script's direction, whatever the text holds. So a run seeded as Arabic is set right to left unless you also give a direction: digits read left to right inside Arabic too, and need
Direction::LeftToRight.Font::shape_bidiworks both out for each run by itself.use daegun::shape::{Direction, ShapeOptions, Shaper}; use daegun::unicode::Script; use daegun::Location; let plain = font.shape("12", &Location::default(), &ShapeOptions::DEFAULT); assert_eq!(plain.shaper, Shaper::Default); // The same digits as part of Arabic text: Arabic's model, and left to right as digits read there too. let options = ShapeOptions::DEFAULT .with_seed_script(Script::ARABIC) .with_direction(Direction::LeftToRight); let run = font.shape("12", &Location::default(), &options); assert_eq!(run.shaper, Shaper::Arabic); assert_eq!(run.clusters, [0, 1]);shape::ShapeOptions::with_suppress_dotted_circlepub const fn with_suppress_dotted_circle(mut self, suppress: bool) -> SelfThese options with the dotted circle left out, or not.
daegun adds a dotted circle, U+25CC, where a mark is left with nothing to sit on, so the reader sees that something is missing. A vowel sign or mark with no base gets one under the models that shape by syllable,
Shaper::Indic,Shaper::Khmer,Shaper::MyanmarandShaper::Universal. So do a Hangul tone mark with no syllable and a mark that opens the text underShapeOptions::beginning_of_text. Each of those needs the font to have the dotted circle glyph. Under the Indic and Universal models, a vowel written as a sequence Unicode forbids, such as अ then ा for आ, also gets one before its last character, even where the font lacks the glyph, which then draws asShapeOptions::not_found_glyph. Devanagari left to the general model, as it is in a Latin font, gets no circle for a vowel sign with no base or for a forbidden sequence. Set this to leave all of them out.use daegun::shape::ShapeOptions; use daegun::Location; // A vowel sign with no letter before it. let plain = font.shape("ि", &Location::default(), &ShapeOptions::DEFAULT); // The sign and a dotted circle to carry it. assert_eq!(plain.glyphs.len(), 2); let options = ShapeOptions::DEFAULT.with_suppress_dotted_circle(true); let run = font.shape("ि", &Location::default(), &options); assert_eq!(run.glyphs.len(), 1);shape::Shaper::namepub fn name(self) -> &'static strThe model's name in snake case, such as
"arabic"or"myanmar_zawgyi".One of
default,dumber,arabic,hangul,hebrew,indic,khmer,myanmar,myanmar_zawgyi,thaianduniversal. For a log or a test report.use daegun::shape::ShapeOptions; use daegun::Location; let run = font.shape("कि", &Location::default(), &ShapeOptions::DEFAULT); assert_eq!(run.shaper.name(), "indic");
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.
daegun::unicode::general_categorypub fn general_category(c: char) -> GeneralCategoryA character's Unicode general category, such as uppercase letter, decimal digit or nonspacing mark.
A lookup in daegun's Unicode tables, which needs no font. Every
charhas a category, and one Unicode has not assigned answersGeneralCategory::Unassigned.Use it to tell letters from marks, digits, punctuation and spaces when you process text yourself.
GeneralCategorysays what each value covers.use daegun::unicode::{general_category, GeneralCategory}; assert_eq!(general_category('A'), GeneralCategory::UppercaseLetter); assert_eq!(general_category('7'), GeneralCategory::DecimalNumber); assert_eq!(general_category(' '), GeneralCategory::SpaceSeparator); // U+0301 is the combining acute accent. assert_eq!(general_category('\u{301}'), GeneralCategory::NonspacingMark); // Drop the combining accents from a string. let bare: String = "e\u{301}te\u{301}" .chars() .filter(|&c| general_category(c) != GeneralCategory::NonspacingMark) .collect(); assert_eq!(bare, "ete");daegun::unicode::grapheme_boundariespub fn grapheme_boundaries(text: &str) -> alloc::vec::Vec<usize>Where each grapheme of a string starts, as byte offsets, with the end of the string as the last entry.
A grapheme, or grapheme cluster, is what a reader takes for one character: a letter with its combining accents, a Hangul syllable written as several jamo, an emoji joined from several by zero width joiners, a flag made of two regional indicators, a carriage return with its newline. It can be many
chars long. It is the unit a text cursor moves by, and by default the unit of a shaped run's clusters (ClusterLevel::MonotoneGraphemes). The rules are those of UAX #29.The list holds the start of every grapheme and then
text.len(). So it begins with 0, ends with the length of the string, and each neighboring paira,bis one grapheme,&text[a..b]. The number of graphemes is the length of the list less one. An empty string gives[0]: its start and its end are the same place, and it has no grapheme.Each offset is a UTF-8 byte offset where a character starts, as every position in daegun is, so it slices the string directly.
use daegun::unicode::grapheme_boundaries; // An e with a combining acute accent, then the flag of South Korea. let text = "e\u{301}🇰🇷"; let bounds = grapheme_boundaries(text); // Two graphemes, in a string of 4 chars and 11 bytes. assert_eq!(bounds, [0, 3, 11]); // Each neighboring pair of offsets is one grapheme. let graphemes: Vec<&str> = bounds.windows(2).map(|pair| &text[pair[0]..pair[1]]).collect(); assert_eq!(graphemes, ["e\u{301}", "🇰🇷"]); // An empty string has a start and no grapheme. assert_eq!(grapheme_boundaries(""), [0]);daegun::unicode::line_break_opportunitiespub fn line_break_opportunities(text: &str, segmenter: Option<WordSegmenter>) -> alloc::vec::Vec<LineBreak>Every place a line of the text may end, in order, each marked as allowed or mandatory.
These are the break opportunities of the Unicode line breaking algorithm, UAX #14. A line breaker measures the text between them and ends each line at the last one that fits. Each
LineBreakhasat, the byte offset where the next line would start, so the line before it is the text up toat. It is a UTF-8 byte offset where a character starts, so it slices the text directly. Spaces stay at the end of the line before the break: inone twothe break is at 4, after the space.A break is allowed or mandatory, and
LineBreak::mandatorytells them apart. An allowed break is a place the line may end if it has to: after a space, after a hyphen, between two ideographs. A mandatory break is a place the line must end however much room is left: after a newline, a carriage return, a vertical tab, a form feed, U+0085, U+2028 or U+2029. A carriage return with a newline right after it is one break, after the pair.The list never holds 0, and it always ends with a mandatory break at
text.len(), the end of the text, whether or not the text ends with a newline. So a single word gives that one entry. An empty string gives an empty list.Thai, Lao, Khmer and Myanmar are written without spaces between words, and a line may break only between words, so finding the breaks takes knowing the words. With daegun's
dictionariescrate feature, its word lists for those four scripts find them whensegmenterisNone. AWordSegmenteryou pass finds them in place of the lists, with or without the feature. With neither, such text gets no break between its words, only the ones its spaces and other characters allow.Font::layoutcalls this itself. Use it when you break lines on your own.use daegun::unicode::line_break_opportunities; let text = "one two\nthree"; let breaks = line_break_opportunities(text, None); let found: Vec<(usize, bool)> = breaks.iter().map(|b| (b.at, b.mandatory)).collect(); // Allowed after "one ", mandatory after the newline, and mandatory at the end. assert_eq!(found, [(4, false), (8, true), (13, true)]); // The pieces between the breaks are what a line breaker measures and fits. let mut start = 0; let mut pieces = Vec::new(); for b in &breaks { pieces.push(&text[start..b.at]); start = b.at; } assert_eq!(pieces, ["one ", "two\n", "three"]);daegun::unicode::scriptpub fn script(c: char) -> ScriptThe script a character belongs to, its Unicode Script property.
A lookup in daegun's Unicode tables, which needs no font. A letter answers with its script, such as
Script::LATINorScript::ARABIC. A character many scripts share, such as a digit, a space or a comma, answersScript::COMMON, and a combining mark that takes the script of its base answersScript::INHERITED. An unassigned or private use character answers the unknown script, which has no constant and is namedUnknown.This is the property of one character alone. For the script of a stretch of text, where shared characters go with their neighbors, use
script_runs.use daegun::unicode::{script, Script}; assert_eq!(script('ب'), Script::ARABIC); assert_eq!(script('字'), Script::HAN); // Digits, spaces and commas are shared by many scripts. assert_eq!(script('1'), Script::COMMON); assert_eq!(script(' '), Script::COMMON); assert_eq!(script(','), Script::COMMON); // U+0301, the combining acute accent, takes the script of its base. assert_eq!(script('\u{301}'), Script::INHERITED);daegun::unicode::script_runspub fn script_runs(text: &str) -> alloc::vec::Vec<ScriptRun>Cuts text into runs of one script each, in order, covering every byte.
Text is shaped one script at a time, so it is cut where its script changes before it is shaped. This is that cut, by the rules of UAX #24. Each
ScriptRunhas the byte range it covers, which slices the text, and itsScript.Most characters with no script of their own don't start a run. A space, a digit or a punctuation mark stays with the run it follows, and one at the very start of the text joins the run after it. A combining mark stays with its base. A closing bracket takes the script of its opening bracket, so a pair around text of another script still belongs to the text outside it. Brackets pair up to 32 deep: a closing bracket whose opener has 32 newer brackets still open after it stays with the run it follows.
Some shared characters are used by a few scripts only, and continue a run of those scripts alone. The Japanese long vowel mark
ーcontinues a run of Katakana or Hiragana, and after a Latin letter it starts a run of its own, as the ideographic comma、does.An empty string gives no runs. Text of characters that claim no script, such as
123, is one run ofScript::COMMON. Text of shared characters that a few scripts claim takes one of those:、alone is a run ofScript::HAN.Font::shape_bidiandFont::layoutmake this cut themselves. Call it when you itemize text on your own, to choose a font for each script for instance.use daegun::unicode::{script_runs, Script}; let text = "Tokyo 東京 (とうきょう)"; let runs: Vec<(&str, Script)> = script_runs(text).iter().map(|run| (&text[run.bytes], run.script)).collect(); // Spaces stay with the run before them, and the closing bracket goes with its opening one. assert_eq!( runs, [ ("Tokyo ", Script::LATIN), ("東京 (", Script::HAN), ("とうきょう", Script::HIRAGANA), (")", Script::HAN), ] );daegun::unicode::vertical_formpub const fn vertical_form(c: char) -> Option<char>The character Unicode encodes as the vertical form of another, such as
︒for。, orNonewhere there is none.Punctuation is drawn differently in vertical text: a bracket opens downward, a comma moves to another corner of its box. Unicode has separate characters for some of these shapes, in its Vertical Forms and CJK Compatibility Forms blocks, and this maps a character to that one.
It knows 33 pairs: the ideographic comma and full stop, seven pairs of CJK brackets such as
「and」, the fullwidth!,?,,,:,;and_with the fullwidth parentheses, square brackets and braces, the wavy low line﹏, and the en dash, the em dash, the ellipsis and the two dot leader. Every other character givesNone.A font made for vertical text swaps these shapes itself, through its
vertfeature. Shaping a vertical run with a font that has novertfeature uses this mapping instead, wherever the font has a glyph for the vertical form. It is aconst fn, so it can fill a constant.use daegun::unicode::vertical_form; assert_eq!(vertical_form('。'), Some('︒')); assert_eq!(vertical_form('('), Some('︵')); // Most characters have no separate vertical form. assert_eq!(vertical_form('a'), None); assert_eq!(vertical_form('日'), None); // A line of text with each character in its vertical form, where it has one. let vertical: String = "「はい。」".chars().map(|c| vertical_form(c).unwrap_or(c)).collect(); assert_eq!(vertical, "﹁はい︒﹂");daegun::unicode::vertical_orientationpub fn vertical_orientation(c: char) -> VerticalOrientationHow a character stands in vertical text: upright, or turned on its side.
A lookup in daegun's Unicode tables, with an answer for every
char. It returns theVerticalOrientationthat UAX #50 gives the character.A vertical layout uses it to decide which characters to turn.
Font::layoutdoes that for you in a verticalWritingMode. Call this when you set vertical text yourself.use daegun::unicode::{vertical_orientation, VerticalOrientation}; assert_eq!(vertical_orientation('日'), VerticalOrientation::Upright); assert_eq!(vertical_orientation('a'), VerticalOrientation::Rotated); // The ideographic full stop stands upright, in a form made for vertical text. assert_eq!(vertical_orientation('。'), VerticalOrientation::TransformedUpright);daegun::unicode::word_boundariespub fn word_boundaries(text: &str) -> alloc::vec::Vec<usize>Where the words of a string begin and end, as byte offsets, with the start and the end of the string included.
The boundaries are those of UAX #29, the ones a double click or a word-by-word cursor goes by. The list begins with 0 and ends with
text.len(), and each neighboring paira,bis one piece of the text,&text[a..b]. Every offset is a UTF-8 byte offset where a character starts. An empty string gives[0].Not every piece is a word. A run of spaces is a piece of its own and so is each punctuation mark, so
Hello, worldis cut intoHello, the comma, the space andworld. To keep the words, keep the pieces that hold a letter or a digit.An apostrophe inside a word and a separator inside a number don't cut them:
can'tis one piece, and so is1,000.50.The rules use no word list, so text written without spaces is not cut into its words. Each Han ideograph, each Hiragana letter and each Thai letter with its marks comes out as a piece of its own, while a run of Katakana or of Hangul stays whole.
use daegun::unicode::word_boundaries; let text = "Hello, world"; let bounds = word_boundaries(text); assert_eq!(bounds, [0, 5, 6, 7, 12]); // Each neighboring pair of offsets is one piece. Keep the ones that are words. let words: Vec<&str> = bounds .windows(2) .map(|pair| &text[pair[0]..pair[1]]) .filter(|piece| piece.chars().any(char::is_alphanumeric)) .collect(); assert_eq!(words, ["Hello", "world"]); // An apostrophe inside a word does not cut it. assert_eq!(word_boundaries("can't stop"), [0, 5, 6, 10]);unicode::BidiParagraph::newpub fn new(text: &str, base: BaseDirection) -> BidiParagraphResolves text for bidi: finds its paragraphs and gives every byte its level.
basesets the direction of every paragraph. WithBaseDirection::Autoeach paragraph takes the direction of its own first strong character, so a Hebrew paragraph after an English one is right to left while the English one stays left to right.There is no failure: any string resolves, and an empty one gives empty lists. The call reads the whole text and allocates the lists it returns, one level per byte and one visual position per character.
Resolve a text once, then call
BidiParagraph::visual_runsfor each of its lines. Breaking a paragraph into lines does not change its levels, so there is nothing to resolve again.use daegun::unicode::{BaseDirection, BidiParagraph}; // Two paragraphs: an English one, then a Hebrew one. let text = "abc\nשלום"; let para = BidiParagraph::new(text, BaseDirection::Auto); assert_eq!(para.paragraphs.len(), 2); // Each took its direction from its own first letter. assert_eq!(para.paragraphs[0].level, 0); assert_eq!(para.paragraphs[1].level, 1); // Set right to left, the English paragraph is at level 1 too, and its letters are at level 2. let forced = BidiParagraph::new(text, BaseDirection::RightToLeft); assert_eq!(forced.paragraphs[0].level, 1); assert_eq!(forced.levels[..3], [2, 2, 2]);unicode::BidiParagraph::visual_runspub fn visual_runs(&self, text: &str, line: impl core::ops::RangeBounds<usize>) -> alloc::vec::Vec<VisualRun>The runs of one line in the order they are drawn, from the left, each with its bytes and its level.
textis the stringBidiParagraph::newresolved, andlineis the byte range of the line within it:..for the whole text, orstart..endfrom your line breaker. Both ends must fall on character boundaries: where a character starts, or the end of the text.Each
VisualRunis a stretch of one level. Set the runs one after another from the left. Inside a run with an odd level the characters go right to left, so shape each run in the direction its level gives.The paragraph that holds the start of the line supplies the base level, and spaces at the end of the line take that level whatever they followed. That keeps a trailing space at the far end of the line instead of between two runs. A line lies within one paragraph, so ask for one line at a time.
The result is empty when the range is empty or reversed, when an end is not where a character starts, or when it reaches past the text.
use daegun::unicode::{BaseDirection, BidiParagraph}; // An Arabic word and a number: a right-to-left paragraph. let text = "مرحبا 123"; let para = BidiParagraph::new(text, BaseDirection::Auto); let runs = para.visual_runs(text, ..); let drawn: Vec<(&str, u8)> = runs.iter().map(|run| (&text[run.bytes], run.level)).collect(); // The number is the first run from the left, and reads left to right at level 2. assert_eq!(drawn, [("123", 2), ("مرحبا ", 1)]); // A line that holds the Arabic word alone, bytes 0 to 10. let line = para.visual_runs(text, 0..10); assert_eq!(line.len(), 1); assert_eq!((&text[line[0].bytes], line[0].level), ("مرحبا", 1)); // A range that does not start where a character starts gives no runs. assert!(para.visual_runs(text, 1..10).is_empty());unicode::Script::directionpub fn direction(self) -> ScriptDirectionWhich way the script is written across a line: left to right or right to left.
Right to left for the scripts whose letters Unicode classes as right to left, such as Arabic, Hebrew, Syriac, Thaana, Nko and Adlam. Every other script answers left to right. So do
Script::COMMON,Script::INHERITEDand the unknown script, which have no direction of their own, and a script that was once written either way, such as Old Italic.It is the direction shaping gives a run of that script when
ShapeOptions::directionis unset.use daegun::unicode::{Script, ScriptDirection}; assert_eq!(Script::HEBREW.direction(), ScriptDirection::RightToLeft); assert_eq!(Script::LATIN.direction(), ScriptDirection::LeftToRight); // Common has no direction of its own, and answers left to right. assert_eq!(Script::COMMON.direction(), ScriptDirection::LeftToRight);unicode::Script::from_iso15924pub fn from_iso15924(code: &str) -> Option<Script>The script an ISO 15924 code names, or
Noneif daegun has no script by that code.The code is four letters in any letter case, so
Arab,arabandARABall giveScript::ARABIC. Anything that is not exactly four bytes long isNone. So is a code of the standard that names no single Unicode script, such asJpanfor Japanese writing orZzzzfor an unknown script.A script name is not a code. To read either, parse the string instead, as in
"Arabic".parse::<Script>().use daegun::unicode::Script; assert_eq!(Script::from_iso15924("Hebr"), Some(Script::HEBREW)); assert_eq!(Script::from_iso15924("hebr"), Some(Script::HEBREW)); // A name is not a code, and "Jpan" names a mix of scripts. assert_eq!(Script::from_iso15924("Hebrew"), None); assert_eq!(Script::from_iso15924("Jpan"), None);unicode::Script::is_context_dependentpub fn is_context_dependent(self) -> boolWhether the script takes its identity from the text around it, as Common, Inherited and the unknown script do.
True for
Script::COMMON(digits, spaces, punctuation), forScript::INHERITED(combining marks) and for the unknown script of unassigned and private use characters. False for every other script.A character of such a script does not decide the script of the text it is in.
script_runsfolds it into a neighboring run, and shaping passes over it to find the first character with a script of its own. Use it the same way when you group text by script yourself.use daegun::unicode::{script, Script}; assert!(Script::COMMON.is_context_dependent()); assert!(Script::INHERITED.is_context_dependent()); assert!(!Script::LATIN.is_context_dependent()); // The script of a text: that of its first character with a script of its own. let text = "(42) שלום"; let found = text.chars().map(script).find(|s| !s.is_context_dependent()); assert_eq!(found, Some(Script::HEBREW));unicode::Script::iso15924pub fn iso15924(self) -> Option<&'static str>The script's four-letter ISO 15924 code, such as
"Arab".The code is written the way the standard writes it, a capital and three small letters. It is the form to store a script in or to hand to other software, and
Script::from_iso15924reads it back.Every constant has a code:
Script::COMMONisZyyyandScript::INHERITEDisZinh.Nonecomes only from the unknown script, the onescriptgives an unassigned or private use character.use daegun::unicode::{script, Script}; assert_eq!(Script::ARABIC.iso15924(), Some("Arab")); assert_eq!(Script::COMMON.iso15924(), Some("Zyyy")); // A private use character has no script, so there is no code to give. assert_eq!(script('\u{E000}').iso15924(), None);unicode::Script::namepub fn name(self) -> &'static strThe script's Unicode name, such as
"Arabic"or"Old_Italic".It is the name the Unicode Character Database gives the script, with an underscore between its words:
Old_Italic,Canadian_Aboriginal.Displaywrites the same text, and parsing reads it back.The unknown script, the one
scriptgives an unassigned or private use character, is namedUnknown. That name does not parse.use daegun::unicode::{script, Script}; assert_eq!(Script::ARABIC.name(), "Arabic"); // Words are joined by an underscore. assert_eq!(Script::OLD_ITALIC.name(), "Old_Italic"); // A private use character has no script. assert_eq!(script('\u{E000}').name(), "Unknown");unicode::Script::opentype_tagspub fn opentype_tags( self, ) -> impl ExactSizeIterator<Item = Tag> + DoubleEndedIterator + core::iter::FusedIterator + CloneThe OpenType script tags a font may keep this script's rules under, newest first.
A font's
GSUBandGPOStables group their rules by script tag. For most scripts there is one tag, the ISO 15924 code in lowercase:latn,arab. Hiragana and Katakana sharekana, and Lao, Nko, Vai and Yi have tags padded with spaces, such aslaowith one space at its end.Ten scripts have more than one tag. OpenType gave Bengali, Devanagari, Gujarati, Gurmukhi, Kannada, Malayalam, Oriya, Tamil, Telugu and Myanmar a second tag for their second shaping specification, such as
dev2besidedevaandmym2besidemymr. All of them but Myanmar have a third as well, such asdev3, which a font uses to ask for the Universal Shaping Engine. The newest comes first, and shaping tries them in that order.Script::COMMON,Script::INHERITEDand the unknown script give one tag,DFLT, the default script. The iterator knows its length, which is 1, 2 or 3, and can be read from either end.use daegun::unicode::Script; use daegun::Tag; let tags: Vec<Tag> = Script::DEVANAGARI.opentype_tags().collect(); assert_eq!(tags, [Tag::new(b"dev3"), Tag::new(b"dev2"), Tag::new(b"deva")]); // Most scripts have one tag, their ISO 15924 code in lowercase. let mut latin = Script::LATIN.opentype_tags(); assert_eq!(latin.len(), 1); assert_eq!(latin.next(), Some(Tag::new(b"latn")));
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.
Font::justification_glyphspub fn justification_glyphs(&self, script: Tag) -> Option<Vec<GlyphId>>The glyphs a font's
JSTFtable lists as extenders for a script: glyphs a justifier may add to widen a line, such as the Arabic tatweel.An extender is a glyph that makes a line longer without changing what it says. The tatweel (U+0640), the stroke that stretches Arabic words, is the usual one. This call only reads the list. Justification in daegun never inserts extenders:
Font::justifyapplies lookups, andAlign::Justifyresizes spaces. A justifier of yours that adds tatweels can ask shaping where one may go, withShapeOptions::with_report_tatweel_positions.scriptis an OpenType script tag, such asarab. The answer isNonewhen the font has noJSTFtable, when the table does not list the script, when the script has no list of extenders, or when the list runs past the end of the table. AJSTFtable of a major version other than 1 is not read, and answersNonetoo.The glyph IDs come back as the table stores them: they are not checked against
Font::glyph_count, and the list can be empty.use daegun::Tag; match font.justification_glyphs(Tag::new(b"arab")) { Some(extenders) => { // Scheherazade New lists two. The first is the tatweel, U+0640. assert_eq!(extenders.len(), 2); assert_eq!(Some(extenders[0]), font.glyph_id('\u{0640}')); } None => { /* The font names none for Arabic: widen spaces instead. */ } } // A script the table does not list has none. assert!(font.justification_glyphs(Tag::new(b"latn")).is_none());Font::justification_prioritiespub fn justification_priorities(&self, script: Tag, language_system: Option<Tag>) -> Option<Vec<JstfModLists>>A script's justification priority levels from the font's
JSTFtable: for each level, the lookups to turn on and off to shrink or extend a line.Levels come in the font's order, highest priority first: a justifier tries level 0 and moves to the next only if the line is still not the width it wants. Each level is a
JstfModLists, which you hand toFont::shape_justified.Font::justifyruns that loop for you.scriptis an OpenType script tag, such asarab, andlanguage_systeman OpenType language system tag, such asURD. WithNone, or with a language system the script's table does not list, you get the script's default levels.The answer is
Nonewhen the font has noJSTFtable, when the table does not list the script, when the script lists neither that language system nor default levels, or when the table is damaged. AJSTFtable of a major version other than 1 is not read, and answersNonetoo. A script can list extender glyphs and still have no levels: Scheherazade New does for Arabic.Somecan hold an empty list, where the font's table for the language system has no levels in it, so check before you indexlevels[0].use daegun::layout::Adjustment; use daegun::{Location, Orientation, Tag}; let text = "Aa الماس"; let (at, target) = (Location::default(), 8_000.0); if let Some(levels) = font.justification_priorities(Tag::new(b"arab"), None) { // Try each level in turn, highest priority first, and stop at one that is wide enough. for level in &levels { let run = font.shape_justified(text, &at, Orientation::Horizontal, level, Adjustment::Extend); if run.width() >= target { // Here the first level is: it takes the line from 7649 units to 8127. break; } } // daegun's JSTF test font has two levels for Arabic. assert_eq!(levels.len(), 2); } // A script the table does not list has none. assert!(font.justification_priorities(Tag::new(b"latn"), None).is_none());Font::justifypub fn justify( &self, text: &str, location: &Location, orientation: Orientation, options: &JustifyOptions, ) -> JustifiedShapes one line toward a target width with the font's own justification data, its
JSTFtable, and reports how near it came.A font may carry a
JSTFtable: for a script, a list of priority levels, each naming lookups to turn on or off to make a line narrower or wider. This call tries them for you. It first shapes the text as one run, asFont::shapedoes with default options. If that natural width is withinJustifyOptions::toleranceofJustifyOptions::target_width, it returns the run as it is.Otherwise it shapes the line again at each level in turn, highest priority first, with the level's shrinkage lookups if the line is too wide or its extension lookups if it is too narrow. The first level that lands within the tolerance is the answer. If none does, you get whichever came nearest, the natural run included, with
Justified::best_effortset.That is all it does. It does not stretch spaces and it does not insert extender glyphs such as the tatweel, so with a font that has no levels for the script the line comes back at its natural width and the rest of the gap is yours to close. To justify a wrapped paragraph by its spaces, use
Font::layoutwithAlign::Justify, which does not readJSTF.Widths and the tolerance are in font units.
Orientation::Verticalshapes the line top to bottom. The text is one line in one direction: nothing here breaks lines or reorders mixed directions.The natural run comes through the font's shape cache, the same
ArcthatFont::shapehands out. Each level tried is shaped afresh on every call and not kept, so keep theJustifiedrather than asking again for the same line.use daegun::layout::{Adjustment, JustifyOptions}; use daegun::shape::ShapeOptions; use daegun::{Location, Orientation, Tag}; let text = "Aa الماس"; let natural = font.shape(text, &Location::default(), &ShapeOptions::DEFAULT).width(); // Ask for a line 400 units wider, give or take 100. let options = JustifyOptions::new(Tag::new(b"arab"), natural + 400.0).with_tolerance(100.0); let line = font.justify(text, &Location::default(), Orientation::Horizontal, &options); // Draw line.run. In daegun's JSTF test font the first level's extension lookups take the // line from 7649 units to 8127, which is near enough to count. assert_eq!(line.adjustment, Adjustment::Extend); assert_eq!((line.level, line.width, line.best_effort), (Some(0), 8127.0, false)); // Past what the levels can reach, the nearest result comes back flagged, and the rest of // the gap is yours to close, by widening spaces or adding tatweels. let far = JustifyOptions::new(Tag::new(b"arab"), 9_000.0); let line = font.justify(text, &Location::default(), Orientation::Horizontal, &far); if line.best_effort { let gap = far.target_width - line.width; }Font::layoutpub fn layout(&self, text: &str, location: &Location, options: &LayoutOptions) -> TextLayoutLays text out as a block: breaks it into lines that fit a width, shapes each line and places every run on it.
It sets a block of text in one call. The text is split at its hard breaks, a newline and the like, run through the Unicode bidirectional algorithm, and cut into runs of one script and one direction. Each stretch between hard breaks is wrapped at the line break opportunities Unicode gives it, each line is shaped as it will be drawn, and the lines are aligned. What comes back is a
TextLayout: the lines, each line's runs, and where everything sits.Units. Layout works in font units, like the rest of daegun. With
scale = px / f64::from(font.units_per_em()), a width in pixels goes in divided byscale, and every position that comes out is multiplied by it. In horizontal text a line'sbaselinecounts down from the top of the block, while the offsets of glyphs are y up, as in anyShapedRun. In a verticalWritingModethe baseline is an x from the left edge of the block, and a run's offset counts down its column:PositionedRunsays how the two combine, andWritingModeshows how to draw one.With
LayoutOptions::default()nothing wraps: lines end only at hard breaks, however long they get. To wrap, setLayoutOptions::max_inline_size, the measure, which is the length lines wrap at.locationpicks the instance of a variable font, and&Location::default()works for any font.A word too wide for the measure is cut between two of its graphemes, so a line overflows only where something that cannot be cut, a single grapheme or a cluster of glyphs the font fused, is wider than the measure. A line that breaks at a soft hyphen (U+00AD) shows a hyphen there, counted in the line's size: the font's U+2010 or, without one, its hyphen-minus. A font with neither shows nothing.
Spaces and tabs at the end of a line hang: they are not in its runs, not counted in its size and not counted against the measure, on the last line too. A space here is any character Unicode classes as a space separator, so a no-break space (U+00A0), an em space or an ideographic space (U+3000) at the end of a line hangs as well.
Thai, Lao, Khmer and Myanmar are written without spaces between words. Such text breaks between words only where a
WordSegmenteryou pass inLayoutOptions::segmenterfinds them, or where the word lists of thedictionariescrate feature do. With neither, it breaks at its spaces and, where a stretch won't fit a line, between graphemes.There is no failure to handle, and empty text gives a layout with no lines. A hard break at the very end of the text ends its line and starts no empty line after it:
"a\n"is one line and"a\n\n"is two, the second one blank. A blank line has no runs and a size of 0, and still takes its place in the block.The result borrows nothing: it holds byte ranges, not text, so keep the string to slice it. Text is shaped through the font's shape cache, so laying the same text out again, at another width too, reuses what the cache still holds.
For one line of mixed-direction text that never wraps,
Font::shape_bidiis the lighter call.use daegun::layout::LayoutOptions; use daegun::Location; let text = "Type is the voice of the page, and a paragraph is where it speaks."; // 16 px text in a column 240 px wide. Layout works in font units, so the width goes in // divided by the scale, and positions come out multiplied by it. 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); for line in &layout.lines { for run in &line.runs { let mut pen = run.offset.x; for i in 0..run.run.glyphs.len() { let x = (pen + run.run.offsets[i].x) * scale; let y = (line.baseline - run.run.offsets[i].y) * scale; // Draw run.run.glyphs[i] at (x, y) pixels, from the top left corner of the column. pen += run.run.advances[i]; } } } // With Inter this makes three lines, and the block is about 58 px tall.Font::shape_justifiedpub fn shape_justified( &self, text: &str, location: &Location, orientation: Orientation, level: &JstfModLists, adjustment: Adjustment, ) -> Arc<ShapedRun>Shapes text with one JSTF priority level's lookups switched on and off, to make the line narrower or wider.
The building block under
Font::justify, for a justifier of your own that tries levels itself. It shapes the text asFont::shapedoes with default options, with one change: the lookups the level lists for the chosenAdjustmentare forced.Adjustment::Shrinkreads the level's four shrinkage lists andAdjustment::Extendits four extension lists.A lookup in a disable list is left out of shaping. A lookup in an enable list that shaping would not have run is added after the others and applied to every glyph. A lookup named in both lists counts as enabled: it runs where shaping would have run it, and is added where it would not. An index past the end of the font's lookup list is ignored.
Get levels from
Font::justification_priorities. The run is shaped afresh on every call and does not go through the shape cache. Advances are in font units, andOrientation::Verticalshapes top to bottom.use daegun::layout::{Adjustment, JstfModLists}; use daegun::{Location, Orientation}; // A level as a font's JSTF table would give it: to extend a line, turn GPOS lookup 1 off. // In Inter that lookup kerns these letters. let mut level = JstfModLists::default(); level.extension_disable_gpos = Some(vec![1]); let at = Location::default(); let wider = font.shape_justified("Wave", &at, Orientation::Horizontal, &level, Adjustment::Extend); // "Wave" is 5513 units wide without its kerning, where plain shaping gives 5339. assert_eq!(wider.width(), 5513.0); // The level lists nothing for shrinking, so that way the line is shaped as usual. let same = font.shape_justified("Wave", &at, Orientation::Horizontal, &level, Adjustment::Shrink); assert_eq!(same.width(), 5339.0);layout::JustifyOptions::newpub const fn new(script: Tag, target_width: f64) -> JustifyOptionsOptions to justify a line to a width, in font units, with a script's JSTF levels.
The tolerance starts at 0, so only the exact width counts as reached, and the levels are the script's default ones. Change those with
JustifyOptions::with_toleranceandJustifyOptions::with_language_system. It is aconst fn, so options can be constants.use daegun::layout::JustifyOptions; use daegun::Tag; let options = JustifyOptions::new(Tag::new(b"arab"), 12_000.0); assert_eq!(options.script, Tag::new(b"arab")); assert_eq!(options.target_width, 12_000.0); // Exact, and with the script's default levels, until you say otherwise. assert_eq!(options.tolerance, 0.0); assert_eq!(options.language_system, None);layout::JustifyOptions::with_language_systempub const fn with_language_system(mut self, language_system: Tag) -> JustifyOptionsThese options with the OpenType language system whose JSTF levels to use.
A font may give a script different levels for different languages. The tag is an OpenType language system tag such as
URD, four characters with a trailing space, not a BCP 47 tag. If the script does not list it, the script's default levels are used.use daegun::layout::JustifyOptions; use daegun::{Location, Orientation, Tag}; let urdu = Tag::new(b"URD "); let options = JustifyOptions::new(Tag::new(b"arab"), 8_127.0).with_language_system(urdu); assert_eq!(options.language_system, Some(urdu)); let line = font.justify("Aa الماس", &Location::default(), Orientation::Horizontal, &options); // daegun's JSTF test font does not list Urdu, so the script's default levels are the // ones tried, and the first of them reaches the width. assert_eq!((line.level, line.width), (Some(0), 8127.0)); let arab = Tag::new(b"arab"); assert_eq!(font.justification_priorities(arab, Some(urdu)), font.justification_priorities(arab, None));layout::JustifyOptions::with_tolerancepub const fn with_tolerance(mut self, tolerance: f64) -> JustifyOptionsThese options with how near the target width counts as reaching it, in font units.
A line whose width is within the tolerance of the target, on either side, is taken as it is:
Font::justifystops at the natural shaping, or at the first level that gets there. The default of 0 accepts only the exact width. Set it to the difference you can make up elsewhere, such as in the spaces.A tolerance below 0, or NaN, accepts nothing: even a line already at the exact width comes back with
Justified::best_effortset.use daegun::layout::JustifyOptions; use daegun::{Location, Orientation, Tag}; let (text, at) = ("Aa الماس", Location::default()); // daegun's JSTF test font sets this line 7649 units wide, or 8127 at its first level. // Asked for exactly 8000, it can only come near. let exact = JustifyOptions::new(Tag::new(b"arab"), 8_000.0); let line = font.justify(text, &at, Orientation::Horizontal, &exact); assert_eq!((line.width, line.best_effort), (8127.0, true)); // Give or take 200, the same 8127 counts as reaching the target. let near = exact.with_tolerance(200.0); let line = font.justify(text, &at, Orientation::Horizontal, &near); assert_eq!((line.width, line.best_effort), (8127.0, false));layout::LayoutOptions::with_alignpub const fn with_align(mut self, align: Align) -> SelfThese options with where lines sit in the measure.
See
Alignfor the four choices. The default isAlign::Start. With no measure set, lines align against the longest line of the layout. The shift goes into each run'sPositionedRun::offset.use daegun::layout::{Align, LayoutOptions}; use daegun::Location; let options = LayoutOptions::default().with_max_inline_size(20_000.0).with_align(Align::End); let layout = font.layout("Total", &Location::default(), &options); let line = &layout.lines[0]; // The line ends at the right edge of the measure, so its run starts this far in. assert_eq!(line.runs[0].offset.x, 20_000.0 - line.inline_size);layout::LayoutOptions::with_base_directionpub const fn with_base_direction(mut self, direction: BaseDirection) -> SelfThese options with the direction of the paragraphs.
BaseDirection::Auto, the default, takes each paragraph's direction from its first strongly directional character, and left to right where it has none. SetBaseDirection::LeftToRightorBaseDirection::RightToLeftwhen you know the direction from elsewhere, such as the language of the page. The base direction orders the runs of a mixed line and decides which edgeAlign::Startmeans.A newline, a carriage return, a next line (U+0085) or a paragraph separator (U+2029) starts a new paragraph, with a direction of its own under
Auto. A line separator (U+2028), a vertical tab or a form feed breaks the line and stays in the paragraph. The information separators U+001C to U+001E start a new paragraph too, without breaking the line. Vertical text set withTextOrientation::Uprightdoes not read the base direction.use daegun::layout::LayoutOptions; use daegun::unicode::BaseDirection; use daegun::Location; let text = "Read مرحبا aloud"; // The text opens with a Latin letter, so by default the paragraph reads left to right. let auto = font.layout(text, &Location::default(), &LayoutOptions::default()); assert_eq!(&text[auto.lines[0].runs[0].bytes], "Read "); // As part of a right-to-left page, the same words are set from the right. let options = LayoutOptions::default().with_base_direction(BaseDirection::RightToLeft); let rtl = font.layout(text, &Location::default(), &options); // Now "aloud" is the leftmost run and "Read" the rightmost. assert_eq!(&text[rtl.lines[0].runs[0].bytes], "aloud"); assert_eq!(&text[rtl.lines[0].runs[3].bytes], "Read");layout::LayoutOptions::with_featurespub const fn with_features(mut self, features: &'a [Feature]) -> SelfThese options with OpenType features to turn on, off or set.
The slice replaces any features set before. Each
Featurecovers all of the text or a byte range of it, and the range counts bytes of the whole text you lay out, wherever its lines break.use daegun::layout::LayoutOptions; use daegun::shape::Feature; use daegun::{Location, Tag}; // Tabular figures, so the digits of one line sit under those of the next. let features = [Feature::new(Tag::new(b"tnum"), 1)]; let options = LayoutOptions::default().with_features(&features); let layout = font.layout("111\n000", &Location::default(), &options); // Both lines are 3984 units wide. Without the feature Inter sets them 2499 and 3876 wide. assert_eq!(layout.lines[0].inline_size, 3984.0); assert_eq!(layout.lines[1].inline_size, 3984.0);layout::LayoutOptions::with_languagepub const fn with_language(mut self, language: &'a str) -> SelfThese options with the language of the text, as a BCP 47 tag.
It is handed to shaping, as
ShapeOptions::with_languageis, so the font applies the forms it keeps for that language. It does not change where lines may break.use daegun::layout::LayoutOptions; use daegun::Location; let plain = font.layout("fi", &Location::default(), &LayoutOptions::default()); // EB Garamond joins f and i into one ligature glyph. assert_eq!(plain.lines[0].runs[0].run.glyphs.len(), 1); let turkish = LayoutOptions::default().with_language("tr"); let layout = font.layout("fi", &Location::default(), &turkish); // In Turkish it keeps them apart, so the dot of the i stays. assert_eq!(layout.lines[0].runs[0].run.glyphs.len(), 2);layout::LayoutOptions::with_line_heightpub const fn with_line_height(mut self, height: f64) -> SelfThese options with the distance from one baseline to the next, in font units.
It is a length, not a multiple of the font size. For 20 px lines of 16 px text, pass
20.0 / (16.0 / f64::from(font.units_per_em())). Without it, lines are spaced by the font's own line height: ascent less descent plus line gap.Only the gaps between baselines change. The first baseline stays one ascent below the top of the block, and
TextLayout::block_sizestill ends at the last line's descent.use daegun::layout::LayoutOptions; use daegun::Location; let scale = 16.0 / f64::from(font.units_per_em()); let options = LayoutOptions::default().with_line_height(20.0 / scale); let layout = font.layout("one\ntwo\nthree", &Location::default(), &options); let baselines: Vec<f64> = layout.lines.iter().map(|line| line.baseline * scale).collect(); // At 16 px Inter's ascent is 15.5 px, and each baseline is 20 px below the last. assert_eq!(baselines, [15.5, 35.5, 55.5]);layout::LayoutOptions::with_max_inline_sizepub const fn with_max_inline_size(mut self, size: f64) -> SelfThese options wrapping lines at a measure, in font units.
The measure is the longest a line may be: the width of the column in horizontal text, its height in vertical text. From pixels, divide by
px / f64::from(font.units_per_em()). The default,f64::INFINITY, wraps only at hard breaks. A value below 0 is taken as 0, and NaN as infinite.A word that no line can hold is cut between graphemes rather than left to overflow.
use daegun::layout::LayoutOptions; use daegun::Location; let text = "Type is the voice of the page."; let unwrapped = font.layout(text, &Location::default(), &LayoutOptions::default()); assert_eq!(unwrapped.lines.len(), 1); // The same 16 px text in a column 140 px wide. let scale = 16.0 / f64::from(font.units_per_em()); let options = LayoutOptions::default().with_max_inline_size(140.0 / scale); let wrapped = font.layout(text, &Location::default(), &options); // Two lines now, neither longer than the measure. assert_eq!(wrapped.lines.len(), 2); assert!(wrapped.lines.iter().all(|line| line.inline_size <= options.max_inline_size));layout::LayoutOptions::with_max_linespub const fn with_max_lines(mut self, lines: usize) -> SelfThese options laying out at most so many lines.
Layout stops once it has that many lines, and
TextLayout::truncatedgives the byte offset where the first line left out begins, so you know there is more and where it starts. It isNonewhen everything fit. A limit of 0 lays out no lines.The lines kept break where they would with no limit. Nothing is added to the last of them, so an ellipsis is yours to draw.
use daegun::layout::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).with_max_lines(2); let layout = font.layout(text, &Location::default(), &options); assert_eq!(layout.lines.len(), 2); // The text needed a third line, and this is what it would have held. let rest = layout.truncated.map(|at| &text[at..]); assert_eq!(rest, Some("speaks."));layout::LayoutOptions::with_segmenterpub const fn with_segmenter(mut self, segmenter: WordSegmenter<'a>) -> SelfThese options breaking text that has no spaces between its words where your segmenter finds the words.
Thai, Lao, Khmer and Myanmar are written without spaces, so finding where a line may break takes knowing the words. A
WordSegmenterwraps a function of yours. It is given one stretch of such text at a time, and pushes the byte offsets of the word boundaries inside it, counted from the start of that stretch.A segmenter takes the place of the built-in word lists, which exist only with the
dictionariescrate feature. With neither, such text breaks at spaces and, where a stretch won't fit the line, between graphemes.use daegun::layout::LayoutOptions; use daegun::shape::ShapeOptions; use daegun::unicode::WordSegmenter; use daegun::Location; // Two Khmer words, "hello" and "world", 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); // A measure with room for the longer word, and not for both. let world = font.shape("ពិភពលោក", &Location::default(), &ShapeOptions::DEFAULT).width(); let options = LayoutOptions::default() .with_max_inline_size(world + 10.0) .with_segmenter(WordSegmenter(&find_words)); let layout = font.layout(text, &Location::default(), &options); // The line breaks between the two words. assert_eq!(layout.lines.len(), 2); assert_eq!(layout.lines[1].bytes.start, first);layout::LayoutOptions::with_strategypub const fn with_strategy(mut self, strategy: BreakStrategy) -> SelfThese options with how line breaks are chosen.
BreakStrategy::Greedy, the default, fills each line before starting the next.BreakStrategy::Optimalpicks all the breaks of a paragraph together so the lines come out more even, for more work.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 options = LayoutOptions::default().with_max_inline_size(160.0 / scale); let greedy = font.layout(text, &Location::default(), &options); // Greedy takes "of" onto the first line, which leaves the second one short. assert_eq!(&text[greedy.lines[0].bytes], "Type is the voice of "); assert_eq!(&text[greedy.lines[1].bytes], "the page, and a "); let optimal = options.with_strategy(BreakStrategy::Optimal); let even = font.layout(text, &Location::default(), &optimal); // Optimal moves it down, and the first two lines end up nearer in length. assert_eq!(&text[even.lines[0].bytes], "Type is the voice "); assert_eq!(&text[even.lines[1].bytes], "of the page, and a ");layout::LayoutOptions::with_tab_sizepub const fn with_tab_size(mut self, spaces: f64) -> SelfThese options with tab stops so many spaces apart.
Tab stops sit every
spacesadvances of the space character, counted from the start edge of each line, as thetab-sizeof CSS counts them. The default is 8. A tab character moves to the next stop, or to the one after if the next is closer than half the advance of the digit 0. In a font with no digit 0, a stop closer than a quarter of the em is skipped.In the run, a tab is the glyph of a space, its advance set to the distance to the stop. A size of 0 or less, or one that is not a finite number, gives tabs no width.
use daegun::layout::LayoutOptions; use daegun::shape::ShapeOptions; use daegun::Location; let space = font.shape(" ", &Location::default(), &ShapeOptions::DEFAULT).width(); let options = LayoutOptions::default().with_tab_size(4.0); let layout = font.layout("a\tb", &Location::default(), &options); let run = &layout.lines[0].runs[0].run; // The tab carries the pen from the end of the "a" to the first stop, 4 spaces in, // where the "b" starts. assert_eq!(run.advances[0] + run.advances[1], 4.0 * space);layout::LayoutOptions::with_text_orientationpub const fn with_text_orientation(mut self, orientation: TextOrientation) -> SelfThese options with how characters stand in vertical lines.
It matters only in a vertical
WritingMode.TextOrientation::Mixed, the default, stands CJK upright and lays Latin on its side. SeeTextOrientationfor the others.use daegun::layout::{LayoutOptions, TextOrientation, WritingMode}; use daegun::Location; let vertical = LayoutOptions::default().with_writing_mode(WritingMode::VerticalRl); let text = "日本語ABC"; let mixed = font.layout(text, &Location::default(), &vertical); // By default the Latin letters lie on their side, and "ABC" takes 1825 units of the line. assert_eq!(mixed.inline_size, 3000.0 + 1825.0); let upright = vertical.with_text_orientation(TextOrientation::Upright); let stacked = font.layout(text, &Location::default(), &upright); // Upright, each letter takes a full 1000 units, like the characters before it. assert_eq!(stacked.inline_size, 6000.0);layout::LayoutOptions::with_writing_modepub const fn with_writing_mode(mut self, mode: WritingMode) -> SelfThese options with the direction lines run and stack in.
The default,
WritingMode::Horizontal, runs lines across and stacks them downward.WritingMode::VerticalRlandWritingMode::VerticalLrrun lines down the page. In a vertical modeLayoutOptions::max_inline_sizeis the height of a column, the line metrics are the font's vertical ones, andLayoutOptions::text_orientationdecides which characters stand upright.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); // Two columns, the first on the right. Each baseline is an x, from the left edge of the block. let baselines: Vec<f64> = layout.lines.iter().map(|line| line.baseline).collect(); assert_eq!(baselines, [1500.0, 500.0]); // The longer column is 4 glyphs of 1000 units, and the two columns are 2000 units across. assert_eq!((layout.inline_size, layout.block_size), (4000.0, 2000.0));layout::WritingMode::is_verticalpub const fn is_vertical(self) -> boolWhether lines run down the page in this mode.
True for
WritingMode::VerticalRlandWritingMode::VerticalLr, false forWritingMode::Horizontal.use daegun::layout::WritingMode; assert!(WritingMode::VerticalRl.is_vertical()); assert!(WritingMode::VerticalLr.is_vertical()); assert!(!WritingMode::Horizontal.is_vertical());
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.
daegun::outline::max_area_forpub fn max_area_for(px: f32, units_per_em: f32) -> f32The
max_areato givePath::flattenfor a path in font units that will be drawn at a pixel size.pxis the size in pixels to the em andunits_per_emis the font's. The answer is6.0 * units_per_em / px, so a larger size gives a smaller area and finer polygons.A
pxof zero or below, or one so small that the answer would overflow, givesf32::MAX, the coarsest setting there is. That matters becausePath::flattenreads an infinite or negativemax_areaas a request for the finest. Apxof NaN comes back as NaN and one of infinity as 0, whichPath::flattenreads as the finest too.use daegun::outline::{max_area_for, Path}; 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)?; let upem = f32::from(font.units_per_em()); // Inter has 2048 units to the em, so at 32 px the area is 6 * 2048 / 32 = 384. assert_eq!(max_area_for(32.0, upem), 384.0); let points = |px: f32| -> daegun::Result<usize> { Ok(path.flatten(max_area_for(px, upem))?.iter().map(Vec::len).sum()) }; // A bigger size asks for finer polygons: 80 points for the o at 32 px, 160 at 256 px. assert_eq!((points(32.0)?, points(256.0)?), (80, 160));daegun::outline::normalize_windingpub fn normalize_winding(curves: &mut [Quad])Reverses a list of quadratic curves if it runs counterclockwise, so that it is wound clockwise, as TrueType outlines are.
It adds up the signed area of all the curves. If the total is positive, which is counterclockwise with y up, the
startandendof every curve are swapped. If not, nothing changes.Font::quadshas done this already. Call it on curves from aQuadraticPenof your own when your rasterizer tells inside from outside by direction and wants one convention for every font: CFF fonts wind their outlines the other way from TrueType fonts.Each curve is reversed where it sits, and the list keeps its order. After a reversal a curve ends where the curve before it in the list starts, so the list no longer chains front to back. The total decides for the whole list, holes included, so pass the curves of one glyph at a time.
use daegun::outline::{normalize_winding, OutlinePen, QuadraticPen}; let mut pen = QuadraticPen::new(0.5); pen.move_to(0.0, 0.0); pen.line_to(10.0, 0.0); pen.line_to(10.0, 10.0); pen.line_to(0.0, 10.0); let mut curves = pen.finish()?; // A square drawn counterclockwise: its first side runs right, from x = 0 to x = 10. assert_eq!((curves[0].start.x, curves[0].end.x), (0.0, 10.0)); normalize_winding(&mut curves); // Now clockwise. Each curve is reversed in place, so the same side runs left. assert_eq!((curves[0].start.x, curves[0].end.x), (10.0, 0.0));daegun::outline::resolve_overlapspub fn resolve_overlaps(contours: &[Vec<Point>]) -> Option<Vec<Vec<Point>>>Merges polygons that overlap into one boundary that covers every point once, or returns
Nonewhen the polygons should be kept as they are.For a rasterizer that sums coverage. It adds up what every edge covers, so where two contours overlap, the overlap is counted twice. Many fonts draw a glyph as parts that overlap (Inter's A is a wedge and a crossbar). An embolden from
Font::prepared_outlinealways overlaps the fill of the glyph, and a stroke overlaps itself where a corner is too tight for its width or two parts lie closer than it is wide. Pass the polygonsPath::flattengives.The answer is the outline of the area a nonzero fill of the input covers, in the same units. It can be several contours. Each runs with the filled side on its left, so outer boundaries are counterclockwise and holes clockwise, whichever way the input ran.
Nonemeans keep the polygons you passed. That is the answer when no point is covered twice, which includes contours that lie apart, a hole wound against the contour around it, and two contours wound opposite ways, whose overlap cancels out. It is also the answer when the merge cannot be trusted: where contours meet too closely to call, as can happen where a corner of one lies exactly on an edge of another; where a coordinate is not finite; and where contours cross far more often than their number of edges allows, which no font does and which ends the work early.use daegun::outline::{max_area_for, resolve_overlaps, Path, Point}; use daegun::Location; let max_area = max_area_for(32.0, f32::from(font.units_per_em())); let polygons_of = |ch: char| -> daegun::Result<Vec<Vec<Point>>> { let glyph = font.glyph_id(ch).expect("Inter maps the letter"); let mut path = Path::new(); font.outline(glyph, &Location::default(), &mut path)?; path.flatten(max_area) }; // Inter draws its A as a wedge and a crossbar that overlap. let polygons = polygons_of('A')?; let merged = resolve_overlaps(&polygons); assert!(merged.is_some()); // Fill the merged boundary where there is one, and the polygons as they are where there is none. let to_fill = merged.unwrap_or(polygons); // The H is one contour that never crosses itself: nothing to merge. assert!(resolve_overlaps(&polygons_of('H')?).is_none());Font::cff_hintspub fn cff_hints(&self, glyph: GlyphId, location: &Location) -> Option<CffHints>A CFF or CFF2 glyph's stem hints and hint masks, as its charstring declares them.
For a hinter of your own, or for looking into a font. A CFF glyph marks its stems, the upright and level strokes a hinter keeps even, and may switch sets of them on and off as it draws. This reads those declarations and applies nothing. To have daegun apply them, hint with
HintMode::Font.Edges are in font units. In a variable CFF2 font they are blended at
location, as the outline is, so they match whatFont::outlinedraws there.It returns
Nonefor a glyph that no CFF or CFF2 table draws, as in any TrueType font, and for a glyph whose charstring doesn't decode, which includes a glyph id the font doesn't have. A glyph that declares no hints, such as a space, givesSomewith both lists empty. So does a CFF glyph built from two others byseac, the operator for accented letters.use daegun::Location; // STIX Two Math has CFF outlines. let glyph = font.glyph_id('H').expect("the font maps H"); let hints = font.cff_hints(glyph, &Location::default()).expect("a CFF glyph"); // The H declares five stems. Its two uprights run from x 133 to 225 and from x 553 to 644. assert_eq!(hints.stems.len(), 5); let uprights: Vec<(f32, f32)> = hints.stems.iter().filter(|stem| stem.vertical).map(|stem| (stem.min, stem.max)).collect(); assert_eq!(uprights, [(133.0, 225.0), (553.0, 644.0)]);Font::has_overlap_flagpub fn has_overlap_flag(&self, glyph: GlyphId) -> boolWhether the font flags a glyph as one whose contours or components may overlap.
A TrueType font can mark a glyph whose parts overlap each other. The answer is true where the glyph's
glyfdata carries theOVERLAP_SIMPLEflag, where a glyph it is built from carries it, or where one of its components carriesOVERLAP_COMPOUND.A rasterizer may take it as a cue to treat the glyph with more care: to antialias it more finely, or to merge its contours with
outline::resolve_overlapsbefore it sums their coverage.It is a cue and not a promise. A glyph the font leaves unflagged may overlap all the same. A glyph that CFF, CFF2 or a
VARCtable draws is never flagged, as those formats have no such flag, and neither is a glyph id the font doesn't have. The flag doesn't vary, so the call takes no location.let glyph = font.glyph_id('W').expect("Inter maps W"); if font.has_overlap_flag(glyph) { // Merge the glyph's contours, or antialias it with more care. } // Inter flags none of its glyphs, although the strokes of its W do cross each other. assert!(!font.has_overlap_flag(glyph));Font::hinted_outlinepub fn hinted_outline( &self, glyph: GlyphId, location: &Location, px: f32, mode: HintMode, ) -> Result<Option<HintedOutline>>A glyph's outline hinted at a pixel size, as points to read or draw, or
Nonewhere no hinter takes the glyph.pxis the size in pixels to the em, rounded to the nearest 64th of a pixel and not to a whole one: 16.4 is hinted at 16.40625, not at 16.modepicks the hinter, asHintModedescribes. TheHintedOutlinethat comes back is in pixels, y up, from the glyph's origin, and owns its points.Noneis not a failure. It means no hinter takes this glyph at this size, and the thing to do is draw it unhinted, whichFont::prepared_outlinedoes by itself.HintMode::NonegivesNonefor every glyph. Under any other mode it comes back for a glyph with nothing to draw, for a glyph id the font doesn't have or a glyph that doesn't decode, for a glyph whose points would land too far out to hint at that size, and for a glyph that aVARCtable composes, which has no hints. It also comes back for apxthat, rounded to the nearest 64th of a pixel, is under half a pixel or at 65,535.5 or more.With the font's own hints,
Nonealso means those hints leave the glyph where scaling put it, as they leave a simple TrueType glyph with no instructions in a font without native ClearType. It can mean that the font switches glyph hinting off at this size, or that the hints can't be used: a font program or CVT program that fails, or a CFF Private DICT that doesn't read. With the autohinter, it also means a glyph of more than 65,535 points, or a font that doesn't have enough of the Latin letters the autohinter measures its heights from.The error is
ErrorKind::InvalidArgumentunlesspxis finite and above zero, whatever the mode.Setting up a size runs the font's programs once, and daegun keeps the result for the sizes hinted most recently, so hinting glyph after glyph at one size costs each glyph only its own work.
use daegun::outline::{HintMode, OutlineOptions, Path}; use daegun::Location; let glyph = font.glyph_id('g').expect("Inter maps g"); let at = Location::default(); let mut path = Path::new(); match font.hinted_outline(glyph, &at, 13.0, HintMode::Auto)? { // Fitted to the pixel grid at 13 px: read its points, or draw it as here. Some(hinted) => hinted.draw(&mut path), // No hinter takes this glyph, so draw it as scaled. None => drop(font.prepared_outline(glyph, &at, 13.0, &OutlineOptions::DEFAULT, &mut path)?), } // Either way `path` holds the g in pixels. For Inter's g a hinter did take it. assert!(font.hinted_outline(glyph, &at, 13.0, HintMode::Auto)?.is_some());Font::outlinepub fn outline(&self, glyph: GlyphId, location: &Location, pen: &mut dyn OutlinePen) -> Result<()>Draws a glyph's outline onto a pen, in font units.
The glyph's shape as the font holds it, drawn a contour at a time: a
move_to, then lines and curves, then aclose. A TrueType glyph draws lines and quadratic curves, and a CFF or CFF2 glyph lines and cubic curves. Every point is in font units, y up, measured from the glyph's origin on the baseline.Nothing is scaled, hinted or styled. A point in pixels is the point times
px / f32::from(font.units_per_em()), andFont::prepared_outlinedoes that for you, along with hinting, stroking and the rest.penis anything that implementsOutlinePen. APathrecords the outline to read back or replay, and a pen of your own takes each call as the glyph is decoded.locationpicks the instance of a variable font, and&Location::default()is the default one.A glyph with nothing to draw, such as a space, is
Okand makes no call on the pen.An error is the decoder's reason for a glyph it could not draw.
ErrorKind::NoOutlinemeans the glyph id is past the font's last glyph, or the font has no outlines at all, as a font that holds only bitmaps may have none.ErrorKind::Malformedmeans the glyph's data is cut short or contradicts itself,ErrorKind::Missingthat something it needs is not there,ErrorKind::Unsupportedthat a CFF glyph uses an operator daegun doesn't read, andErrorKind::LimitExceededthat the glyph asks for more work than daegun allows one. By then the pen may already hold part of the glyph, so use what it drew only when the call isOk.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)?; // `path` holds the a in font units: two contours, the outside and the counter of its bowl. let contours = path.segments().filter(|(verb, _)| *verb == Verb::Move).count(); assert_eq!(contours, 2); // It reaches from 26 units under the baseline to 1132 above it, in Inter's em of 2048 units. let bounds = path.bounds().expect("the a has ink"); assert_eq!((bounds.y_min, bounds.y_max), (-26.0, 1132.0));Font::prepared_outlinepub fn prepared_outline( &self, glyph: GlyphId, location: &Location, px: f32, options: &OutlineOptions, pen: &mut (impl OutlinePen + ?Sized), ) -> Result<PreparedGlyph>Draws a glyph's outline onto a pen in pixels at a size, hinted, leaned, transformed, stroked or emboldened as the options say.
The call for a rasterizer of your own. Where
Font::outlineanswers in font units, this one scales the outline topxpixels to the em, so every point reaches the pen in pixels, y up, measured from the glyph's origin. Add the position of the glyph on the line, and flip y for a surface whose y runs down.With
OutlineOptions::DEFAULTthat scaling is all it does. Options are applied in a fixed order: hinting first, then the oblique and the transform, then a stroke or an embolden.OutlineOptionssays what each one does and in which units, and what a stroke or an embolden means for a rasterizer that sums coverage.It returns a
PreparedGlyph: the advances in pixels, and whether a hinter ran. Asking for hinting never fails the call. A glyph no hinter takes is drawn unhinted, andPreparedGlyph::hintedis false.A glyph with nothing to draw, such as a space, is
Okwith its advances and no call on the pen.The error is
ErrorKind::InvalidArgumentunlesspxis finite and above zero and the options are finite: the transform's six numbers, the stroke's width, the embolden and the oblique. It isErrorKind::Overflowwhere an advance, a stroke width or a point would pass whatf32holds once scaled, as a huge transform makes it. Any other kind is the decoder's, asFont::outlinelists them. A call that fails draws nothing onto the pen.use daegun::outline::{HintMode, OutlineOptions, Path}; use daegun::Location; let glyph = font.glyph_id('a').expect("Inter maps a"); let options = OutlineOptions::DEFAULT.with_hinting(HintMode::Auto); let mut path = Path::new(); let prepared = font.prepared_outline(glyph, &Location::default(), 16.0, &options, &mut path)?; // `path` holds the a in pixels at 16 px, fitted to the pixel grid. Fill it where the glyph goes, // then move right by prepared.advance_width, about 8.98 pixels. assert!(prepared.hinted); assert!((prepared.advance_width - 8.98).abs() < 0.01);Font::quadspub fn quads(&self, glyph: GlyphId, location: &Location) -> Result<Vec<Quad>>A glyph's outline as quadratic curves alone, in font units, for a renderer that evaluates curves in a shader.
Every piece of the outline becomes a
Quad: a start, a control and an end. A quadratic curve passes through as it is. A line becomes a curve whose control is its midpoint. A cubic curve, as CFF and CFF2 glyphs draw, is split into quadratics until each lies within 1/4096 of an em of it. A contour that doesn't end where it began is closed with a line. Points are in font units, y up, atlocation.The curves are wound by
outline::normalize_winding, so every font gives the same winding: clockwise, TrueType's way. Where the outline came the other way around, as CFF outlines do, each curve has its start and end swapped and keeps its place in the list, so a curve's end is then the start of the curve before it, not of the one after.The error is
ErrorKind::NoOutlinefor a glyph that draws nothing, such as a space, since there are no curves to give. It isErrorKind::Overflowfor an outline with a point that is not finite or is past a sixteenth of whatf32holds. Any other kind is the decoder's, asFont::outlinelists them.Each call returns a new list.
Font::quads_intofills one you keep.use daegun::{ErrorKind, Location}; let glyph = font.glyph_id('W').expect("Inter maps W"); let curves = font.quads(glyph, &Location::default())?; // 32 curves for Inter's W, its straight edges among them: the first is a line, its control halfway. assert_eq!(curves.len(), 32); assert_eq!(curves[0].control.x, (curves[0].start.x + curves[0].end.x) / 2.0); for curve in &curves { // Hand curve.start, curve.control and curve.end to the shader, in font units. } // A space has no curves, which is an error to handle and not an empty list. let space = font.glyph_id(' ').expect("Inter maps a space"); let error = font.quads(space, &Location::default()).unwrap_err(); assert_eq!(error.kind(), ErrorKind::NoOutline);Font::quads_intopub fn quads_into(&self, glyph: GlyphId, location: &Location, curves: &mut Vec<Quad>) -> Result<()>A glyph's outline as quadratic curves, as
Font::quadsgives them, into a list you keep.For a loop over many glyphs.
curvesis emptied and filled with this glyph's curves, and its capacity is reused, so a list kept between glyphs allocates only when a glyph needs more room than any before it.The errors are those of
Font::quads. On an error the list is left empty, not holding the curves of the glyph before, and it still keeps its capacity.use daegun::outline::Quad; use daegun::Location; let mut curves: Vec<Quad> = Vec::new(); for letter in "Wo a".chars() { let Some(glyph) = font.glyph_id(letter) else { continue }; match font.quads_into(glyph, &Location::default(), &mut curves) { Ok(()) => { /* `curves` holds this glyph's curves, and only this glyph's */ } // The space draws nothing: the list is left empty. Err(_) => assert!(curves.is_empty()), } }outline::HintedOutline::contourspub fn contours(&self) -> &[usize]Where each contour of the hinted outline ends, as the index of its last point.
One entry for each contour, rising. The first contour is the points from 0 to the first entry, and each later one starts right after the end of the one before, so the last entry plus one is the number of points.
use daegun::outline::HintMode; 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)? .expect("the autohinter takes Inter's o"); assert_eq!(hinted.contours(), [23, 47]); let points: Vec<_> = hinted.points().collect(); let mut start = 0; for &end in hinted.contours() { let contour = &points[start..=end]; // 24 points each for the outside of the o and for its counter. assert_eq!(contour.len(), 24); start = end + 1; }outline::HintedOutline::drawpub fn draw(&self, pen: &mut (impl OutlinePen + ?Sized))Draws the hinted outline onto a pen, in pixels.
The pen gets each contour as a
move_to, its lines and curves, and aclose: quadratic curves for a TrueType glyph, cubic ones for a CFF glyph. Coordinates are pixels at the size the glyph was hinted at, y up, from the glyph's origin, so there is nothing left to scale.It can be called as often as you like.
Font::prepared_outlinewith aHintModeand no other option draws the same outline in one step, for when you don't need the points.use daegun::outline::{HintMode, Path, Verb}; 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)? .expect("the autohinter takes Inter's o"); let mut path = Path::new(); hinted.draw(&mut path); // Inter's o is two closed contours of quadratic curves, 24 curves in all. let count = |wanted: Verb| path.segments().filter(|(verb, _)| *verb == wanted).count(); assert_eq!((count(Verb::Move), count(Verb::Quad), count(Verb::Close)), (2, 24, 2));outline::HintedOutline::pointspub fn points( &self, ) -> impl ExactSizeIterator<Item = (Point, PointKind)> + DoubleEndedIterator + core::iter::FusedIterator + CloneEach point of the hinted outline in pixels, with what kind of point it is.
An iterator of
(Point, PointKind)pairs, one contour after another:HintedOutline::contourssays where each contour ends. A point is on the curve, or the control of a quadratic curve as TrueType outlines have them, or one of the two controls of a cubic curve as CFF outlines have them. Coordinates are pixels, y up, in multiples of 1/64.In a TrueType outline two quadratic controls in a row have an on-curve point halfway between them that is not listed, and a contour can start on a control.
HintedOutline::drawfills these in.The iterator knows its length, runs from either end and can be cloned.
use daegun::outline::{HintMode, PointKind}; use daegun::Location; // A test font whose B is a rectangle with TrueType instructions that round its top to a pixel. let glyph = font.glyph_id('B').expect("the font maps B"); let hinted = font .hinted_outline(glyph, &Location::default(), 16.0, HintMode::Font)? .expect("the font hints its B"); for (point, kind) in hinted.points() { // point.x and point.y are pixels. Every corner of a rectangle is on the curve. assert_eq!(kind, PointKind::OnCurve); } // Scaled alone, the top of the B would sit 15.671875 pixels up. Hinted, it sits at 16. let top = hinted.points().map(|(point, _)| point.y).fold(f32::MIN, f32::max); assert_eq!(top, 16.0);outline::HintMode::may_autohintpub const fn may_autohint(self) -> boolWhether the autohinter may take a glyph under this mode.
True for
HintMode::AutoandHintMode::AutoForce, false forHintMode::NoneandHintMode::Font. UnderAutoit means may, not will: a font that keeps its own hints never reaches the autohinter. It is aconst fn.use daegun::outline::HintMode; assert!(HintMode::Auto.may_autohint()); assert!(HintMode::AutoForce.may_autohint()); assert!(!HintMode::Font.may_autohint()); assert!(!HintMode::None.may_autohint());outline::OutlineOptions::with_emboldenpub const fn with_embolden(mut self, units: f32) -> OutlineOptionsThese options making the glyph bolder by so many font units.
A synthetic bold. Every edge of the outline moves out by half of
units, so a stem grows thicker by all of it, and the advance width grows byunitstoo, so the heavier glyphs keep their spacing. In a font with vertical metrics the advance height grows the same way.What reaches the pen is the glyph's own outline, then a band
unitswide with round corners along each of its contours, as lines. Each band lies half over the fill, so the contours always overlap. A non-zero fill hides that, and a rasterizer that sums coverage needs them merged first, withoutline::resolve_overlaps.Zero or less does nothing, and neither does any amount when a stroke is set. The transform doesn't scale it.
use daegun::outline::{resolve_overlaps, OutlineOptions, Path}; use daegun::Location; let glyph = font.glyph_id('o').expect("Inter maps o"); let options = OutlineOptions::DEFAULT.with_embolden(40.0); let mut path = Path::new(); let bold = font.prepared_outline(glyph, &Location::default(), 32.0, &options, &mut path)?; // 40 units are 0.625 pixels at 32 px in Inter: the advance grew from 19.1875 to 19.8125. assert_eq!(bold.advance_width, 19.8125); // For a rasterizer that sums coverage, merge the o and the bands around it into one boundary. let polygons = path.flatten(0.01)?; let merged = resolve_overlaps(&polygons).expect("the bands overlap the fill"); // Six contours went in and two came out: the outside of the o and its counter. assert_eq!((polygons.len(), merged.len()), (6, 2));outline::OutlineOptions::with_hintingpub const fn with_hinting(mut self, hinting: HintMode) -> OutlineOptionsThese options with a hinter to fit the outline to the pixel grid.
See
HintModefor the modes and their exact rules.HintMode::Autois the one to reach for: it takes the autohinter for a TrueType font with no font program and at most a few bytes of CVT program, and the font's own hints for any other.A glyph no hinter takes is drawn unhinted, and
PreparedGlyph::hintedsays which happened.use daegun::outline::{HintMode, OutlineOptions, Path}; use daegun::Location; let glyph = font.glyph_id('o').expect("Inter maps o"); let options = OutlineOptions::DEFAULT.with_hinting(HintMode::Auto); let mut path = Path::new(); let prepared = font.prepared_outline(glyph, &Location::default(), 16.0, &options, &mut path)?; assert!(prepared.hinted); // Unhinted, this o runs from 0.1875 pixels under the baseline to 8.84375 above it. Hinted, its // bottom and its top land on whole pixels. let bounds = path.bounds().expect("the o has ink"); assert_eq!((bounds.y_min, bounds.y_max), (0.0, 9.0));outline::OutlineOptions::with_obliquepub const fn with_oblique(mut self, tangent: f32) -> OutlineOptionsThese options leaning the outline, for a synthetic italic.
tangentis the tangent of the lean from upright. Each point moves right bytangenttimes its height above the baseline, and left by as much below it, so 0.25 leans the glyph about 14 degrees to the right and a negative tangent leans it left.The lean goes on after hinting and before the transform, so a glyph you also turn leans in its own frame. The advances don't change.
use daegun::outline::{OutlineOptions, Path}; use daegun::Location; let glyph = font.glyph_id('H').expect("Inter maps H"); let options = OutlineOptions::DEFAULT.with_oblique(0.25); let mut path = Path::new(); font.prepared_outline(glyph, &Location::default(), 32.0, &options, &mut path)?; // Upright at 32 px, Inter's H spans 2.8125 to 20.96875 pixels across and is 23.28125 tall. // Leaned, its foot stays put and its top moves right by a quarter of that height. let bounds = path.bounds().expect("the H has ink"); assert_eq!(bounds.x_min, 2.8125); assert_eq!(bounds.x_max, 20.96875 + 0.25 * 23.28125);outline::OutlineOptions::with_strokepub const fn with_stroke(mut self, stroke: StrokeStyle) -> OutlineOptionsThese options drawing the outline as a stroke in place of the fill.
The stroke runs along the glyph's contours, half its width to either side, and reaches the pen as closed contours of straight lines for you to fill, its curves flattened to a tolerance of a quarter of a pixel. Each contour of the glyph gives two: the outer edge of its stroke and the inner one.
The width is in font units, and the transform doesn't scale it. A width of 0 draws nothing. An embolden set alongside is ignored, and the advances stay the font's.
A stroke runs over itself where a corner is too tight for its width, or where two parts of the glyph lie closer than it is wide, and its contours overlap there. Fill them with the non-zero rule, or merge them first with
outline::resolve_overlapsfor a rasterizer that sums coverage.use daegun::outline::{OutlineOptions, Path, StrokeStyle, Verb}; use daegun::Location; let glyph = font.glyph_id('o').expect("Inter maps o"); // An outlined o: a line 40 units wide along each of its two contours. let options = OutlineOptions::DEFAULT.with_stroke(StrokeStyle::new(40.0)); let mut path = Path::new(); font.prepared_outline(glyph, &Location::default(), 32.0, &options, &mut path)?; // Each of the two contours became two, and all four are made of lines. let contours = path.segments().filter(|(verb, _)| *verb == Verb::Move).count(); assert_eq!(contours, 4); assert!(path.segments().all(|(verb, _)| matches!(verb, Verb::Move | Verb::Line | Verb::Close)));outline::OutlineOptions::with_transformpub const fn with_transform(mut self, transform: [f32; 6]) -> OutlineOptionsThese options with a transform for the outline.
The six numbers are
[a, b, c, d, dx, dy]: a point(x, y)moves to(a*x + c*y + dx, b*x + d*y + dy). It is applied after hinting and after the oblique, anddxanddyare in font units.It moves and scales the outline only. A stroke keeps its width, an embolden its amount, and the advances in the
PreparedGlyphstay the font's. A number that is not finite makesFont::prepared_outlinefail withErrorKind::InvalidArgument.use daegun::outline::{OutlineOptions, Path}; use daegun::Location; let glyph = font.glyph_id('H').expect("Inter maps H"); // Half size and raised 700 units, as for a superscript made from the full-size glyph. let options = OutlineOptions::DEFAULT.with_transform([0.5, 0.0, 0.0, 0.5, 0.0, 700.0]); let mut path = Path::new(); let prepared = font.prepared_outline(glyph, &Location::default(), 32.0, &options, &mut path)?; // At 32 px, 700 units are 10.9375 pixels: the foot of the H now stands that far above the baseline. let bounds = path.bounds().expect("the H has ink"); assert_eq!(bounds.y_min, 10.9375); // The advance is still the full-size glyph's. assert_eq!(prepared.advance_width, 23.78125);outline::OutlinePen::closefn close(&mut self)Ends the current contour, joining it back to the point its
move_tostarted at.The closing edge is a straight line from the current point to the contour's start. No point is passed, and where the contour already ended on its start there is no edge to add.
The crate's own pens then take the contour's start as the current point. A segment drawn straight after a close, with no
move_tofirst, begins there forQuadraticPenand forPath::flatten.use daegun::outline::{OutlinePen, Path}; let mut path = Path::new(); path.move_to(0.0, 0.0); path.line_to(10.0, 0.0); path.line_to(10.0, 10.0); path.line_to(0.0, 10.0); // Back to (0, 0): the fourth side of the square, with no point passed. path.close(); // Five verbs, and four points, as the close takes none. let (verbs, points) = path.parts(); assert_eq!((verbs.len(), points.len()), (5, 4));outline::OutlinePen::curve_tofn curve_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32)Draws a cubic curve from the current point to a point, shaped by two control points.
(c1x, c1y)is the first control point, which the curve heads for as it leaves the current point.(c2x, c2y)is the second, which it comes from as it arrives at the end,(x, y). CFF and CFF2 outlines are made of these and of lines.use daegun::outline::{OutlinePen, Path}; let mut path = Path::new(); path.move_to(0.0, 0.0); // Leaves (0, 0) straight up, toward (0, 100), and comes down into (100, 0) from (100, 100). path.curve_to(0.0, 100.0, 100.0, 100.0, 100.0, 0.0); path.close(); // The curve stays below its control points: its box tops out at y = 75. let bounds = path.bounds().expect("the curve has points"); assert_eq!(bounds.y_max, 75.0);outline::OutlinePen::line_tofn line_to(&mut self, x: f32, y: f32)Draws a straight line from the current point to a point.
The current point is where the call before ended: the point of a
move_to, or the end of the line or curve before this one. After the call it is(x, y).use daegun::outline::{OutlinePen, Path, Verb}; let mut path = Path::new(); path.move_to(0.0, 0.0); path.line_to(10.0, 0.0); path.line_to(5.0, 8.0); path.close(); // Each line_to recorded one verb and one point, its end. let (verbs, points) = path.parts(); assert_eq!(verbs, [Verb::Move, Verb::Line, Verb::Line, Verb::Close]); assert_eq!(points.len(), 3);outline::OutlinePen::move_tofn move_to(&mut self, x: f32, y: f32)Starts a new contour at a point.
Nothing is drawn by the move itself. The point is where the next line or curve begins, and where
OutlinePen::closeleads back to.A pen of your own should take a move that arrives while a contour is still open as the end of that contour. The crate's own do:
QuadraticPenadds the line that closes it,Path::flattencloses its polygon, andPath::replaysends the missingclosebefore the move.use daegun::outline::{OutlinePen, Path}; let mut path = Path::new(); // Two triangles: each move_to starts a contour of its own. path.move_to(0.0, 0.0); path.line_to(10.0, 0.0); path.line_to(5.0, 8.0); path.close(); path.move_to(20.0, 0.0); path.line_to(30.0, 0.0); path.line_to(25.0, 8.0); path.close(); let polygons = path.flatten(1.0)?; assert_eq!(polygons.len(), 2);outline::OutlinePen::quad_tofn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32)Draws a quadratic curve from the current point to a point, bending toward one control point.
(cx, cy)is the control point and(x, y)the end. The curve leaves the current point heading for the control and arrives at the end coming from it, without passing through the control itself. TrueType outlines are made of these and of lines.use daegun::outline::{OutlinePen, Path}; let mut path = Path::new(); path.move_to(0.0, 0.0); // An arch from (0, 0) to (10, 0), pulled up toward the control point at (5, 10). path.quad_to(5.0, 10.0, 10.0, 0.0); path.close(); // The curve rises halfway to its control and no further: the top of its box is y = 5. let bounds = path.bounds().expect("the arch has points"); assert_eq!(bounds.y_max, 5.0);outline::Path::boundspub fn bounds(&self) -> Option<Bounds>The tight box around what the path draws, or
Nonefor a path with no points.Tight means the curves themselves are measured, at their extremes, not their control points: a control point that lies outside its curve does not widen the box.
The
Boundsis in the units the path was drawn in, y up, asf64.use daegun::outline::Path; use daegun::{Bounds, Location}; let glyph = font.glyph_id('o').expect("Inter maps o"); let mut path = Path::new(); font.outline(glyph, &Location::default(), &mut path)?; // In font units, y up. The o dips 24 units below the baseline. let bounds = path.bounds().expect("the o has points"); assert_eq!(bounds, Bounds { x_min: 104.0, y_min: -24.0, x_max: 1124.0, y_max: 1132.0 }); // A path with nothing in it has no box. assert_eq!(Path::new().bounds(), None);outline::Path::clearpub fn clear(&mut self)Empties the path and keeps its memory.
For a path you draw into again and again. After the first few outlines it has grown to fit, and from then on drawing allocates only for an outline larger than any before it.
use daegun::outline::Path; use daegun::Location; let mut path = Path::new(); for ch in ['l', 'o'] { let glyph = font.glyph_id(ch).expect("Inter maps the letter"); // Without the clear, the o would be added after the l. path.clear(); font.outline(glyph, &Location::default(), &mut path)?; } // The path holds the o alone: 28 verbs. assert_eq!(path.parts().0.len(), 28);outline::Path::costpub const fn cost(&self) -> usizeThe bytes the outline takes: one for each verb and eight for each point.
It counts what the path holds, not the memory set aside for it, so equal paths cost the same. A number to weigh a path by, in a cache of outlines with a budget for example.
use daegun::outline::Path; 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)?; // 28 verbs at a byte each and 50 points at eight: 428 bytes. let (verbs, points) = path.parts(); assert_eq!((verbs.len(), points.len()), (28, 50)); assert_eq!(path.cost(), 428);outline::Path::flattenpub fn flatten(&self, max_area: f32) -> Result<Vec<Vec<Point>>>Turns the path into closed polygons: every curve cut into straight edges, and one list of points for each contour.
The lists come in the order the path holds its contours, in its units. Each is a closed polygon: an edge runs from every point to the next and from the last back to the first, which is not repeated at the end. A contour the path left open is closed the same way. A contour that comes to fewer than three points is left out, so a path with nothing to fill gives an empty list, not an error.
max_areasets how fine the edges are, in square units of the path. A curve is cut in half, and each half again, until twice the area of the triangle between a piece's two ends and its midpoint is no more thanmax_area. A cubic curve is tested at its quarter points too, so an S-shaped piece whose midpoint lies on its chord is still cut. Smaller values give more edges, andmax_area_forworks out the value for a path in font units drawn at a pixel size.A
max_areathat is not finite and above zero, which covers 0, a negative number, NaN and infinity, cuts every curve all the way, 12 halvings, which is at most 4,096 edges for one curve. Only a piece that is already straight is left whole.The polygons keep the direction their contours were drawn in. By the conventions of the formats that is clockwise for the outer contour of a TrueType glyph and counterclockwise for a hole in it, and the reverse for a CFF glyph. Where contours overlap, the polygons do too:
resolve_overlapsmerges them for a rasterizer that needs each point covered once.It fails with
ErrorKind::InvalidArgumentif any coordinate of the path, control points included, is NaN, infinite or further from zero thanf32::MAX / 16. It fails withErrorKind::LimitExceededif the polygons would hold more thanMAX_FLATTEN_POINTSpoints, or if making them meant reading more than twice that many, a count that includes the points of contours that end up left out.use daegun::outline::{max_area_for, Path}; 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)?; // Fine enough to draw at 32 px. let max_area = max_area_for(32.0, f32::from(font.units_per_em())); let polygons = path.flatten(max_area)?; // Two polygons, the bowl and the hole in it, of 48 and 32 points, still in font units. assert_eq!(polygons.len(), 2); assert_eq!((polygons[0].len(), polygons[1].len()), (48, 32)); for polygon in &polygons { // An edge runs from each point to the next, and from the last back to the first. }outline::Path::flatten_intopub fn flatten_into(&self, max_area: f32, contours: &mut Vec<Vec<Point>>) -> Result<()>Flattens the path as
Path::flattendoes, into a list you already own, reusing its memory.For a loop that flattens one outline after another. The inner lists that
contoursheld are filled again, so lists kept between calls allocate only when an outline needs more room than any before it.What the list held is replaced: afterward it holds the polygons of this path and nothing else. The errors are those of
Path::flatten, and on an error the list is left empty.use daegun::outline::{max_area_for, Path, Point}; use daegun::Location; let max_area = max_area_for(32.0, f32::from(font.units_per_em())); let mut path = Path::new(); let mut polygons: Vec<Vec<Point>> = Vec::new(); for ch in "Wave".chars() { let glyph = font.glyph_id(ch).expect("Inter maps the letter"); path.clear(); font.outline(glyph, &Location::default(), &mut path)?; path.flatten_into(max_area, &mut polygons)?; // `polygons` now holds this letter alone, in the memory the letters before it left. } // After the loop it holds the e: one polygon of 71 points.outline::Path::is_emptypub const fn is_empty(&self) -> boolWhether nothing has been drawn into the path.
True until the first pen call of any kind. A glyph with no outline, such as a space, is not an error for
Font::outline: the call succeeds and draws nothing, and this is how you tell.use daegun::outline::Path; use daegun::Location; let space = font.glyph_id(' ').expect("Inter maps a space"); let mut path = Path::new(); font.outline(space, &Location::default(), &mut path)?; // The call succeeded and drew nothing: a space has no outline. assert!(path.is_empty());outline::Path::newpub const fn new() -> PathAn empty path.
It allocates nothing until something is drawn into it.
Path::default()gives the same, and this one is aconst fn, so it also works in a constant or a static.use daegun::outline::Path; use daegun::Location; let mut path = Path::new(); assert!(path.is_empty()); let glyph = font.glyph_id('g').expect("Inter maps g"); font.outline(glyph, &Location::default(), &mut path)?; assert!(!path.is_empty());outline::Path::partspub fn parts(&self) -> (&[Verb], &[Point])The path as two slices: its verbs, and the points of all of them in one list.
The verbs take their points from the list in order.
Verb::MoveandVerb::Linetake one each,Verb::Quadtakes two (its control, then its end),Verb::Cubicthree (two controls, then its end) andVerb::Closenone.Path::segmentsdoes that pairing for you.Use the slices when you want the data as it is stored, to count it or to copy it out. A
Verbis one byte with a fixed value and aPointis twof32s, both laid out as C reads them.use daegun::outline::{OutlinePen, Path, Point, Verb}; let mut path = Path::new(); path.move_to(0.0, 0.0); path.quad_to(5.0, 10.0, 10.0, 0.0); path.close(); let (verbs, points) = path.parts(); assert_eq!(verbs, [Verb::Move, Verb::Quad, Verb::Close]); // One point for the move, then the curve's control and its end. The close takes none. assert_eq!(points.len(), 3); assert_eq!(points[1], Point { x: 5.0, y: 10.0 });outline::Path::replaypub fn replay(&self, transform: Option<&[f64; 6]>, pen: &mut (impl OutlinePen + ?Sized))Draws the recorded outline onto another pen, through a transform if you give one.
Each verb becomes the pen call it was recorded from, in order.
pencan be a pen of any type, or adyn OutlinePen.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). So[s, 0, 0, s, 0, 0]scales bys,[1, 0, 0, 1, dx, dy]moves, and a negativedflips y for a canvas whose y runs down. It is worked out inf64and the pen getsf32.Nonepasses the points on as they are.Contours left open are closed on the way. A contour that a move started and nothing closed gets its
closebefore the next move, or at the end of the path, so a pen that fills is handed closed contours. Segments with no move before them, at the start of the path or after a close, are passed on as they are, with nocloseadded.use daegun::outline::Path; 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)?; // From font units, y up, to 16 px on a canvas whose y runs down, with the baseline at y = 20. let scale = 16.0 / f64::from(font.units_per_em()); let to_canvas = [scale, 0.0, 0.0, -scale, 0.0, 20.0]; let mut pixels = Path::new(); path.replay(Some(&to_canvas), &mut pixels); // The l now stands on y = 20 and reaches up to about y = 8.36. let bounds = pixels.bounds().expect("the l has points"); assert_eq!((bounds.y_min, bounds.y_max), (8.359375, 20.0));outline::Path::segmentspub fn segments(&self) -> impl ExactSizeIterator<Item = (Verb, &[Point])> + FusedIterator + Clone + '_Each verb of the path in order, paired with the points it takes.
The slice that comes with a verb holds one point for
Verb::MoveorVerb::Line(where it goes), two forVerb::Quad(its control, then its end), three forVerb::Cubic(both controls, then its end) and none forVerb::Close.A line or curve starts where the segment before it ended, and that point is not in its slice. Keep the last point of each slice as you go, as the example does.
The iterator knows its length, which is the number of verbs.
use daegun::outline::{Path, Point, 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)?; let (mut lines, mut curves) = (0, 0); let mut at = Point::default(); for (verb, points) in path.segments() { match (verb, points) { (Verb::Move, [start]) => { /* a contour starts at `start` */ } (Verb::Line, [end]) => lines += 1, // from `at` to `end` (Verb::Quad, [control, end]) => curves += 1, // from `at` to `end`, bending toward `control` (Verb::Cubic, [c1, c2, end]) => curves += 1, _ => { /* Verb::Close: back to the contour's start */ } } // The next segment starts where this one ended. if let Some(end) = points.last() { at = *end; } } // Inter's A: 10 lines and 4 quadratic curves, in 18 verbs. assert_eq!((lines, curves), (10, 4)); assert_eq!(path.segments().len(), 18);outline::Path::strokepub fn stroke(&self, style: &StrokeStyle, tolerance: f32, pen: &mut dyn OutlinePen) -> Result<()>Draws the stroke of the path, the band of a given width that runs along it, onto a pen as contours to fill.
The
StrokeStylesets the width, in the units of the path, how corners are joined and how open contours end. The sign of the width is ignored, and a width of 0 draws nothing without being an error.What the pen gets is polygons:
move_to,line_toandclose, never a curve. A closed contour gives two loops, one along each side of it, and an open contour gives one loop all the way around it. A lonemove_towith nothing after it gives a dot the width of the stroke underCap::RoundorCap::Square, and nothing underCap::Butt. A lone point that is closed draws nothing.Fill the result with the nonzero rule,
FillRule::NonZero. The loops overlap where the path crosses itself, where a corner is too tight for the width, and where two parts of the path lie closer than the width. An even-odd fill would turn those places into holes and a rasterizer that sums coverage would count them twice.Path::stroke_simplifiedis for those.toleranceis how far the straight edges may sit from the true curves, in the units of the path. Zero, a negative number or NaN means 0.1. A curve becomes at most 256 lines, as does the arc of a round join or cap, and an infinite tolerance makes each one line.Font::prepared_outlinestrokes with a quarter of a pixel.Points go to the pen as they are worked out, so a stroke of any size draws. Both errors are found before the first point is sent, so a call that fails has drawn nothing:
ErrorKind::InvalidArgumentfor a width that is NaN or infinite, andErrorKind::Overflowif a point of the path is NaN or infinite, or if a point of the stroke would be, as the tip of a sharp miter can pass the range off32long before the width does.use daegun::outline::{OutlinePen, Path, StrokeStyle}; use daegun::Bounds; let mut line = Path::new(); line.move_to(0.0, 0.0); line.line_to(100.0, 0.0); // A stroke 10 units wide, with the default joins and caps: mitered and butt. let mut band = Path::new(); line.stroke(&StrokeStyle::new(10.0), 0.25, &mut band)?; // One closed contour: the rectangle that reaches 5 units to either side of the line. assert_eq!(band.bounds(), Some(Bounds { x_min: 0.0, y_min: -5.0, x_max: 100.0, y_max: 5.0 }));outline::Path::stroke_simplifiedpub fn stroke_simplified(&self, style: &StrokeStyle, tolerance: f32, pen: &mut dyn OutlinePen) -> Result<()>Strokes the path as
Path::strokedoes, with the loops merged where they overlap into one boundary.For a filler that does not use nonzero winding: one that fills even-odd, or sums the coverage of every edge. A plain stroke overlaps itself where the path crosses itself, at a corner too tight for the width, and where two parts lie closer than the width. This draws the outline of the whole inked area instead, so every point inside is covered once.
The pen gets polygons, as from
Path::stroke, with the sametolerance. Where there is nothing to merge, or the overlaps can't be worked out reliably (loops that touch without crossing, or that cross far more often than their edges allow), the loops come out asPath::strokedraws them, and the call still succeeds.Don't rely on the direction of the loops. Merged ones run counterclockwise around the ink, as
resolve_overlapsgives them, and loops that needed no merging keep the directionPath::strokegave them.The stroke is held whole in memory to be merged, so unlike
Path::strokethis has a size limit. The errors are those ofPath::stroke, andErrorKind::LimitExceededfor a stroke of more thanMAX_FLATTEN_POINTSpoints. A call that fails has drawn nothing.use daegun::outline::{OutlinePen, Path, StrokeStyle, Verb}; // A plus sign: two lines that cross. let mut plus = Path::new(); plus.move_to(0.0, 50.0); plus.line_to(100.0, 50.0); plus.move_to(50.0, 0.0); plus.line_to(50.0, 100.0); let style = StrokeStyle::new(10.0); let loops = |path: &Path| path.parts().0.iter().filter(|&&verb| verb == Verb::Move).count(); // The plain stroke is two bars that overlap in the middle. let mut bars = Path::new(); plus.stroke(&style, 0.25, &mut bars)?; assert_eq!(loops(&bars), 2); // Simplified, it is one outline around the whole plus, with 12 corners. let mut outline = Path::new(); plus.stroke_simplified(&style, 0.25, &mut outline)?; assert_eq!(loops(&outline), 1); assert_eq!(outline.parts().1.len(), 12);outline::Path::viewpub fn view(&self) -> PathView<'_>The path borrowed as a
PathView.A view is the same verbs and points as two slices. It reads, measures and replays as the path does, allocates nothing and copies freely.
DisplayList::push_pathtakes one.use daegun::outline::{Path, PathView}; 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)?; // A view is Copy, and the path stays where it is. let view: PathView = path.view(); let copy = view; assert_eq!(view.bounds(), path.bounds()); assert_eq!(copy.to_path(), path);outline::Path::with_capacitypub fn with_capacity(verbs: usize, points: usize) -> PathAn empty path with room set aside for a number of verbs and a number of points.
Drawing up to that many allocates nothing more. Count one verb for each pen call. A move or a line takes one point, a quadratic curve two, a cubic curve three and a close none.
use daegun::outline::Path; use daegun::Location; // Room for 64 verbs and 128 points, which each of these letters fits in. let mut path = Path::with_capacity(64, 128); for ch in "Wave".chars() { let glyph = font.glyph_id(ch).expect("Inter maps the letter"); path.clear(); font.outline(glyph, &Location::default(), &mut path)?; // Use this letter's outline, then go around again. }outline::PathView::boundspub fn bounds(&self) -> Option<Bounds>The tight box around what the view draws, or
Noneif it has no points.As
Path::boundsgives it: the curves are measured at their extremes, so a control point outside its curve does not widen the box. In the units of the outline, y up.use daegun::color::SceneOptions; use daegun::{Bounds, GlyphId, Location}; let scene = font.color_scene(GlyphId(9), &Location::default(), &SceneOptions::default())?; let scene = scene.expect("a color glyph"); // The box of the first outline the scene keeps, in font units. let first = scene.paths().next().expect("the scene has an outline"); assert_eq!(first.bounds(), Some(Bounds { x_min: 100.0, y_min: 250.0, x_max: 900.0, y_max: 950.0 }));outline::PathView::is_emptypub const fn is_empty(&self) -> boolWhether the path the view borrows has nothing drawn into it.
True for a path with no verbs, as
Path::is_emptyis.use daegun::outline::{OutlinePen, Path}; let mut path = Path::new(); assert!(path.view().is_empty()); path.move_to(0.0, 0.0); path.line_to(10.0, 0.0); assert!(!path.view().is_empty());outline::PathView::partspub const fn parts(&self) -> (&'a [Verb], &'a [Point])The view's two slices: the verbs, and the points of all of them in one list.
They pair up as
Path::partsdescribes: each verb takes its points from the front of what is left of the list. The slices borrow from the path or scene the view came from, not from the view, so they can outlive it.use daegun::outline::{OutlinePen, Path, Point, Verb}; let mut path = Path::new(); path.move_to(0.0, 0.0); path.line_to(10.0, 0.0); path.line_to(5.0, 8.0); path.close(); // The view is gone at the end of this line, and the slices live on: they borrow from the path. let (verbs, points): (&[Verb], &[Point]) = path.view().parts(); assert_eq!((verbs.len(), points.len()), (4, 3));outline::PathView::replaypub fn replay(&self, transform: Option<&[f64; 6]>, pen: &mut (impl OutlinePen + ?Sized))Draws the outline onto a pen, through a transform if you give one, as
Path::replaydoes.The transform
[a, b, c, d, dx, dy]sends(x, y)to(a * x + c * y + dx, b * x + d * y + dy), andNonepasses the points on as they are. A contour that a move started and nothing closed reaches the pen with acloseadded.use daegun::outline::{OutlinePen, Path}; let mut path = Path::new(); path.move_to(0.0, 0.0); path.line_to(10.0, 0.0); path.line_to(5.0, 8.0); // Twice the size and 100 units to the right, onto any pen: here another path. let mut moved = Path::new(); path.view().replay(Some(&[2.0, 0.0, 0.0, 2.0, 100.0, 0.0]), &mut moved); let (verbs, points) = moved.parts(); assert_eq!((points[1].x, points[2].y), (120.0, 16.0)); // The triangle was left open, and the replay closed it: a fourth verb. assert_eq!(verbs.len(), 4);outline::PathView::segmentspub fn segments(&self) -> impl ExactSizeIterator<Item = (Verb, &'a [Point])> + FusedIterator + Clone + use<'a>Each verb in order, paired with the points it takes.
The slice holds the end point for a move or a line, the control point and then the end for a quadratic curve, both control points and then the end for a cubic curve, and nothing for a close. A line or curve starts where the segment before it ended, which is not in its slice.
The iterator knows its length, the number of verbs, and its slices borrow from what the view came from, not from the view.
use daegun::outline::{OutlinePen, Path, Verb}; let mut path = Path::new(); path.move_to(0.0, 0.0); path.quad_to(5.0, 10.0, 10.0, 0.0); path.close(); let view = path.view(); let verbs: Vec<Verb> = view.segments().map(|(verb, _)| verb).collect(); assert_eq!(verbs, [Verb::Move, Verb::Quad, Verb::Close]); // The end of a segment is the last point of its slice. A close has none. let ends: Vec<_> = view.segments().filter_map(|(_, points)| points.last()).collect(); assert_eq!((ends[1].x, ends[1].y), (10.0, 0.0));outline::PathView::to_pathpub fn to_path(self) -> PathA
Pathof your own, copied from the view.It allocates and copies the verbs and points. Use it to keep an outline after what the view borrows from is gone, or to reach what only a
Pathhas:Path::flatten,Path::strokeand drawing more into it.use daegun::color::SceneOptions; use daegun::outline::Path; use daegun::{GlyphId, Location}; let scene = font.color_scene(GlyphId(9), &Location::default(), &SceneOptions::default())?; let scene = scene.expect("a color glyph"); // Copy the scene's outlines out, to keep them after the scene is gone. let kept: Vec<Path> = scene.paths().map(|view| view.to_path()).collect(); drop(scene); // An owned path can be flattened. This one comes to a polygon of 4 points. let polygons = kept[0].flatten(1.0)?; assert_eq!(polygons[0].len(), 4);outline::QuadraticPen::finishpub fn finish(mut self) -> Result<Vec<Quad>>Ends the outline and returns its curves, in the order they were drawn.
It consumes the pen. If the last contour was left open, it is closed first with a line back to its start, so every contour in the list is a closed chain: each curve starts where the one before it ended.
The curves run in the direction they were drawn.
normalize_windingmakes them clockwise if your rasterizer wants one direction for every font.There are three errors.
ErrorKind::InvalidArgumentif the tolerance the pen was made with is not finite and above zero, whatever was drawn.ErrorKind::Overflowif a coordinate drawn into the pen was NaN, infinite or further from zero thanf32::MAX / 16.ErrorKind::NoOutlineif no curve came of it: nothing was drawn, or only moves, as for a glyph with no outline such as a space.use daegun::outline::{OutlinePen, QuadraticPen}; use daegun::{ErrorKind, Location}; let mut pen = QuadraticPen::new(0.5); pen.move_to(0.0, 0.0); pen.line_to(10.0, 0.0); pen.line_to(5.0, 8.0); // Two lines were drawn and the contour left open, so finish adds a third to close it. let curves = pen.finish()?; assert_eq!(curves.len(), 3); assert_eq!((curves[2].end.x, curves[2].end.y), (0.0, 0.0)); // A space draws nothing, which is an error here and not an empty list. let space = font.glyph_id(' ').expect("Inter maps a space"); let mut pen = QuadraticPen::new(0.5); font.outline(space, &Location::default(), &mut pen)?; assert_eq!(pen.finish().map_err(|e| e.kind()), Err(ErrorKind::NoOutline));outline::QuadraticPen::newpub fn new(tolerance: f32) -> QuadraticPenA pen that splits cubic curves to within
toleranceof the original.toleranceis a distance in the units the outline is drawn in: how far a quadratic curve may sit from the piece of a cubic it stands for. A smaller one gives more curves.Font::quadsuses 1/4096 of an em, which isunits_per_em / 4096for an outline in font units. Lines and quadratic curves are not affected.A tolerance that is not finite and above zero is not refused here. The pen still takes what you draw, and
QuadraticPen::finishreturns the error.The pen starts with room for 32 curves.
use daegun::outline::{OutlinePen, QuadraticPen}; // One cubic curve, converted at two tolerances. let count = |tolerance: f32| { let mut pen = QuadraticPen::new(tolerance); pen.move_to(0.0, 0.0); pen.curve_to(0.0, 100.0, 100.0, 100.0, 100.0, 0.0); pen.close(); pen.finish().map(|curves| curves.len()) }; // Within 1 unit: 4 curves for the cubic, and 1 for the line that closes the contour. assert_eq!(count(1.0)?, 5); // Within a hundredth of a unit: 16 and 1. assert_eq!(count(0.01)?, 17);outline::QuadraticPen::reusingpub fn reusing(tolerance: f32, mut curves: Vec<Quad>) -> QuadraticPenA pen like the one
QuadraticPen::newmakes, that draws into a list of curves you hand it, reusing its memory.For a loop over many outlines. The list is emptied, and what it held is gone, but its memory is kept and topped up to room for 32 curves. From then on the pen allocates only when an outline has more curves than the list has room for.
QuadraticPen::finishhands the same list back, ready to pass in again.If
QuadraticPen::finishfails, the list is dropped with the pen and the next round starts from an empty one.Font::quads_intoruns this loop for glyphs and keeps the list's memory through a failure too.use daegun::outline::{Quad, QuadraticPen}; use daegun::Location; let tolerance = f32::from(font.units_per_em()) / 4096.0; let mut curves: Vec<Quad> = Vec::new(); for ch in ['l', 'o'] { let glyph = font.glyph_id(ch).expect("Inter maps the letter"); // The pen takes the list, empties it and draws into the memory it already has. let mut pen = QuadraticPen::reusing(tolerance, curves); font.outline(glyph, &Location::default(), &mut pen)?; // finish hands the same list back, now holding this letter's curves. curves = pen.finish()?; } // After the loop: the 24 curves of the o, and none of the l. assert_eq!(curves.len(), 24);outline::StrokeStyle::newpub const fn new(width: f32) -> StrokeStyleA stroke of a given width, with mitered corners and butt caps.
The join is a
Join::Miterwith a limit of 4 and the cap isCap::Butt, as inStrokeStyle::default(), which has a width of 1.widthis in the units of the path being stroked: font units for a glyph throughOutlineOptions::with_stroke. It is aconst fn.use daegun::outline::{Cap, Join, StrokeStyle}; const HAIRLINE: StrokeStyle = StrokeStyle::new(8.0); assert_eq!(HAIRLINE.width, 8.0); assert_eq!(HAIRLINE.join, Join::Miter { limit: 4.0 }); assert_eq!(HAIRLINE.cap, Cap::Butt); assert_eq!(StrokeStyle::default(), StrokeStyle::new(1.0));outline::StrokeStyle::with_cappub const fn with_cap(mut self, cap: Cap) -> StrokeStyleThis style with another cap at the ends of open contours.
See
Capfor the three. A cap shows only on a contour that is not closed, so it changes nothing for a glyph's outline, whose contours all are. The width and the join stay as they were.use daegun::outline::{Cap, OutlinePen, Path, StrokeStyle}; // An underline 500 units long, 100 units under the baseline, 50 thick, with round ends. let mut line = Path::new(); line.move_to(0.0, -100.0); line.line_to(500.0, -100.0); let style = StrokeStyle::new(50.0).with_cap(Cap::Round); let mut underline = Path::new(); line.stroke(&style, 0.1, &mut underline)?; // The round caps reach 25 units past each end. let bounds = underline.bounds().expect("the stroke has ink"); assert_eq!((bounds.x_min, bounds.x_max), (-25.0, 525.0));outline::StrokeStyle::with_joinpub const fn with_join(mut self, join: Join) -> StrokeStyleThis style with another join at its corners.
See
Joinfor the three. The width and the cap stay as they were.use daegun::outline::{Join, OutlineOptions, Path, StrokeStyle, Verb}; use daegun::Location; let glyph = font.glyph_id('H').expect("Inter maps H"); let lines = |join: Join| -> daegun::Result<usize> { let options = OutlineOptions::DEFAULT.with_stroke(StrokeStyle::new(120.0).with_join(join)); let mut path = Path::new(); font.prepared_outline(glyph, &Location::default(), 200.0, &options, &mut path)?; Ok(path.segments().filter(|(verb, _)| *verb == Verb::Line).count()) }; // Beveled, the stroke of Inter's H takes 34 lines. Rounded, each outer corner becomes an arc of several. assert_eq!(lines(Join::Bevel)?, 34); assert!(lines(Join::Round)? > 34);outline::TransformPen::newpub fn new(inner: &'a mut P, t: [f64; 6]) -> SelfA pen that draws onto
innerthrough the transformt.tis[a, b, c, d, dx, dy]: a point(x, y)reachesinneras(a * x + c * y + dx, b * x + d * y + dy).[1, 0, 0, 1, 0, 0]changes nothing,[s, 0, 0, s, 0, 0]scales bys,[1, 0, 0, 1, dx, dy]moves, and[1, 0, 0, -1, 0, h]flips y within a height ofh.The new pen holds
innerby mutable reference, soinneris yours again once the new pen is no longer used.use daegun::outline::{OutlinePen, Path, TransformPen}; let mut flipped = Path::new(); // For a canvas 100 units tall whose y runs down: y becomes 100 - y. let mut pen = TransformPen::new(&mut flipped, [1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); pen.move_to(10.0, 30.0); pen.line_to(20.0, 30.0); pen.line_to(20.0, 90.0); pen.close(); let points = flipped.parts().1; assert_eq!((points[0].x, points[0].y), (10.0, 70.0)); assert_eq!((points[2].x, points[2].y), (20.0, 10.0));
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::Blend::blendpub fn blend(self, cb: Rgb, cs: Rgb) -> RgbThe mode's color formula alone: the color that a backdrop color and a source color make where both are fully there.
This is the function the W3C specification writes as B(Cb, Cs). It takes two straight colors, 0 to 1, and returns one. No alpha comes into it: it answers what an opaque source looks like on an opaque backdrop.
Mind the order. The backdrop comes first here, and the source comes first in
Blend::composite.Only the fifteen blend modes,
Blend::ScreentoBlend::HslLuminosity, have a formula. For a Porter-Duff mode,Blend::CleartoBlend::Plus, the source comes back unchanged, as those modes mix no colors.Blend::compositeis the whole operation, and it calls this inside: it uses the mixed color only for the part where source and backdrop overlap, weighs it by the two alphas and returns a premultiplied result. Callblendalone when you do the alpha work yourself. Its inputs are not clamped.use daegun::color::Blend; let (backdrop, source) = ([0.2, 0.4, 0.6], [0.5, 0.5, 1.0]); // Multiply: each channel of one times the same channel of the other. assert_eq!(Blend::Multiply.blend(backdrop, source), [0.1, 0.2, 0.6]); // Darken: the lower of the two. assert_eq!(Blend::Darken.blend(backdrop, source), [0.2, 0.4, 0.6]); // A Porter-Duff mode mixes nothing and hands the source back. assert_eq!(Blend::SrcOver.blend(backdrop, source), source);color::Blend::compositepub fn composite(self, cs: Rgb, a_s: f32, cb: Rgb, a_b: f32) -> PremultipliedComposites one source color onto one backdrop color under this mode, and returns the result premultiplied.
This is the per-pixel step of popping a layer.
csanda_sare the layer's color and alpha, andcbanda_bthose of what lies under it. Colors go in straight, 0 to 1, and the result comes back as aPremultiplied.It works in two steps, written here with Cs and Cb for the two colors and
asandabfor the two alphas. First the source's color is mixed with the backdrop's, but only as far as the backdrop is there:Cs' = (1 - ab)·Cs + ab·B(Cb, Cs), where B is the mode's formula,Blend::blend. For a Porter-Duff mode B is the source itself, so this step changes nothing. Then two factors of the mode, Fa and Fb, say how much of each side is kept: the color isas·Fa·Cs' + ab·Fb·Cband the alpha isas·Fa + ab·Fb. The blend modes use the factors ofBlend::SrcOver, which are 1 and1 - as.The two alphas are clamped to 0 to 1 on the way in, and each channel and the alpha of the result on the way out. The colors are not clamped on the way in, so keep them within 0 to 1. Every mode returns NaN for a color that is infinite or near the largest
f32, or an alpha that is NaN.For a layer pushed with an
opacity, multiplya_sby it first. No color space is converted, so the result is in the space of the colors you passed. SeeRgb.use daegun::color::{Blend, Premultiplied}; // A half-transparent red layer over opaque white: pink, and opaque. let (red, white) = ([1.0, 0.0, 0.0], [1.0, 1.0, 1.0]); let out = Blend::SrcOver.composite(red, 0.5, white, 1.0); assert_eq!(out, Premultiplied { color: [1.0, 0.5, 0.5], alpha: 1.0 }); // Multiply at half alpha: half the multiplied color (0.5, 0.25, 0), half the gray that was there. let out = Blend::Multiply.composite([1.0, 0.5, 0.0], 0.5, [0.5, 0.5, 0.5], 1.0); assert_eq!(out.color, [0.5, 0.375, 0.25]); // Over nothing there is no backdrop to mix with, so the layer's own color comes through. let out = Blend::Multiply.composite(red, 0.5, [0.0; 3], 0.0); assert_eq!(out, Premultiplied { color: [0.5, 0.0, 0.0], alpha: 0.5 });color::Blend::from_colrpub fn from_colr(mode: u8) -> BlendThe mode that a composite-mode number from a COLR table stands for.
COLR numbers its modes 0 to 27, in the order the variants are declared:
Blend::Clearis 0 andBlend::HslLuminosityis 27. Any other number givesBlend::Clear, which is what the OpenType specification says to do with a mode it doesn't define.You need it only when you read a COLR table's bytes yourself. A scene or a paint graph from daegun already holds a
Blend.use daegun::color::Blend; assert_eq!(Blend::from_colr(3), Blend::SrcOver); assert_eq!(Blend::from_colr(23), Blend::Multiply); // A number COLR does not define clears. assert_eq!(Blend::from_colr(200), Blend::Clear);color::DisplayList::clearpub fn clear(&mut self)Empties the list and keeps its memory, so that filling it again allocates only if it has to grow.
The ops, paths, clip shapes and gradients all go, and every id the list handed out before is void. The buffers keep their capacity. It is for a list you fill again and again, with the push methods or with
color::lower, which adds to whatever a list already holds.use daegun::color::{DisplayList, SceneOptions}; use daegun::{GlyphId, Location}; let options = SceneOptions::DEFAULT; let mut scene = font.color_scene(GlyphId(8), &Location::default(), &options)?.expect("a color glyph"); assert!(!scene.is_empty()); scene.clear(); // Nothing is left, and the list is ready to be filled again. assert!(scene.is_empty()); assert_eq!(scene.paths().len(), 0); assert_eq!(scene, DisplayList::default());color::DisplayList::gradientpub fn gradient(&self, id: GradientId) -> Option<Gradient<'_>>The gradient a
GradientIdnames, orNonefor an id past the list's gradients.It comes back as a
Gradientthat borrows its stops from the list: the shape (linear, radial or sweep), the color stops, what happens past the ends, and a transform from the space the shape is given in to the scene's. That transform is the gradient's own. The transform of the fill places the path and has no say over the gradient.In a scene from
Font::color_scenethe stops are sorted by offset and their colors are final, with the palette and the text color applied.color::gradient::Rampturns one into colors per pixel.use daegun::color::{Extend, GradientKind, Op, Paint, Rgba, SceneOptions}; use daegun::{GlyphId, Location}; let options = SceneOptions::DEFAULT; let scene = font.color_scene(GlyphId(8), &Location::default(), &options)?.expect("a color glyph"); let gradient = scene.ops().iter() .find_map(|op| match op { Op::Fill { paint: Paint::Gradient(id), .. } => scene.gradient(*id), _ => None, }) .expect("this glyph is filled with a gradient"); // A linear gradient from red at x = 100 to blue at x = 900, which repeats past both ends. assert!(matches!(gradient.kind, GradientKind::Linear { x0, x1, .. } if x0 == 100.0 && x1 == 900.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);color::DisplayList::gradientspub fn gradients( &self, ) -> impl ExactSizeIterator<Item = Gradient<'_>> + DoubleEndedIterator + FusedIterator + CloneEvery gradient of the list, in id order.
Item
nis the gradientGradientId(n)names. The iterator knows its length. Use it to build each gradient's color ramp once before you run the ops.use daegun::color::gradient::Ramp; use daegun::color::{GradientId, SceneOptions, IDENTITY}; use daegun::{GlyphId, Location}; let options = SceneOptions::DEFAULT; let scene = font.color_scene(GlyphId(180), &Location::default(), &options)?.expect("a color glyph"); // One ramp per gradient, made before drawing. The matrix takes the scene's space to pixels: // the identity here, your scale and flip in a renderer. let ramps: Vec<Ramp> = scene.gradients().map(|gradient| Ramp::new(&gradient, &IDENTITY)).collect(); // A fill whose paint is Paint::Gradient(GradientId(n)) then samples ramps[n]. assert_eq!(ramps.len(), 5); for (n, gradient) in scene.gradients().enumerate() { assert_eq!(scene.gradient(GradientId(n)), Some(gradient)); }color::DisplayList::is_emptypub const fn is_empty(&self) -> boolWhether the scene draws nothing, which is to say it has no ops.
From
Font::color_scenean empty scene is a color glyph that paints nothing, which is not the same as a glyph with no color description: that one isNone. For an empty scene there is nothing to draw.Only the ops are looked at. An empty scene can still hold paths that no op names.
use daegun::color::SceneOptions; use daegun::{GlyphId, Location}; let options = SceneOptions::DEFAULT; // Glyph 194 of the test font is a color glyph whose one gradient paints nothing. let scene = font.color_scene(GlyphId(194), &Location::default(), &options)?.expect("still a color glyph"); assert!(scene.is_empty()); assert_eq!(scene.ops().len(), 0); // Glyph 193 draws. let scene = font.color_scene(GlyphId(193), &Location::default(), &options)?.expect("a color glyph"); assert!(!scene.is_empty());color::DisplayList::opspub fn ops(&self) -> &[Op]The scene's ops, in the order to draw them.
Do each in turn:
Opsays what a renderer does at each kind. An empty slice is a scene that draws nothing.use daegun::color::{Op, SceneOptions}; use daegun::Location; let a = font.glyph_id('A').expect("Bungee Tint has an A"); let scene = font.color_scene(a, &Location::default(), &SceneOptions::DEFAULT)?.expect("a color glyph"); for op in scene.ops() { if let Op::Fill { path, paint, .. } = op { // Fill scene.path(*path) with `paint`, over what the ops before it drew. } } // Bungee Tint's A is two fills and nothing else. assert_eq!(scene.ops().len(), 2); assert!(scene.ops().iter().all(|op| matches!(op, Op::Fill { .. })));color::DisplayList::pathpub fn path(&self, id: PathId) -> Option<PathView<'_>>The outline a
PathIdnames, orNonefor an id past the list's paths.It comes back as a
PathView, a borrowed outline you can replay into a pen withPathView::replay, measure or copy. Its points are in the path's own space: the op or clip shape that named the path carries the transform that places it.use daegun::color::{Op, PathId, SceneOptions}; use daegun::outline::Path; use daegun::{GlyphId, Location}; let options = SceneOptions::DEFAULT; // Glyph 84 of the test font fills one outline twice, the second time squeezed and stretched. let scene = font.color_scene(GlyphId(84), &Location::default(), &options)?.expect("a color glyph"); for op in scene.ops() { let Op::Fill { path, transform, .. } = *op else { continue }; let outline = scene.path(path).expect("a fill names a path of its scene"); // Replay the outline through the fill's transform to get it where the fill draws it. let mut placed = Path::new(); outline.replay(Some(&transform), &mut placed); } // An id the scene doesn't have is None. assert!(scene.path(PathId(7)).is_none());color::DisplayList::pathspub fn paths(&self) -> impl ExactSizeIterator<Item = PathView<'_>> + DoubleEndedIterator + FusedIterator + CloneEvery path of the list, in id order.
Item
nis the pathPathId(n)names. The iterator knows its length, sopaths().len()counts them. Use it to get every outline ready once, uploaded or flattened or cached, before you run the ops.use daegun::color::{PathId, SceneOptions}; use daegun::outline::Path; use daegun::Location; let a = font.glyph_id('A').expect("Bungee Tint has an A"); let scene = font.color_scene(a, &Location::default(), &SceneOptions::DEFAULT)?.expect("a color glyph"); // Copy every outline out once. A fill of PathId(n) then draws outlines[n]. let outlines: Vec<Path> = scene.paths().map(|outline| outline.to_path()).collect(); assert_eq!(outlines.len(), 2); for (n, outline) in scene.paths().enumerate() { assert_eq!(scene.path(PathId(n)), Some(outline)); }color::DisplayList::pushpub fn push(&mut self, op: Op)Adds an op to the end of the list.
Ops draw in the order they are pushed. Nothing is checked here: it is up to you to name paths, gradients and shapes this list holds, and to give every
Op::PushClipandOp::PushLayerits pop.use daegun::color::{Blend, DisplayList, Op, Paint, Rgba, IDENTITY}; use daegun::outline::{FillRule, OutlinePen, Path}; 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 mut list = DisplayList::default(); let path = list.push_path(square.view()); let paint = Paint::Solid(Rgba::opaque(0, 128, 128)); // A square drawn into a layer of its own, which then shows at half strength. list.push(Op::PushLayer { opacity: 0.5, blend: Blend::SrcOver }); list.push(Op::Fill { path, paint, rule: FillRule::NonZero, transform: IDENTITY }); list.push(Op::PopLayer); assert_eq!(list.ops().len(), 3);color::DisplayList::push_gradientpub fn push_gradient(&mut self, gradient: Gradient<'_>) -> GradientIdAdds a gradient to the list and returns the id that fills name it by.
The stops are copied into the list, so the slice the
Gradientborrows can go away after the call. Ids are handed out in order, starting atGradientId(0). Put the id in aPaint::Gradientto fill with it. The stops are kept as given: nothing sorts or checks them.use daegun::color::{DisplayList, Extend, Gradient, GradientId, GradientKind, Rgba, Stop, IDENTITY}; let stops = [ Stop { offset: 0.0, color: Rgba::opaque(255, 0, 0) }, Stop { offset: 1.0, color: Rgba::opaque(0, 0, 255) }, ]; // A linear gradient from red at x = 0 to blue at x = 100. let kind = GradientKind::Linear { x0: 0.0, y0: 0.0, x1: 100.0, y1: 0.0 }; let mut list = DisplayList::default(); let id = list.push_gradient(Gradient::new(kind, &stops, Extend::Pad, IDENTITY)); assert_eq!(id, GradientId(0)); // The list holds its own copy of the stops. A fill uses it as Paint::Gradient(id). assert_eq!(list.gradient(id).expect("the id it gave").stops, stops);color::DisplayList::push_pathpub fn push_path(&mut self, path: PathView<'_>) -> PathIdAdds a path to the list and returns the id that ops name it by.
The outline is copied into the list, so the
PathViewyou pass need not outlive the call. Ids are handed out in order, starting atPathId(0). Put the id in anOp::Fillor aClipShapeto use the path. Adding one outline twice stores it twice, so keep the id and name it again.use daegun::color::{DisplayList, Op, Paint, PathId, Rgba, IDENTITY}; use daegun::outline::{FillRule, OutlinePen, Path}; 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 mut list = DisplayList::default(); let path = list.push_path(square.view()); assert_eq!(path, PathId(0)); // One path, filled twice: where it lies, and again 150 units to the right. let paint = Paint::Solid(Rgba::opaque(201, 9, 0)); let moved = [1.0, 0.0, 0.0, 1.0, 150.0, 0.0]; list.push(Op::Fill { path, paint, rule: FillRule::NonZero, transform: IDENTITY }); list.push(Op::Fill { path, paint, rule: FillRule::NonZero, transform: moved }); assert_eq!(list.path(path), Some(square.view()));color::DisplayList::push_shapespub fn push_shapes(&mut self, shapes: &[ClipShape]) -> Range<usize>Adds clip shapes to the list and returns the range an
Op::PushClipnames them by.The shapes are copied onto the end of the list's shapes, and the range covers exactly the ones this call added. Put it in an
Op::PushClip, push the ops to be clipped, then push anOp::PopClip.A shape's
pathis read as an id of this list, so add the paths first. AClipShapecannot be written from nothing outside daegun, so take one from a scene and set its fields, as the example does.use daegun::color::{DisplayList, Op, SceneOptions}; use daegun::{GlyphId, Location}; // Take the clip a color glyph's scene opens with: its clip box, as one shape. let options = SceneOptions::DEFAULT; let scene = font.color_scene(GlyphId(8), &Location::default(), &options)?.expect("a color glyph"); let Op::PushClip { shapes } = scene.ops()[0] else { panic!("the scene opens with a clip") }; let mut shape = scene.shapes(shapes)[0]; // Use it in a list of our own. A shape names its path by id, so copy the path over too // and point the shape at the copy. let mut list = DisplayList::default(); shape.path = list.push_path(scene.path(shape.path).expect("the shape's path")); let clip = list.push_shapes(&[shape]); list.push(Op::PushClip { shapes: clip }); // ... push the fills to clip here ... list.push(Op::PopClip); assert_eq!(list.shapes(clip), [shape]);color::DisplayList::shapespub fn shapes(&self, shapes: Range<usize>) -> &[ClipShape]The clip shapes an
Op::PushClipnames.Pass the range the op holds and get its
ClipShapes back as a slice. A range that reaches past the list's shapes gives an empty slice, not a panic.The range is a
core::range::Range<usize>, the range type that isCopy, so theshapesof an op goes straight in.(0..2).into()makes one from range syntax.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"); for op in scene.ops() { let Op::PushClip { shapes } = *op else { continue }; for shape in scene.shapes(shapes) { let outline = scene.path(shape.path).expect("a shape names a path of its scene"); // Add `outline`, placed by shape.transform, to this clip. } } // A range past the scene's shapes reads as no shapes. assert!(scene.shapes((100..102).into()).is_empty());color::Gradient::newpub const fn new(kind: GradientKind, stops: &'s [Stop], extend: Extend, transform: [f64; 6]) -> Gradient<'s>A gradient from its four parts.
The way to make a gradient of your own, since the struct can't be built by literal. It borrows the stops and copies nothing, and as a
const fnit can build a constant.transformtakes the spacekindis written in to the space you draw in. PassIDENTITYwhen they are the same.Nothing is checked or sorted here.
Rampsorts its own copy of the stops when it is built, andDisplayList::push_gradientcopies them into a scene as they are.use daegun::color::gradient::Ramp; use daegun::color::{Extend, Gradient, GradientKind, Rgba, Stop, IDENTITY}; // A glow: white at (50, 50), fading to nothing 50 away. let stops = [ Stop { offset: 0.0, color: Rgba::opaque(255, 255, 255) }, Stop { offset: 1.0, color: Rgba { r: 255, g: 255, b: 255, a: 0 } }, ]; let circles = GradientKind::Radial { x0: 50.0, y0: 50.0, r0: 0.0, x1: 50.0, y1: 50.0, r1: 50.0 }; let glow = Gradient::new(circles, &stops, Extend::Pad, IDENTITY); let ramp = Ramp::new(&glow, &IDENTITY); // About halfway out the white is about half faded, and past the outer circle it is gone. assert_eq!(ramp.at(74.0, 49.0), Some(Rgba { r: 255, g: 255, b: 255, a: 130 })); assert_eq!(ramp.at(0.0, 0.0), Some(Rgba { r: 255, g: 255, b: 255, a: 0 }));color::gradient::Ramp::atpub fn at(&self, dx: f64, dy: f64) -> Option<Rgba>The color the gradient paints at one pixel, or
Nonewhere it paints nothing.(
dx,dy) is a pixel in the spaceto_deviceled to, and the sample is taken at its center, half a pixel in from the corner the coordinates name:at(10.0, 20.0)reads the point (10.5, 20.5). The coordinates aref64and need not be whole, so to sample an exact point, pass it less 0.5 each way.The color is straight sRGB, like the stops. On a stop it is that stop's color exactly, and past the first or the last stop
Extenddecides.Nonemeans the gradient leaves the pixel alone, which is not the same as a color with an alpha of 0. A ramp that paints nothing answersNoneeverywhere:Ramp::newlists those. A radial gradient also answers it pixel by pixel, wherever none of its circles passes through the point, such as outside the band that two equal circles set side by side sweep out, which runs on past both of them.It takes
&selfand aRampisSync, so several threads may sample one ramp at once.use daegun::color::gradient::Ramp; use daegun::color::{Extend, Gradient, GradientKind, Rgba, Stop, IDENTITY}; let stops = [ Stop { offset: 0.0, color: Rgba::opaque(255, 0, 0) }, Stop { offset: 1.0, color: Rgba::opaque(0, 0, 255) }, ]; // Two circles of radius 10, 100 apart on the x axis: they and the circles past them sweep a band 20 high. let band = GradientKind::Radial { x0: 0.0, y0: 0.0, r0: 10.0, x1: 100.0, y1: 0.0, r1: 10.0 }; let ramp = Ramp::new(&Gradient::new(band, &stops, Extend::Pad, IDENTITY), &IDENTITY); let mut painted = 0; for y in 0..40 { for x in 0..100 { match ramp.at(f64::from(x), f64::from(y)) { Some(color) => { // Write `color` to pixel (x, y). painted += 1; } None => {} // Outside the band: leave the pixel as it is. } } } // Only the 10 rows whose centers lie within 10 of the x axis are painted, here and past both circles. assert_eq!(painted, 10 * 100);color::gradient::Ramp::newpub fn new(g: &Gradient, to_device: &[f64; 6]) -> RampPrepares a gradient for sampling in pixels, blending its colors in linear light.
to_deviceis theMatrixthat takes the scene's space to pixels. For a color glyph that is from font units, y up, to where the glyph sits on your surface, usually with y flipped. The gradient's owntransformis applied first andto_deviceafter it, so you pass the placement of the scene alone, the same matrix for every gradient in it. Leave the fill's owntransformout: that one places the path, not the gradient.Colors between stops are blended in linear light with the alpha premultiplied, as the OpenType specification asks.
Ramp::with_interpolationoffers the other way.There is no error to handle. A gradient that can't be drawn gives a ramp that paints nothing, and
Ramp::atthen returnsNoneeverywhere. That is a gradient with no stops, one whose stops all share an offset underExtend::RepeatorExtend::Reflect, one whose two transforms together have no inverse (a scale of 0, a NaN or an infinity), a linear gradient whose two points are the same, a radial one whose two circles are the same, and a sweep whose two angles are the same under repeat or reflect.Two cases paint flat color. A single stop paints its color everywhere, whatever the shape and the transforms, even ones with no inverse. A sweep whose two angles are the same under
Extend::Padpaints the first stop's color below that angle and the last stop's from it on.The stops are copied, so the gradient and its scene can be dropped once the ramp is built.
use daegun::color::gradient::Ramp; use daegun::color::{Op, Paint, Rgba, 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 ramp = scene.ops().iter().find_map(|op| match op { Op::Fill { paint: Paint::Gradient(id), .. } => Some(Ramp::new(&scene.gradient(*id)?, &to_device)), _ => None, }); let ramp = ramp.expect("the glyph has a gradient fill"); // `at` samples a pixel's center, so 49.5 reads x = 50 px, 500 font units: halfway across the glyph, // where red and blue mix half and half in linear light. assert_eq!(ramp.at(49.5, 50.0), Some(Rgba::opaque(188, 0, 188)));color::gradient::Ramp::with_interpolationpub fn with_interpolation(g: &Gradient, to_device: &[f64; 6], how: Interpolation) -> RampPrepares a gradient for sampling as
Ramp::newdoes, with the blend between stops of your choosing.Everything is as in
Ramp::new: the sameto_device, and the same gradients that paint nothing.howpicks what the colors between stops are worked out on.Interpolation::LinearLightis whatRamp::newuses, andInterpolation::Srgbaverages the stored sRGB numbers with straight alpha, for matching a renderer that does the same.A pixel that falls exactly on a stop gets that stop's color either way. Only what lies between stops changes.
use daegun::color::gradient::{Interpolation, Ramp}; use daegun::color::{Extend, Gradient, GradientKind, Rgba, Stop, IDENTITY}; let stops = [ Stop { offset: 0.0, color: Rgba::opaque(255, 0, 0) }, Stop { offset: 1.0, color: Rgba::opaque(0, 0, 255) }, ]; 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); // Halfway from red to blue, each way. (`at` samples half a pixel in, so 49.5 reads x = 50.) let linear = Ramp::with_interpolation(&gradient, &IDENTITY, Interpolation::LinearLight); assert_eq!(linear.at(49.5, 0.0), Some(Rgba::opaque(188, 0, 188))); let srgb = Ramp::with_interpolation(&gradient, &IDENTITY, Interpolation::Srgb); assert_eq!(srgb.at(49.5, 0.0), Some(Rgba::opaque(128, 0, 128)));color::PaintGraph::newpub fn new() -> PaintGraphAn empty graph, to build by hand or to fill with
Font::visit_paint_graph.An empty graph reads as a
PaintNode::Layerswith nothing below it, which draws nothing.PaintGraph::default()gives the same.With the
stdfeature it takes over the memory of the last graph dropped on this thread, when one was kept, so filling it allocates only once it outgrows that.use daegun::color::{PaintGraph, PaintNode}; use daegun::{GlyphId, Location}; let mut graph = PaintGraph::new(); assert!(matches!(graph.root().node(), PaintNode::Layers)); assert_eq!(graph.root().children().count(), 0); // A graph is a visitor, so the font can fill one you own. It comes out as Font::paint_graph gives it. let found = font.visit_paint_graph(GlyphId(8), &Location::default(), 0, &mut graph); assert!(found); assert_eq!(Some(graph), font.paint_graph(GlyphId(8), &Location::default(), 0));color::PaintGraph::rootpub const fn root(&self) -> PaintRef<'_>The paint at the top of the graph, where reading it starts.
The root is the first paint entered. In a graph read from a font that is the glyph's root paint. An empty graph has none, and its root reads as a
PaintNode::Layerswith no children.The
PaintRefit returns borrows the graph.use daegun::color::PaintNode; use daegun::{GlyphId, Location}; let graph = font.paint_graph(GlyphId(8), &Location::default(), 0).expect("a COLR version 1 glyph"); let root = graph.root(); // This glyph's root clips to an outline, and the one paint below it is the gradient that fills it. assert!(matches!(root.node(), PaintNode::Glyph { .. })); let fill = root.children().next().expect("a fill"); assert!(matches!(fill.node(), PaintNode::LinearGradient { .. }));color::PaintGraph::withpub fn with(&mut self, node: PaintNode<'_>, below: impl FnOnce(&mut PaintGraph)) -> &mut PaintGraphAdds a paint to a graph built by hand, with the paints below it added inside the closure.
It enters
node, runsbelowon the same graph so the closure can add the paints undernode, then leaves. That isPaintVisitor::enterandPaintVisitor::leavepaired for you, so the nesting of your closures is the nesting of the paints. It returns the graph, so calls chain to add paints side by side.The first paint added is the root. Add everything else inside its closure: a second paint added at the top level is not below the root, and
PaintGraph::rootnever reaches it.Give each paint the children its kind reads: one for
PaintNode::Glyph,PaintNode::ColrGlyphand the transforms, two forPaintNode::Composite(the source, then the backdrop), any number forPaintNode::Layers, and none for a fill. A child you leave out reads as layers with nothing in them.A gradient's
stopsare copied into the graph, so the slice need not outlive the call.ColorStophas no constructor, so the stops of a gradient you add are ones read from a font.use daegun::color::{PaintGraph, PaintNode, Rgba}; use daegun::GlyphId; // Two outlines, one over the other: glyph 4 in red, then glyph 5 in the color of the text. let red = PaintNode::Solid { color: Rgba::opaque(200, 30, 30), foreground: false }; let text = PaintNode::Solid { color: Rgba::opaque(0, 0, 0), foreground: true }; let mut graph = PaintGraph::new(); graph.with(PaintNode::Layers, |layers| { layers .with(PaintNode::Glyph { glyph: GlyphId(4) }, |glyph| { glyph.with(red, |_| {}); }) .with(PaintNode::Glyph { glyph: GlyphId(5) }, |glyph| { glyph.with(text, |_| {}); }); }); let layers: Vec<PaintNode> = graph.root().children().map(|paint| paint.node()).collect(); assert_eq!(layers, [PaintNode::Glyph { glyph: GlyphId(4) }, PaintNode::Glyph { glyph: GlyphId(5) }]);color::PaintRef::childrenpub fn children(&self) -> impl core::iter::FusedIterator<Item = PaintRef<'a>> + Clone + use<'a>The paints directly below this one, in the graph's order.
How many there are depends on the paint. In a graph read from a font,
PaintNode::Layershas one for each layer, the bottom layer first.PaintNode::Compositehas two: the source, then the backdrop.PaintNode::Glyph,PaintNode::ColrGlyphand the transforms have one. The fills,PaintNode::Solidand the three gradients, have none.The iterator gives direct children only, so recurse to reach the whole tree. It is
Clone, and it borrows the graph alone, so it can outlive the ref you called it on.use daegun::color::PaintNode; use daegun::{GlyphId, Location}; let graph = font.paint_graph(GlyphId(123), &Location::default(), 0).expect("a COLR version 1 glyph"); // The root stacks two layers, and the upper one is a composite. let layers: Vec<_> = graph.root().children().collect(); assert_eq!(layers.len(), 2); assert!(matches!(layers[1].node(), PaintNode::Composite { .. })); // A composite's children are its source, then its backdrop. let mut parts = layers[1].children(); let source = parts.next().expect("a source"); let backdrop = parts.next().expect("a backdrop"); assert!(parts.next().is_none()); // Here each is a scaled glyph, with one paint below it. assert_eq!(source.children().count(), 1); assert_eq!(backdrop.children().count(), 1);color::PaintRef::nodepub fn node(&self) -> PaintNode<'a>The paint's own values, as a
PaintNode.The node holds what the paint itself says: a color, a gradient's points and stops, a transform's numbers, the glyph to clip to. It does not hold the paints below, which
PaintRef::childrengives.A gradient's
stopsborrow the graph, so the node lives as long as the graph does, not only as long as this ref.use daegun::color::PaintNode; use daegun::{GlyphId, Location}; let graph = font.paint_graph(GlyphId(154), &Location::default(), 0).expect("a COLR version 1 glyph"); let fill = graph.root().children().next().expect("a fill"); match fill.node() { // This glyph is filled with the color of the text, at full strength. PaintNode::Solid { color, foreground } => assert!(foreground && color.a == 255), other => panic!("not a solid fill: {other:?}"), }color::PaintVisitor::enterfn enter(&mut self, node: PaintNode<'_>)Called for each paint as the walk reaches it, before any of the paints below it.
nodeis the paint's own values. The paints below it follow as further calls toenter, and thePaintVisitor::leavethat pairs with this call comes after the last of them. A fill has nothing below it, so itsleavecomes straight after.A gradient's
stopsare lent for this call only. Copy them, withstops.to_vec(), to keep them.use daegun::color::{PaintNode, PaintVisitor, Rgba}; use daegun::{GlyphId, Location}; // The palette colors of a color glyph's solid fills. struct Colors(Vec<Rgba>); impl PaintVisitor for Colors { fn enter(&mut self, node: PaintNode<'_>) { if let PaintNode::Solid { color, foreground: false } = node { self.0.push(color); } } fn leave(&mut self) {} } let mut colors = Colors(Vec::new()); font.visit_paint_graph(GlyphId(169), &Location::default(), 0, &mut colors); // Eight fills, and the first, at the bottom, is red. assert_eq!(colors.0.len(), 8); assert_eq!(colors.0[0], Rgba::opaque(255, 0, 0));color::PaintVisitor::leavefn leave(&mut self)Called when a paint is done: the last paint entered and not yet left, with every paint below it visited.
It takes no argument because it always closes the innermost open paint, as a closing bracket does. Every
PaintVisitor::entergets exactly oneleave.Use it to undo what
enterset up for that paint: pop a transform, close a clip, end a group. A visitor that tracks nothing by depth leaves the body empty.use daegun::color::{PaintNode, PaintVisitor}; use daegun::{GlyphId, Location}; // Adds up the Translate paints in force around each fill. #[derive(Default)] struct Moves { stack: Vec<(f64, f64)>, fills: Vec<(f64, f64)>, } impl PaintVisitor for Moves { fn enter(&mut self, node: PaintNode<'_>) { let (mut x, mut y) = self.stack.last().copied().unwrap_or((0.0, 0.0)); match node { PaintNode::Translate { dx, dy } => (x, y) = (x + dx, y + dy), PaintNode::Solid { .. } | PaintNode::LinearGradient { .. } => self.fills.push((x, y)), _ => {} } self.stack.push((x, y)); } fn leave(&mut self) { // What enter pushed for this paint comes off again. self.stack.pop(); } } let mut moves = Moves::default(); font.visit_paint_graph(GlyphId(177), &Location::default(), 0, &mut moves); // Two layers: one moved 150 units right, the other 150 left. assert_eq!(moves.fills, [(150.0, 0.0), (-150.0, 0.0)]); assert!(moves.stack.is_empty());color::Rgba::fadepub fn fade(self, by: f64) -> RgbaThe same color with its alpha multiplied by a factor.
byis clamped to 0 to 1 first, so it can only lower the alpha: 0.5 halves it, 0 makes the color fully transparent, and anything above 1 leaves it as it is. The result is rounded to the nearest whole alpha. Red, green and blue are untouched, as the alpha is straight.A
bythat is NaN or infinite returns the color unchanged.use daegun::color::Rgba; let ink = Rgba::opaque(20, 20, 20); // At half strength: 255 * 0.5 rounds to 128. assert_eq!(ink.fade(0.5), Rgba { r: 20, g: 20, b: 20, a: 128 }); // A factor above 1 is clamped, so the alpha never grows. assert_eq!(ink.fade(0.5).fade(4.0).a, 128); assert_eq!(ink.fade(f64::NAN), ink);color::Rgba::opaquepub const fn opaque(r: u8, g: u8, b: u8) -> RgbaA color from its red, green and blue, with an alpha of 255.
A
const fn, so a color can be a constant. For a color that is not opaque, write the struct out, or callRgba::fadeon an opaque one.use daegun::color::{Op, Paint, Rgba, SceneOptions}; use daegun::{GlyphId, Location}; const INK: Rgba = Rgba::opaque(200, 0, 0); assert_eq!(INK, Rgba { r: 200, g: 0, b: 0, a: 255 }); // Glyph 154 of the COLR test font is painted in the text's color, which is INK here. let options = SceneOptions::DEFAULT.with_foreground(INK); let scene = font.color_scene(GlyphId(154), &Location::default(), &options)?.expect("a color glyph"); let fills_in_ink = scene.ops().iter().any(|op| matches!(op, Op::Fill { paint: Paint::Solid(INK), .. })); assert!(fills_in_ink);color::SceneOptions::with_foregroundpub const fn with_foreground(mut self, foreground: Rgba) -> SceneOptionsThese options with the color of the text.
Layers and paints that ask for the foreground take this color. Everything that names a palette entry stays as it is. Pass the color the rest of the line is drawn in, so the glyph matches it.
use daegun::color::{Op, Paint, Rgba, SceneOptions}; use daegun::Location; // A glyph of two layers: the first in the text color, the second in a palette color. let glyph = font.glyph_id('F').expect("the font maps F"); let teal = Rgba::opaque(0, 128, 128); let options = SceneOptions::DEFAULT.with_foreground(teal); let scene = font.color_scene(glyph, &Location::default(), &options)?.expect("a color glyph"); let colors: Vec<Rgba> = scene.ops().iter() .filter_map(|op| match op { Op::Fill { paint: Paint::Solid(c), .. } => Some(*c), _ => None }) .collect(); // Only the first layer took it. assert_eq!(colors, [teal, Rgba::opaque(26, 26, 204)]);color::SceneOptions::with_palettepub const fn with_palette(mut self, palette: u16) -> SceneOptionsThese options with a palette, chosen by its index.
Indexes run from 0 to one less than
Font::palette_count. An index past them is not an error: it reads palette 0.use daegun::color::{Op, Paint, Rgba, SceneOptions}; use daegun::Location; let a = font.glyph_id('A').expect("Bungee Tint has an A"); let colors = |palette: u16| -> daegun::Result<Vec<Rgba>> { let options = SceneOptions::DEFAULT.with_palette(palette); let scene = font.color_scene(a, &Location::default(), &options)?.expect("a color glyph"); let solid = |op: &Op| match op { Op::Fill { paint: Paint::Solid(c), .. } => Some(*c), _ => None }; Ok(scene.ops().iter().filter_map(solid).collect()) }; // The default palette draws the A in red, and palette 1 draws it in white and gray. assert_eq!(colors(0)?, [Rgba::opaque(201, 9, 0), Rgba::opaque(255, 149, 128)]); assert_eq!(colors(1)?, [Rgba::opaque(255, 255, 255), Rgba::opaque(232, 232, 231)]);color::Stops::resolvepub fn resolve(mut stops: Vec<Stop>, extend: Extend) -> StopsTurns a list of stops into what is drawn: nothing, one color, or two or more stops in order.
An empty list is
Stops::Nothing. A single stop isStops::Solidwith its color, whatever its offset. Two or more come back asStops::Many: an offset below 0 becomes 0, one above 1 becomes 1, a NaN offset counts as 0, and the list is sorted by offset with ties left in the order given. That list is the vector you passed, reordered in place.Stops that all share one offset depend on
extend. UnderExtend::Padthey are a hard edge and stayStops::Many, which aRampdraws with the first stop's color before that offset and the last stop's from it on. UnderExtend::RepeatandExtend::Reflectthere is no span to repeat, COLR calls such a line ill-formed, and the answer isStops::Nothing. That test is made before the offsets are clamped, with a NaN already read as 0.Offsets are clamped, not rescaled. A color line whose stops reach past 0 to 1 needs its shape moved to match first, which
Font::color_sceneandRampboth do before they resolve.use daegun::color::{Extend, Rgba, Stop, Stops}; let (red, green, blue) = (Rgba::opaque(255, 0, 0), Rgba::opaque(0, 255, 0), Rgba::opaque(0, 0, 255)); // Out of order and past both ends: sorted, and clamped to 0 to 1. let messy = vec![ Stop { offset: 2.0, color: blue }, Stop { offset: -1.0, color: red }, Stop { offset: 0.5, color: green }, ]; let Stops::Many(stops) = Stops::resolve(messy, Extend::Pad) else { panic!("three stops stay many") }; assert_eq!(stops.iter().map(|s| s.offset).collect::<Vec<_>>(), [0.0, 0.5, 1.0]); assert_eq!(stops[0].color, red); // Two stops at one offset: a hard edge under pad, and nothing to repeat under repeat. let edge = vec![Stop { offset: 0.5, color: red }, Stop { offset: 0.5, color: blue }]; assert!(matches!(Stops::resolve(edge.clone(), Extend::Pad), Stops::Many(_))); assert_eq!(Stops::resolve(edge, Extend::Repeat), Stops::Nothing);daegun::color::concatpub const fn concat(first: &Matrix, second: &Matrix) -> MatrixThe one matrix that does what two do in a row:
first, thensecond.A point sent through the result lands where it would after going through
firstand then throughsecond. The order matters: scaling and then moving is not moving and then scaling.It is how the transforms of a scene are chained.
concat(&transform, &to_device)takes a fill's path from its own space through the scene's and on to pixels, wheretransformis the fill's andto_deviceis your placement of the scene.A
const fn, so a chained matrix can be a constant.use daegun::color::concat; let double = [2.0, 0.0, 0.0, 2.0, 0.0, 0.0]; let right = [1.0, 0.0, 0.0, 1.0, 10.0, 0.0]; // Double, then move right by 10: the point (1, 1) goes to (12, 2). assert_eq!(concat(&double, &right), [2.0, 0.0, 0.0, 2.0, 10.0, 0.0]); // Move, then double: the move is doubled too, and (1, 1) goes to (22, 2). assert_eq!(concat(&right, &double), [2.0, 0.0, 0.0, 2.0, 20.0, 0.0]);daegun::color::invertpub fn invert(t: &Matrix) -> Option<Matrix>The matrix that undoes another, or
Noneif nothing can.Send a point through
tand then through the result, and it is back where it started. Use it to go from a pixel back to font units, for hit testing, or to bring a pixel into a gradient's own space.Nonemeansthas no inverse: it flattens the plane onto a line or a point, as a scale of 0 does, it holds a NaN or an infinity, or its numbers are so large or so small that working out the inverse inf64overflows, as a scale of 1e200 or 1e-200 does.use daegun::color::invert; // Font units to pixels: an eighth the size, y flipped, the baseline 125 px down. let to_device = [0.125, 0.0, 0.0, -0.125, 0.0, 125.0]; let to_font = invert(&to_device).expect("a scale that is not 0 can be undone"); // Pixel (50, 25) is the point (400, 800) in font units. let (px, py) = (50.0, 25.0); let x = to_font[0] * px + to_font[2] * py + to_font[4]; let y = to_font[1] * px + to_font[3] * py + to_font[5]; assert_eq!((x, y), (400.0, 800.0)); // A matrix that flattens everything onto a line has no inverse. assert_eq!(invert(&[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]), None);daegun::color::lowerpub fn lower( glyph: GlyphId, graph: &PaintGraph, ctm: Matrix, clip_box: &dyn Fn(GlyphId) -> Option<Bounds>, outline: &mut dyn FnMut(GlyphId, &mut dyn OutlinePen) -> bool, foreground: Rgba, out: &mut DisplayList, ) -> boolTurns a color glyph's paint graph into drawing steps added to a
DisplayList, the wayFont::color_scenedoes.Font::color_sceneis the call to use. Reach for this one when part of the job has to go differently: outlines from somewhere else, a transform built into the scene, a graph you made or changed, or several glyphs lowered into one list.glyphis the color glyph being drawn andgraphits paint graph, fromFont::paint_graphor built by hand.ctmis aMatrixlaid over everything: it becomes thetransformof each fill and clip, after any transform the graph has around them, and it is folded into each gradient's. PassIDENTITYto keep the scene in font units.clip_boxanswers a color glyph's clip box in font units, orNoneif it has none. It is asked aboutglyphitself and about any other color glyph the graph refers to, and a box it answers becomes a clip around that glyph's paints.Font::colr_clip_boxis the usual answer.outlinedraws one glyph's outline onto the pen it is handed, in font units, and returns false if it can't. A glyph whose outline fails or draws nothing is left out, and so are the paints inside it. A glyph is asked for once, and every fill that uses it shares the one path.foregroundis the text's color, for the paints and stops that ask for it.The ops are added after whatever
outalready holds. The answer is false, with nothing added, for a glyph the OpenType specification says not to draw: one with no clip box whose graph has a fill that nothing bounds. Otherwise it is true, even if the graph turned out to draw nothing. Paints nested more than 64 deep are left out.What it leaves to you is what
Font::color_scenedoes around it: picking the palette, which the graph already has, falling back to the layers of COLR version 0, and the limit on how many outline points one scene may hold.use daegun::color::{lower, DisplayList, Rgba, SceneOptions, IDENTITY}; use daegun::{GlyphId, Location}; let (glyph, location) = (GlyphId(133), Location::default()); let graph = font.paint_graph(glyph, &location, 0).expect("a COLR v1 glyph"); let mut scene = DisplayList::default(); let drawn = lower( glyph, &graph, IDENTITY, &|g| font.colr_clip_box(g, &location), &mut |g, pen| font.outline(g, &location, pen).is_ok(), Rgba::opaque(0, 0, 0), &mut scene, ); assert!(drawn); // With no transform, the font's own outlines and black text, this is the scene color_scene makes. let same = font.color_scene(glyph, &location, &SceneOptions::DEFAULT)?.expect("a color glyph"); assert_eq!(scene, same);Font::bitmappub fn bitmap(&self, glyph: GlyphId, ppem: u16) -> Option<GlyphBitmap<'_>>A glyph's ready-made image from the font's bitmap strikes, taken from the strike nearest the size you draw at.
Some fonts store glyphs as pictures in place of outlines, as color emoji fonts do. The pictures come in one or more fixed sizes, called strikes, each made for a number of pixels per em. This looks for the glyph in
sbix, thenCBDT, thenEBDT, then Apple'sbdat, and returns the first image it finds as aGlyphBitmap.ppemis the size you are drawing at, in pixels per em. The strike chosen is the smallest one at or above that size, or failing that the largest below it. A strike that lacks the glyph is passed over for the next nearest, so a glyph with an image in any strike gets one.GlyphBitmap::ppemsays which strike answered, which is often not the size you asked for: scale the image by your size over that.daegun does not decode PNGs. An image the font stores as a PNG comes back as those bytes,
BitmapImage::Png, borrowed from the font for your own decoder. An image stored as raw bits, as monochrome and grayscale strikes are, is decoded for you intoBitmapImage::Coverage, one byte per pixel, which allocates.The image's
leftandtopare counted in pixels of the strike, not in font units, so they scale along with the image.Nonemeans no strike holds the glyph, which is the answer for every glyph of a font with no bitmap tables. Ansbiximage in a format other than PNG is passed over as if it were not there, and so is a raw color image of 32 bits a pixel, which daegun does not decode.use daegun::color::BitmapImage; let smile = font.glyph_id('😀').expect("Noto Color Emoji maps it"); let bitmap = font.bitmap(smile, 64).expect("it has an image"); // The image comes from a strike of 109 pixels per em, so at 64 it is drawn smaller. assert_eq!(bitmap.ppem, 109); let scale = 64.0 / f64::from(bitmap.ppem); match &bitmap.image { // PNG bytes lent by the font. Decode them, scale the picture by `scale`, and put its top left // corner bitmap.left * scale right of the glyph's origin and bitmap.top * scale above it. BitmapImage::Png(png) => assert!(png.starts_with(b"\x89PNG")), // One byte of coverage per pixel, rows top to bottom. BitmapImage::Coverage { width, height, pixels } => { assert_eq!(pixels.len(), usize::from(*width) * usize::from(*height)); } _ => {} }Font::color_scenepub fn color_scene( &self, glyph: GlyphId, location: &Location, options: &SceneOptions, ) -> Result<Option<DisplayList>>Turns a color glyph into a scene: fills, clips and layers to draw in order, each fill a path with a color or a gradient.
The call for drawing a color glyph with a renderer of your own. It reads the glyph's
COLRversion 1 paint graph, or else its version 0 layers, and flattens either into aDisplayList. Go throughDisplayList::opsin order and do what eachOpsays. If you want pixels and not a scene,Rasterizer::color_glyphdraws it for you.Everything is in font units, y up. Each glyph outline is in the scene once, however many fills use it, and each op's transform places it, so apply that transform first and your own scale to pixels after.
Ok(None)means the glyph has no color description. Draw its outline withFont::outline, or look for an image withFont::bitmap. In a font that lacks aCOLRtable or aCPALpalette table, every glyph answers this. A version 1 glyph with no clip box whose paints would cover the whole plane is not drawn either, as the OpenType specification asks: its version 0 layers draw if it has any, and otherwise it isNonetoo.Ok(Some(scene))with no ops is a color glyph that paints nothing, so there is nothing to draw.DisplayList::is_emptytells you.optionspicks the palette and the color of the text: seeSceneOptions.locationpicks the instance of a variable font, and&Location::default()is the default instance.A version 0 glyph comes out as one solid
Op::Fillper layer, back to front, leaving out a layer whose glyph has no outline. A version 1 glyph can use every kind of op, and one with a clip box arrives wrapped in a clip to that box. Clips and layers together never nest more than 128 deep, so a renderer can give its stack a fixed size. To keep that bound daegun lowers a paint graph 64 levels deep, so a graph nested deeper loses the paints below that.The only error is
ErrorKind::LimitExceeded, a guard against a font built to exhaust memory. As the scene is made, daegun adds up the points of every outline it holds, each glyph once however many layers use it, along with the work of decoding those glyphs. Past the larger of 1,048,576 and 16 for every byte of the font's outline tables (glyf,CFF,CFF2andVARC), the call fails. A font whose layers are composite glyphs that repeat a component thousands of times can reach it.Each call builds the scene afresh, and nothing is cached. With the
stdfeature a dropped scene of up to 64 KiB leaves its buffers to the next scene made on the same thread, so drawing glyph after glyph allocates little.use daegun::color::{Op, Paint, SceneOptions}; use daegun::{GlyphId, Location}; // Glyph 156 of the COLR version 1 test font, which uses every kind of op. let glyph = GlyphId(156); let Some(scene) = font.color_scene(glyph, &Location::default(), &SceneOptions::DEFAULT)? else { // Not a color glyph: draw font.outline(glyph, ..) instead. return Ok(()); }; for op in scene.ops() { match *op { Op::Fill { path, paint, rule, transform } => { let outline = scene.path(path).expect("a scene's ids are its own"); // Fill `outline`, placed by `transform`, in font units. match paint { Paint::Solid(color) => { /* with one color */ } Paint::Gradient(id) => { /* with scene.gradient(id) */ } _ => {} } } Op::PushClip { shapes } => { /* clip to scene.shapes(shapes) until the matching PopClip */ } Op::PopClip => { /* back to the clip before it */ } Op::PushLayer { opacity, blend } => { /* start a transparent layer and draw into it */ } Op::PopLayer => { /* composite that layer onto the one below */ } _ => {} } }Font::colr_clip_boxpub fn colr_clip_box(&self, glyph: GlyphId, location: &Location) -> Option<Bounds>A
COLRversion 1 glyph's clip box: the rectangle, in font units, that everything the glyph draws stays inside.A font can give a color glyph a clip box so that its extent is known without walking its paints. The scene from
Font::color_sceneis already clipped to it, so you need the box yourself only to size a buffer or a bounding box before you draw.Nonefor a glyph the font gives no box. That is every glyph of a font withoutCOLRversion 1 data, or without aCPALtable beside it.In a variable font the box can change with the location. Each edge moves by the font's delta for it and is then rounded outward to a whole unit, a minimum down and a maximum up, so the box never cuts off what it bounds.
use daegun::{Bounds, GlyphId, Location, Tag}; let clip = font.colr_clip_box(GlyphId(160), &Location::default()); assert_eq!(clip, Some(Bounds { x_min: 250.0, y_min: 250.0, x_max: 750.0, y_max: 750.0 })); // A glyph that is not a color glyph has none. assert_eq!(font.colr_clip_box(GlyphId(1), &Location::default()), None); // The same glyph in the variable build of the font, where the axis CLXI moves the box's left edge. let moved = font.location(&[(Tag::new(b"CLXI"), 100.0)]); let clip = font.colr_clip_box(GlyphId(160), &moved).expect("glyph 160 has a box"); assert_eq!((clip.x_min, clip.x_max), (350.0, 750.0));Font::colr_layerspub fn colr_layers(&self, glyph: GlyphId, palette: u16) -> Option<Vec<ColrLayer>>A
COLRversion 0 glyph's layers, back to front: each one a glyph whose outline is filled with a single color.Version 0 of the
COLRtable describes a color glyph as a stack of ordinary glyphs, each filled with one color of a palette. This returns the stack in drawing order, the first layer at the back, asColrLayers whose colors are already looked up in the palette you name.paletteis aCPALpalette index, and one the font doesn't have reads palette 0. A layer that asks for the color of the text hasforegroundset, and itscoloris opaque black standing in for it.Nonefor a glyph with no version 0 layers. That covers every glyph of a font that lacksCOLRorCPAL, and a glyph described only by a version 1 paint graph, whichFont::paint_graphreads. A layer that names a glyph or a palette entry the font doesn't have is left out of the list, and where that leaves none the answer isNone.To draw,
Font::color_sceneis the easier call: it handles both versions and hands you the outlines too. Use this one to inspect a font, or to draw layers from outlines you already keep.use daegun::color::Rgba; let a = font.glyph_id('A').expect("Bungee Tint has an A"); let layers = font.colr_layers(a, 0).expect("a color glyph"); for layer in &layers { // Fill the outline of layer.glyph with layer.color, over the layers before it. } // Two layers: the letter in red, then a lighter inline over it. 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)); // Palette 1 colors the same two layers white and gray. let pale = font.colr_layers(a, 1).expect("the same glyph"); assert_eq!(pale[0].color, Rgba::opaque(255, 255, 255));Font::paint_graphpub fn paint_graph(&self, glyph: GlyphId, location: &Location, palette: u16) -> Option<PaintGraph>A
COLRversion 1 glyph's paint graph: the tree of paints the font describes it with, read at a location and in a palette.Version 1 of
COLRdescribes a color glyph as a graph of paints: glyph outlines that clip, solid colors and gradients that fill, transforms, layers and composites. This returns it as aPaintGraphto walk fromPaintGraph::root, with its colors looked up in the palette and, in a variable font, every value that varies set for the location.It is the font's own description, for a tool that inspects fonts or a renderer that interprets the paints itself. To draw,
Font::color_scenehas already turned the graph into fills, clips and layers.Nonefor a glyph with no version 1 paint: a version 0 glyph, whichFont::colr_layersreads, or any glyph of a font that lacksCOLRorCPAL. A palette index the font doesn't have reads palette 0.Each call reads the table again and builds a new graph.
Font::visit_paint_graphhands you the same paints without building one.use daegun::color::PaintNode; use daegun::{GlyphId, Location}; let graph = font.paint_graph(GlyphId(8), &Location::default(), 0).expect("a version 1 glyph"); // This glyph is an outline filled with a linear gradient: a Glyph paint with the gradient below it. let root = graph.root(); assert!(matches!(root.node(), PaintNode::Glyph { .. })); let fill = root.children().next().expect("the paint that fills the outline"); assert!(matches!(fill.node(), PaintNode::LinearGradient { .. })); // A glyph with no version 1 paint has no graph. assert!(font.paint_graph(GlyphId(1), &Location::default(), 0).is_none());Font::palette_colorspub fn palette_colors(&self, palette: u16) -> Vec<Rgba>The colors of one palette, in entry order.
This is the list a color picker shows for a palette, and the list CSS's
override-colorsindexes into: itemiis palette entryias the font stores it, the color a layer or paint names by that number. A version 1 paint may scale its alpha. Each is anRgba, sRGB with straight alpha.A palette index the font doesn't have reads palette 0, as drawing does, and so does a palette whose colors run past the table's color records. The list is empty for a font with no
CPALtable, or one whoseCPALdaegun does not read.use daegun::color::Rgba; // Bungee Tint's palettes have two entries, one for each layer of a letter. let colors = font.palette_colors(0); assert_eq!(colors, [Rgba::opaque(201, 9, 0), Rgba::opaque(255, 149, 128)]); assert_eq!(font.palette_colors(1), [Rgba::opaque(255, 255, 255), Rgba::opaque(232, 232, 231)]); // The font has 8 palettes, so index 8 is one past the last and reads palette 0. assert_eq!(font.palette_colors(8), colors);Font::palette_countpub fn palette_count(&self) -> usizeHow many palettes the font has, without building the list
Font::palettesreturns.Palette indexes run from 0 to one less than this. It is 0 for a font with no
CPALtable, or one whoseCPALdaegun does not read.// Bungee Tint comes in eight color schemes. assert_eq!(font.palette_count(), 8); assert_eq!(font.palette_count(), font.palettes().len());Font::palette_entry_labelspub fn palette_entry_labels(&self) -> Vec<Option<NameId>>The name ID of each palette entry, so a color picker can label the colors a palette sets.
A font can say what each palette entry is for, and a picker shows that beside the swatch. The list has one item per palette entry, and it serves every palette, as they all have the same entries. An item is the ID of a name to look up with
Font::name, orNonefor an entry the font leaves unnamed.The list is empty where the font has no entry labels at all: a version 0
CPAL, which has no room for them, a version 1CPALthat leaves them out, or noCPALthat daegun reads. A font that has the labels but sets none gives aNonefor every entry.use daegun::Location; let labels = font.palette_entry_labels(); for (entry, label) in labels.iter().enumerate() { let name = label.and_then(|id| font.name(id, &Location::default())); // Show `name` beside the swatch for palette entry `entry`, or its number where there is none. } // Bungee Tint labels none of its entries, so the list is empty. assert!(labels.is_empty());Font::palettespub fn palettes(&self) -> Vec<Palette>The font's color palettes, one
Paletteeach, as a color picker lists them.CPALis the font's palette table. It holds one or more palettes, each a list of the same number of colors, and color glyphs name their colors by position in that list. Choosing another palette recolors every color glyph at once.Each
Palettegives the index to pass toSceneOptions::with_palette, whether the font marks the palette as fit for light or for dark backgrounds, and the ID of its name where it has one. The colors themselves come fromFont::palette_colors.The list is empty for a font without a
CPALtable, and for one whoseCPALis too short to hold its header or states a version past 1.let palettes = font.palettes(); for palette in &palettes { // Offer palette.index as a choice, and pass the one chosen to SceneOptions::with_palette. } // This test font has three: a default, one marked for dark backgrounds and one for light. assert_eq!(palettes.len(), 3); assert!(palettes[1].dark_safe && palettes[2].light_safe);Font::visit_paint_graphpub fn visit_paint_graph( &self, glyph: GlyphId, location: &Location, palette: u16, visitor: &mut (impl PaintVisitor + ?Sized), ) -> boolWalks a
COLRversion 1 glyph's paints, calling your visitor for each one, without building a graph.These are the paints
Font::paint_graphreturns, delivered as calls:PaintVisitor::enterfor a paint, then the same for each of its children, thenPaintVisitor::leave. A composite's source comes before its backdrop.Returns false, having called nothing, for a glyph with no version 1 paint. Otherwise it walks the graph and returns true.
Use it to interpret the paints as they come, or to measure or search them, where a graph you would throw away is wasted work. A gradient's stops are lent for the length of the
entercall only, so copy the ones you keep.use daegun::color::{PaintNode, PaintVisitor}; use daegun::{GlyphId, Location}; // Counts a glyph's paints, and how deep they nest. #[derive(Default)] struct Depth { paints: usize, open: usize, deepest: usize, } impl PaintVisitor for Depth { fn enter(&mut self, _node: PaintNode<'_>) { self.paints += 1; self.open += 1; self.deepest = self.deepest.max(self.open); } fn leave(&mut self) { self.open -= 1; } } let mut depth = Depth::default(); let found = font.visit_paint_graph(GlyphId(156), &Location::default(), 0, &mut depth); // Glyph 156 is 7 paints, nested 5 deep, and every enter got its leave. assert!(found); assert_eq!((depth.paints, depth.deepest, depth.open), (7, 5, 0)); // A glyph with no paint graph answers false and calls nothing. assert!(!font.visit_paint_graph(GlyphId(1), &Location::default(), 0, &mut depth)); assert_eq!(depth.paints, 7);
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.
Font::math_constantspub fn math_constants(&self, location: &Location) -> Option<MathConstants>The font's math constants at a location: the distances and percentages that place scripts, fractions, limits, bars and roots in a formula.
Returns a
MathConstants, one field for each constant of the OpenTypeMATHtable. Distances are in font units, so a distance in pixels isvalue * px / f64::from(font.units_per_em()). A height is measured up from the baseline, and a shift or a drop downward is a positive number. The type says what each field is for.locationpicks the instance of a variable font.&Location::default()is the default instance, and works for any font. Away from the default, each distance has the variation delta the font gives for that location added to it. The sum is not rounded, so it may carry a fraction.Nonemeans the font has no constants to give: it has noMATHtable, the table holds no constants, or the table ends before the last of them. A text font such as Inter answersNone.Nothing is cached. Each call reads all 56 values from the table, so ask once for a formula and keep the struct, which is
Copy.use daegun::Location; let constants = font.math_constants(&Location::default()).ok_or("the font has no MATH constants")?; // A fraction bar at 20 px: how thick to draw it, and how far above the baseline its middle goes. let scale = 20.0 / f64::from(font.units_per_em()); let thickness = constants.fraction_rule_thickness * scale; let height = constants.axis_height * scale; // STIX Two Math gives 68 and 258 font units, so a bar 1.36 px thick, 5.16 px up.Font::math_glyph_variantspub fn math_glyph_variants( &self, glyph: GlyphId, location: &Location, orientation: Orientation, ) -> Option<MathGlyphConstruction>How a glyph stretches in one direction: its ready-made sizes, and the parts to build it at any size.
A formula needs glyphs that grow: a parenthesis as tall as the fraction inside it, a brace as wide as the terms under it. A math font offers two ways to get one. A variant is a ready-made drawing of the glyph at one size, a glyph in its own right. An assembly is a set of parts, such as the two hooks of a parenthesis and a straight piece that repeats, joined to reach any size. The
MathGlyphConstructionthat comes back holds both.orientationis the direction to stretch in:Orientation::Verticalfor what grows taller, such as delimiters, roots and integrals, andOrientation::Horizontalfor what grows wider, such as arrows, braces over a formula and wide accents. The font lists the two directions separately.To use the result, go through
variantsin order and take the first whoseadvancecovers the size you need. They come as the font lists them, which daegun does not sort: STIX Two Math lists the glyph itself first, then each larger size. If none is large enough and there is anassembly, build the glyph from its parts:GlyphAssemblysays how.Nonemeans the font does not stretch this glyph in that direction. That is the answer for every glyph of a font with noMATHtable.Sizes are in font units, and they are the same at every
location. The one value that follows the location is the assembly'sitalics_correction. Each call reads the table and builds new lists, so keep the result if you need it again.use daegun::{Location, Orientation}; let at = Location::default(); let paren = font.glyph_id('(').ok_or("no parenthesis")?; let stretch = font.math_glyph_variants(paren, &at, Orientation::Vertical).ok_or("it does not stretch")?; // A parenthesis for a formula 2000 units tall: the first ready-made size that covers it. match stretch.variants.iter().find(|variant| variant.advance >= 2000.0) { Some(variant) => { /* draw variant.glyph in place of the parenthesis */ } None => { /* taller than every size: build it from stretch.assembly */ } } // STIX Two Math draws 13 sizes, from 933 to 3821 units tall, and the sixth, at 2145, is the pick. // A parenthesis only grows taller, so the other direction has nothing. assert!(font.math_glyph_variants(paren, &at, Orientation::Horizontal).is_none());Font::math_is_extended_shapepub fn math_is_extended_shape(&self, glyph: GlyphId) -> boolWhether the font marks a glyph as an extended shape: a glyph drawn tall to match the formula beside it, such as a large parenthesis, where scripts are placed by the height of what is drawn and not at the usual shift.
A superscript on an ordinary letter is raised by a fixed amount,
superscript_shift_upof theMathConstants. Beside a tall parenthesis that would leave it stranded halfway up. Where the glyph is an extended shape, a layout works from the ink box instead: the box around everything drawn in the sub-expression the glyph belongs to, such as a fraction and its parentheses. The baseline of a superscript goes no more thansuperscript_baseline_drop_maxbelow the top of that box, and the baseline of a subscript at leastsubscript_baseline_drop_minbelow its bottom.False for a glyph the font does not mark, and for every glyph of a font with no
MATHtable. The mark belongs to the glyph and is the same at every location, so the call takes none.use daegun::{Location, Orientation}; let paren = font.glyph_id('(').ok_or("no parenthesis")?; let letter = font.glyph_id('A').ok_or("no A")?; // STIX Two Math marks its parenthesis, and not a letter. assert!(font.math_is_extended_shape(paren)); assert!(!font.math_is_extended_shape(letter)); // Every larger size of the parenthesis is marked too, so a script on any of them is placed alike. let stretch = font .math_glyph_variants(paren, &Location::default(), Orientation::Vertical) .ok_or("it does not stretch")?; assert!(stretch.variants.iter().all(|variant| font.math_is_extended_shape(variant.glyph)));Font::math_italics_correctionpub fn math_italics_correction(&self, glyph: GlyphId, location: &Location) -> Option<f64>A glyph's italic correction at a location, in font units: the room to leave after a slanted glyph so that what follows clears its overhanging top.
A slanted glyph leans past the end of its advance. The italic correction is by how much, and a math layout uses it in three places. Where a slanted glyph is followed by an upright one, such as an operator or a delimiter, the correction is added to its advance. A superscript on the glyph is set further right than a subscript by the correction, so that both follow the slant. And on a big operator such as an integral, the upper limit moves right by half the correction and the lower limit left by half.
Nonemeans the font gives this glyph no correction, as for an upright glyph, or for any glyph of a font with noMATHtable. Treat it as 0.locationpicks the instance of a variable font. Away from the default, the correction has its variation delta added and is not rounded.use daegun::Location; let at = Location::default(); let integral = font.glyph_id('∫').ok_or("no integral sign")?; let correction = font.math_italics_correction(integral, &at).unwrap_or(0.0); // The integral sign leans to the right, and STIX Two Math gives it a correction of 230 units. // Its upper limit goes 115 units right of the middle, and its lower limit 115 units left. assert_eq!(correction, 230.0); // An upright letter has none. let letter = font.glyph_id('A').ok_or("no A")?; assert_eq!(font.math_italics_correction(letter, &at), None);Font::math_kernpub fn math_kern(&self, glyph: GlyphId, location: &Location, corner: MathKernCorner, height: f64) -> Result<f64>The kern at one corner of a glyph for a script that meets it at a given height, in font units.
Ordinary kerning moves two glyphs along a line. A subscript or superscript sits diagonally from its base, so how close it may come depends on how high it sits: a subscript can slide in under the arm of a V, and one set higher cannot. A math font therefore cuts each corner of a glyph into bands of height and gives a kern for each band.
cornerpicks the corner, aMathKernCorner.heightis where the other glyph meets that corner: a y position in font units, measured up from this glyph's own baseline, so it is negative below the baseline. The answer is the kern of the band the height falls in. A negative kern moves the script closer.The font lists the heights that divide the bands. A height below the first takes the first kern, one at or above the last takes the last kern, and a height equal to a listed one belongs to the band above it. The comparison is exact, with nothing rounded. An infinite height is fine:
f64::NEG_INFINITYtakes the first kern andf64::INFINITYthe last.To kern a base and its script, add two answers: the base at the corner the script sits at, and the script at its own facing corner. For a superscript after its base those are
MathKernCorner::TopRightof the base andMathKernCorner::BottomLeftof the superscript, each asked at the same level, measured from that glyph's own baseline. The OpenType specification takes the sum at two levels, the bottom of the superscript and the top of the base, and kerns by the smaller. For a subscript the corners areMathKernCorner::BottomRightof the base andMathKernCorner::TopLeftof the subscript, and the levels are the top of the subscript and the bottom of the base.Where the font has no kern the answer is
Ok(0.0): a font with noMATHtable, a glyph it lists no kerns for, or a corner it leaves out. The one error is aheightthat is not a number (NaN), which isErrorKind::InvalidArgument.locationpicks the instance of a variable font. Away from the default, the dividing heights and the kerns each have their variation delta added, so a band may begin at another height there.use daegun::math::MathKernCorner; use daegun::{ErrorKind, Location}; let at = Location::default(); let a = font.glyph_id('A').ok_or("no A")?; let kern = |height: f64| font.math_kern(a, &at, MathKernCorner::TopRight, height); // STIX Two Math divides the top right corner of its A at heights 252 and 352. A superscript // that meets it below 252 stays put. Higher up, where the A slopes away, it moves in. assert_eq!(kern(100.0)?, 0.0); assert_eq!(kern(300.0)?, -18.0); assert_eq!(kern(400.0)?, -66.0); // An infinite height takes the last kern. A height that is not a number is the one error. assert_eq!(kern(f64::INFINITY)?, -66.0); assert_eq!(kern(f64::NAN).map_err(|error| error.kind()), Err(ErrorKind::InvalidArgument));Font::math_min_connector_overlappub fn math_min_connector_overlap(&self) -> Option<f64>The least overlap the font allows where two parts of an assembled glyph join, in font units.
When a glyph is built from the parts of a
GlyphAssembly, each part is laid a little over the one before it, so that their strokes merge with no seam. This is the smallest overlap the font allows at such a join. Pulling the parts apart, down to this overlap, is how a build reaches the sizes between one count of repeated pieces and the next.It is one number for the whole font: the same for every glyph, in both directions and at every location, so the call takes no arguments.
Nonemeans the font has noMATHtable, or aMATHtable with nothing in it about stretching glyphs.use daegun::{Location, Orientation}; let overlap = font.math_min_connector_overlap().ok_or("the font has no MATH table")?; // STIX Two Math wants the parts of a glyph to overlap by at least 100 units. assert_eq!(overlap, 100.0); // The two hooks of its parenthesis are 1273 units each, so joined with that overlap they make // a glyph of 2446 units. Anything taller takes a straight piece between them. let paren = font.glyph_id('(').ok_or("no parenthesis")?; let parts = font .math_glyph_variants(paren, &Location::default(), Orientation::Vertical) .and_then(|stretch| stretch.assembly) .ok_or("no parts to build it from")? .parts; let hooks: f64 = parts.iter().filter(|part| !part.extender).map(|part| part.full_advance).sum(); assert_eq!(hooks - overlap, 2446.0);Font::math_top_accent_attachmentpub fn math_top_accent_attachment(&self, glyph: GlyphId, location: &Location) -> f64Where an accent centers over a glyph at a location: an x position in font units from the glyph's origin.
To set an accent such as a hat or a tilde over a base in a formula, line up two attachment points: ask for the base's and for the accent's own, and move the accent right by the difference. The point is not always the middle of the glyph. Over a slanted letter the accent belongs further right, above where the top of the letter is.
The answer is the font's own value where its
MATHtable gives the glyph one. Otherwise it is half the glyph's horizontal advance at that location, the middle of the glyph. So there is always an answer, for a font with noMATHtable too. A glyph id the font does not have answers 0, as its advance is 0.locationpicks the instance of a variable font. The value from the table has its variation delta added, unrounded, and the fallback uses the advance at that location.use daegun::Location; let at = Location::default(); let base = font.glyph_id('A').ok_or("no A")?; let hat = font.glyph_id('\u{0302}').ok_or("no combining circumflex")?; // Put a circumflex over an A: move the accent so that its attachment point lands on the base's. let shift = font.math_top_accent_attachment(base, &at) - font.math_top_accent_attachment(hat, &at); // STIX Two Math gives 360 for the A and -230 for the accent, which is drawn left of its origin. // So the accent is drawn 590 units right of the A's origin. assert_eq!(shift, 590.0);
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.
Font::base_extentspub fn base_extents( &self, script: Tag, location: &Location, orientation: Orientation, language_system: Option<Tag>, feature: Option<Tag>, ) -> Option<Extents>How far a script's glyphs reach to either side of the line, from the font's
BASEtable.Besides baselines,
BASEcan record the lowest and highest points a script's glyphs reach, so a layout can give lines of that script the room they need. The answer is anExtents. Itsminandmaxare y values forOrientation::Horizontaland x values forOrientation::Vertical, in font units atlocation.scriptis an OpenType script tag, and a script with no record takes those ofDFLT, as inFont::base_script.language_systemis an OpenType language system tag such asTRK, the kindFont::language_system_tagslists, not a BCP 47 language. With one the script has extents for, you get those. WithNone, or one it has no record for, you get the script's default extents.featureis a feature tag. Where the extents chosen hold a record for that feature, as for one that swaps in taller glyphs, its values replace both sides, and a side the feature's record leaves out comes backNone, not the value it replaced. ForNone, or a feature with no record, they stand.Nonemeans the font states no extents here: it has noBASEtable, the table holds nothing for that orientation, neither the script norDFLThas a record there, or the record found has no extents. A font can give a script baselines and no extents, as Source Han Sans does, and thenFont::base_scriptanswers while this call does not. In aSome, either side may still beNone, where the font states only the other.use daegun::{Location, Orientation, Tag}; let at = Location::default(); match font.base_extents(Tag::new(b"hani"), &at, Orientation::Horizontal, None, None) { Some(extents) => { // extents.min and extents.max: the lowest and highest y, each an Option, in font units. } None => { // No extents for the script: go by the font's own line metrics. let (bottom, top) = (font.descender(&at), font.ascender(&at)); } } // Source Han Sans gives Han baselines and no extents, so this takes the None arm.Font::base_scriptpub fn base_script(&self, script: Tag, location: &Location, orientation: Orientation) -> Option<BaseScript>A script's baselines from the font's
BASEtable: where each named baseline lies, and which one the script's glyphs sit on.Scripts sit on different lines. Latin letters stand on the roman baseline, Chinese and Japanese characters fill a box whose bottom edge lies below it, and Devanagari hangs from a line near the top. A font's
BASEtable records where those lines are, so that text mixing scripts or sizes can be lined up on one of them.A baseline is named by a four-letter tag:
romnfor the roman baseline,ideoandidtpfor the bottom and top of the ideographic em box,icfbandicftfor the bottom and top of the ideographic character face,hangfor the hanging baseline andmathfor the line math is centered on. TheBaseScriptthat comes back maps each tag the font gives to its position, and names the baseline the script's own glyphs sit on.scriptis an OpenType script tag such aslatn,haniordeva, the kindFont::script_tagslists.orientationpicks the direction of the line: positions are y values forOrientation::Horizontaland x values forOrientation::Vertical. They are in font units atlocation, and in a variable font whoseBASEvaries they move with it.A script the table has no record for gets the baselines of
DFLT, the default script, where the table has that.Nonemeans there is nothing to give: the font has noBASEtable, the table holds nothing for that orientation, neither the script norDFLThas a record there, or the record found has no baseline values. A record whose values list no baseline gives aBaseScriptwith an emptybaselinesmap. Plenty of fonts have noBASEat all. Inter is one.use daegun::{Location, Orientation, Tag}; let at = Location::default(); let han = font .base_script(Tag::new(b"hani"), &at, Orientation::Horizontal) .expect("Source Han Sans has a BASE table"); // Han characters sit on the ideographic baseline, which this font puts 120 units below the // roman one. assert_eq!(han.default_baseline, Some(Tag::new(b"ideo"))); assert_eq!(han.baselines[&Tag::new(b"ideo")], -120.0); assert_eq!(han.baselines[&Tag::new(b"romn")], 0.0); // Latin letters in the same font sit on the roman baseline. let latin = font.base_script(Tag::new(b"latn"), &at, Orientation::Horizontal).expect("as above"); assert_eq!(latin.default_baseline, Some(Tag::new(b"romn")));Font::feature_tagspub fn feature_tags(&self, script: Option<Tag>, language_system: Option<Tag>) -> Vec<Tag>The OpenType features the font offers a script and language system.
A feature is a named set of rules in
GSUBorGPOS, with a four-letter tag:kernfor kerning,ligafor ligatures,smcpfor small caps,ss01for the first stylistic set. This lists the features both tables hold for one script and language system, sorted and each once. Use it to build a feature picker, or to check that a feature is there before you turn it on with aFeature.scriptis an OpenType script tag, one thatFont::script_tagslists. A script the font does not have gives an empty list.Nonestands for the script shaping falls back to when the font has no rules for the text's own script: the first the table has ofDFLT,dfltandlatn. Each of the two tables is read by itself, so each falls back on its own.language_systemis an OpenType language system tag such asROM, asFont::language_system_tagslists them, not a BCP 47 language.None, or a tag the script has no record for, gives the features of the script's default language system. Where a font tags a recorddflt, that record is taken as the default.The list holds the features that are on by default and the optional ones alike, the language system's required feature among them, and does not say which are which. It is empty for a font with neither table.
use daegun::Tag; let latin = Tag::new(b"latn"); // What Inter offers Latin text in its default language system. let features = font.feature_tags(Some(latin), None); assert!(features.contains(&Tag::new(b"kern")) && features.contains(&Tag::new(b"tnum"))); // It has no small caps. assert!(!features.contains(&Tag::new(b"smcp"))); // Romanian has one feature more: locl, the forms a language prefers. let romanian = font.feature_tags(Some(latin), Some(Tag::new(b"ROM "))); assert_eq!(romanian.len(), features.len() + 1); assert!(romanian.contains(&Tag::new(b"locl")) && !features.contains(&Tag::new(b"locl")));Font::glyph_closurepub fn glyph_closure( &self, glyphs: impl IntoIterator<Item: Borrow<GlyphId>>, location: &Location, ) -> Result<Vec<GlyphId>>The glyphs a subset of these glyphs would hold: the ones you name and every glyph they reach.
The ids come back sorted from low to high, each once, in the source font's numbering. It is the set
Font::subsetkeeps, found without writing a font. Use it to see what a subset will hold, or to gather glyphs for a glyph atlas or a subsetter of your own.One glyph reaches another when drawing or shaping can lead from the first to the second: the glyphs the font's substitutions (
GSUB) can turn it into under any feature, the size variants and assembly partsMATHgives it, the layers of a color glyph, the parts a composite glyph is built from, and beyond those the glyphs Apple'smorxcan turn it into, the base and accent of a CFFseacglyph, the glyphs a bitmap glyph copies or is built from (sbix,EBDT), the parts of aVARCglyph, and the glyphsbslnandfmtxname.Substitutions are followed from the glyphs you name until nothing new comes. Then the
MATHvariants, color layers and parts of all of those are added, with their own parts and layers in turn, but a glyph that comes in that way is not run throughGSUBagain. So the é below brings in its e as a part, but not the e's superscript and subscript forms, which asking for the e itself would.Glyph 0,
.notdef, is always in the list. An id past the font's last glyph is left out, and a repeat counts once, so the list is never longer thanFont::glyph_count. Glyphs come by value or by reference, asFont::subsettakes them, andlocationis the one you would subset at.The errors are those of
Font::subset, less the ones that come from writing the font:ErrorKind::Missingfor aglyfwith noloca,ErrorKind::Malformedfor amaxpthat counts no glyphs andErrorKind::LimitExceededfor substitutions that lead past the work daegun allows. For a variable font, or one with CFF2 outlines, the call first builds the font atlocationas a subset does, so the instancer's failures come here too, such asErrorKind::Missingfor a variable font with nohmtx. A font may give a closure and still fail to subset.use daegun::{GlyphId, Location}; let e_acute = font.glyph_id('é').expect("Inter has an é"); let closure = font.glyph_closure([e_acute], &Location::default())?; // Inter builds its é from an e and an acute accent, so a subset of the one glyph holds four: // .notdef, the e, the é and the accent, in the order of their ids. assert_eq!(closure.len(), 4); assert_eq!(closure[0], GlyphId::NOTDEF); assert!(closure.contains(&e_acute) && closure.contains(&font.glyph_id('e').expect("an e")));Font::has_glyph_free_basepub fn has_glyph_free_base(&self) -> boolWhether the font has a
BASEtable that names no glyph, so the table stays valid when glyphs are renumbered.A coordinate in
BASEis usually a plain number, but the format lets one be tied to a contour point of a glyph, named by its id. A table with such a coordinate goes wrong once the glyphs are renumbered, as a subset renumbers them. This is true when the font has aBASEtable and every coordinate in it, baselines and extents alike, is a plain number, or a number with a device or variation adjustment. It is false for a font with noBASEtable, and for one with a coordinate in a format daegun doesn't know or a table too tangled to read within its budget.daegun's own subsets go by it. A subset of a font with TrueType outlines carries
BASEover only when this is true, and a CFF font whoseBASEnames glyphs is subset with its glyph ids left in place. Ask it yourself before copyingBASEinto a font whose glyphs you have renumbered.use daegun::Tag; if font.has_glyph_free_base() { // BASE can go as it is into a font whose glyphs were renumbered. let base = font.table(Tag::new(b"BASE")).expect("true only for a font with BASE"); } // True for Source Han Sans. False for Inter, which has no BASE table.Font::language_system_tagspub fn language_system_tags(&self, script: Tag) -> Vec<Tag>The OpenType language system tags the font's layout tables have for one script.
Within a script a font can keep different rules for different languages. Turkish tells a dotted i from a dotless one, so an fi ligature that swallows the dot must not form. Serbian italics use other letter shapes than Russian ones. Each such set of rules is a language system, and this lists the ones
GSUBandGPOShave forscript, sorted and each once.An OpenType language system tag is not a BCP 47 language tag. BCP 47 is what the web and operating systems write:
tr,ro,sr-Latn. OpenType has its own list of tags in capitals, most of them three letters and a space:TRKfor Turkish,ROMfor Romanian,SRBfor Serbian.ShapeOptions::with_languagetakes the BCP 47 form and finds the font's language system for you. This call andFont::feature_tagsdeal in the OpenType tags as the font stores them, the space included, so writeTag::new(b"TRK ").A script's default language system, the one used when no language is asked for or the language has no rules of its own, has no tag and is not in the list. A font that also tags a record
dfltlists that tag, and that record serves as the default. So an empty list means the script has its default alone, or that the font has no such script.scriptmust be one the font lists: a script it doesn't have gives an empty list, with no falling back toDFLT.use daegun::Tag; let languages = font.language_system_tags(Tag::new(b"latn")); // Inter keeps Latin rules of their own for Catalan, Moldavian and Romanian. assert_eq!(languages, [Tag::new(b"CAT "), Tag::new(b"MOL "), Tag::new(b"ROM ")]); // Its Cyrillic has the default language system and no other. assert!(font.language_system_tags(Tag::new(b"cyrl")).is_empty());Font::script_tagspub fn script_tags(&self) -> Vec<Tag>The OpenType script tags the font's layout tables have rules for.
A font's substitution table
GSUBand its positioning tableGPOSgroup their rules by script, each named by an OpenType script tag:latnfor Latin,arabfor Arabic,devaanddev2for the older and newer ways of shaping Devanagari,DFLTfor rules that apply whatever the script. This reads both tables and lists their scripts together, sorted and each once. Tags sort by their bytes, soDFLTcomes before the lowercase tags.You don't need these to shape text:
Font::shapepicks the script from the text. They are for showing what a font supports, and for the calls that take a script tag:Font::language_system_tags,Font::feature_tags,Font::base_scriptandShapeOptions::with_script.The list is empty for a font with neither table, such as one shaped by Apple's
morx, and a table too damaged for shaping to use adds nothing. A script in the list means the font has rules for it, not that it has glyphs for its characters:Font::has_glyphanswers that.let scripts = font.script_tags(); // Inter has rules for four scripts. let names: Vec<String> = scripts.iter().map(|tag| tag.to_string()).collect(); assert_eq!(names, ["DFLT", "cyrl", "grek", "latn"]);Font::subsetpub fn subset(&self, glyphs: impl IntoIterator<Item: Borrow<GlyphId>>, location: &Location) -> Result<Subset>Builds a smaller font file that holds the glyphs you name and every glyph they reach, pinned to one location.
For when you already hold glyph ids.
Font::subset_texttakes the text itself, and is the one to use for a web font. The glyphs come by value or by reference, so a slice, an array, aVecor a set ofGlyphIdgoes in as it is. You get aSubset:Subset::fontis the bytes of a whole font file, andSubset::renumberedsays where each glyph went.What it keeps. The glyphs you pass and every glyph they reach: every glyph the font's substitutions (
GSUB) can turn them into under any feature of any script, on by default or not, the size variants and assembly parts aMATHtable gives them, the layers of a color glyph and the parts a composite glyph is built from, and also the glyphs Apple'smorxcan turn them into, the base and accent of a CFFseacglyph, the glyphs a bitmap glyph copies or is built from, and the parts of aVARCglyph.Font::glyph_closurereturns the same set without building the font, and says how far each step reaches. Glyph 0,.notdef, is always kept, so an empty list gives.notdefand whatever it reaches, in most fonts.notdefalone. An id past the font's last glyph is ignored, and a repeated one counts once.Pinned to a location. The subset is a static font. A variable font's outlines, advances and kerning are worked out at
locationand its variation tables are left out, so pass the location you will draw at. A font that is not variable gives the same subset at any location.Its tables. Those that name glyphs are rewritten for the glyphs kept, those that name none, such as
cvt,fpgm,prepandgasp, are copied as they are, and the variation tables andDSIG, which signs the source's bytes, are left out. A font with TrueType outlines also loses every table daegun doesn't know,SVGcolor glyphs among them. A font with CFF or CFF2 outlines keeps such tables as they are.Its cmap. The subset's
cmap, the map from characters to glyphs, keeps every character the source maps to a glyph the subset keeps. That includes the characters of glyphs the closure brought in: asking for the glyph ofain Inter also keepsª, whose glyph a feature reaches from it. Variation sequences go the same way: each one whose glyph the subset keeps stays, and one that takes its base's default glyph stays while the base is mapped.Renumbering. In a font with TrueType outlines the kept glyphs are packed together: they stay in their order and take the ids 0, 1, 2 and so on, so a glyph's id in the subset is rarely its id in the source. A font with CFF or CFF2 outlines is left in place by this call: each kept glyph keeps its id, the dropped ones are emptied, and the glyph count stays what it was. That file is larger than the one
Font::subset_textmakes, which packs CFF glyphs too.Subset::renumberedis right in both cases.Errors.
ErrorKind::Missing: the font lacks a table the subsetter needs, such as aglyfwith noloca, or a variable font with nohmtx.ErrorKind::Malformed: a table does not hold together, such as amaxpthat counts no glyphs, or aCFFtable whose glyph count differs from the one inmaxp.ErrorKind::Unsupported: a table is in a form the subsetter can't write, such as a CFF charset of an unknown format.ErrorKind::LimitExceeded: the font asks for more work than daegun allows, as a hostile one does with glyph data that overlaps so the same bytes would be copied again and again, or with substitutions that keep reaching more glyphs. A variable font goes through the instancer first, at the default location too, and its failures come back as these kinds.Each call builds the file anew, and nothing of the result is cached. The font does keep what it read at
location, such as a variable font's instance there, so a later subset or glyph closure at that location is faster.use daegun::{Font, Location}; // The glyphs of "Wave", one per character. let glyphs: Vec<_> = font.glyph_ids("Wave").flatten().collect(); let subset = font.subset(&glyphs, &Location::default())?; // subset.font is a font file of 4,192 bytes, where Inter is 879,708. let small = Font::from_bytes(&subset.font)?; // It holds 17 glyphs: the four asked for, .notdef, and the forms Inter's features reach from them. assert_eq!(small.glyph_count(), 17); // The W was glyph 459 in Inter. In the subset it is glyph 1, and the subset's cmap still finds it. let w = subset.renumbered(glyphs[0]).expect("a glyph asked for is kept"); assert_eq!(small.glyph_id('W'), Some(w));Font::subset_textpub fn subset_text(&self, text: &str, location: &Location) -> Result<Subset>Builds a smaller font file that can draw one piece of text: the glyphs its characters map to and every glyph those reach, pinned to one location.
The call for a web font or an embedded one. Pass the text a page shows and get back a font file that holds what the text needs and little else. It looks up the glyphs of the characters and then keeps what
Font::subsetwould keep for them, so ligatures, the joined forms of Arabic, accents built from parts and color layers all survive, and the subset shapes the text as the source font does.The characters it looks up are the text's own and the ones shaping can turn them into or draw them with, such as the parts a letter breaks into, the single character a letter and its accent make together, a Hangul syllable its jamo make, the halves Thai's SARA AM splits into, a bracket's mirror image, the vertical forms of punctuation, the dotted circle that carries a stray mark, the space a joiner or a missing space is drawn with, the digits a figure space takes its width from, the hyphen a non-breaking hyphen falls back to, and, in a font with no Arabic rules of its own, the presentation forms Arabic shaping falls back to. A variation sequence in the text keeps the glyph the font gives it.
So a character the font has no glyph for can still add glyphs: a letter the font lacks adds the parts it breaks into, and a joiner or a variation selector the font lacks adds the space glyph shaping draws it with. Text that maps to nothing gives
.notdefand whatever it reaches, in most fonts.notdefalone.Its cmap holds those characters and no others, where
Font::subsetkeeps every character of every kept glyph. A glyph the closure brought in, such as a ligature or an alternate, is in the font but has no character of its own in the map.Renumbering. The kept glyphs are packed together as
Font::subsetpacks them, and here a font with CFF or CFF2 outlines is packed too, so the glyph count falls to what is kept. The exception is a CFF or CFF2 font that carries a table daegun has no way to renumber, such as aBASEthat names glyphs or a table it doesn't know: that font keeps its glyph ids in place.Subset::renumberedis right in both cases.The subset is pinned to
locationasFont::subsetpins it.The errors are those of
Font::subset, and one more:ErrorKind::Missingfor a font with nocmaptable, which has no characters to look up.use daegun::shape::ShapeOptions; use daegun::{Font, Location}; let text = "Type is the voice of the page."; let subset = font.subset_text(text, &Location::default())?; // Inter is 879,708 bytes. subset.font is 9,824, ready for std::fs::write. let small = Font::from_bytes(&subset.font)?; // Its cmap maps the 16 different characters of the text and no others. assert_eq!(small.coverage().count(), 16); assert!(small.has_glyph('T') && !small.has_glyph('W')); // The subset sets the text exactly as Inter does. let source = font.shape(text, &Location::default(), &ShapeOptions::DEFAULT); let shaped = small.shape(text, &Location::default(), &ShapeOptions::DEFAULT); assert_eq!(source.advances, shaped.advances);tables::Subset::renumberedpub fn renumbered(&self, old: GlyphId) -> Option<GlyphId>The id a glyph of the source font has in the subset, or
Nonewhere the subset dropped it.A subset packs the glyphs it keeps, so their ids change. The kept glyphs stay in their order and take the ids 0, 1, 2 and so on: a kept glyph's new id is the number of kept glyphs with a lower id. Glyph 0,
.notdef, is always kept and stays glyph 0.Two kinds of subset are not packed:
Font::subsetof a font with CFF or CFF2 outlines, andFont::subset_textof such a font when it carries a table daegun can't renumber, such as aBASEthat names glyphs or a table it doesn't know. There a kept glyph answers its own id. In every subset a dropped glyph answersNone, and so does an id the source never had.Use it to carry glyph ids from the source into the subset: the glyphs of a run shaped with the source font, a glyph you cached, a table of your own keyed by glyph.
use daegun::shape::ShapeOptions; use daegun::{Font, GlyphId, Location}; let at = Location::default(); let subset = font.subset_text("Wave", &at)?; // Shaped with Inter, "Wave" is glyphs 459, 507, 980 and 614. In the subset they are 1, 2, 5 and 4. let run = font.shape("Wave", &at, &ShapeOptions::DEFAULT); let moved: Vec<_> = run.glyphs.iter().map(|&glyph| subset.renumbered(glyph)).collect(); assert_eq!(moved, [Some(GlyphId(1)), Some(GlyphId(2)), Some(GlyphId(5)), Some(GlyphId(4))]); // Those are the ids the subset itself shapes the text to. let small = Font::from_bytes(&subset.font)?; let shaped = small.shape("Wave", &at, &ShapeOptions::DEFAULT); assert!(moved.iter().copied().eq(shaped.glyphs.iter().map(|&glyph| Some(glyph)))); // A glyph the text has no use for was dropped. let x = font.glyph_id('x').expect("Inter has an x"); assert_eq!(subset.renumbered(x), None);
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.
daegun::raw::build_fontpub fn build_font<'a, V: AsRef<[u8]> + 'a>( tables: impl IntoIterator<Item = (&'a Tag, &'a V)>, ) -> Result<alloc::vec::Vec<u8>>Builds a font file from tables: the header and directory, each table padded and checksummed, and the checksum adjustment in
head.The call a tool makes once it has changed the tables of a font. Give it pairs of a tag and the bytes of that table, in any order, and it returns the bytes of a font file. A map passed by reference works as it is: a
BTreeMap<Tag, Vec<u8>>, one of borrowed slices filled fromFont::table, which copies nothing until the file is written, or the mapFont::instance_tablesreturns.The directory is written in tag order, as the specification sorts it, and the tables follow in that same order, each padded with zeros to a multiple of four bytes. Of a tag given twice, the last is kept. Every table gets its checksum, and a
headtable of 12 bytes or more gets itscheckSumAdjustmentset in the file, so the whole file sums to 0xB1B0AFBA as the specification asks. The bytes you passed are left as they were.The file states its kind by what it holds:
OTTOwhere a table is taggedCFForCFF2, and otherwise 0x00010000, the TrueType version. So tables with both kinds of outline make anOTTOfile, whichFont::from_bytesreads by its CFF table, leavingglyfandlocaaside. A font rebuilt from its own tables need not match the file it came from byte for byte, since that file may lay its tables out in another order.Nothing checks that the tables make a working font. The call writes what it is given, and
Font::from_bytesis where a missing or broken table is refused. No tables at all giveOkwith no bytes, since no tables make no font.An error is of kind
ErrorKind::InvalidArgument, for what a font's directory has no way to state: more than 65,535 tables, a table of 4 GiB or more, or one that would start 4 GiB or more into the file.use daegun::raw::bytes::write_u16_be; use daegun::{Font, Location, Tag}; use std::collections::BTreeMap; // An edited copy of OS/2: usWeightClass, the 16-bit field at byte 4, set to 700. let mut os2 = font.table(Tag::new(b"OS/2")).ok_or("no OS/2")?.to_vec(); write_u16_be(&mut os2, 4, 700); // Every table of the font, borrowed and keyed by tag. Then the edit goes in and GPOS comes out. let mut tables: BTreeMap<Tag, &[u8]> = font.table_tags().filter_map(|tag| Some((tag, font.table(tag)?))).collect(); tables.insert(Tag::new(b"OS/2"), &os2); tables.remove(&Tag::new(b"GPOS")); let file = daegun::raw::build_font(&tables)?; let rebuilt = Font::from_bytes(&file)?; assert_eq!(rebuilt.table_tags().count(), font.table_tags().count() - 1); assert!(!rebuilt.has_table(Tag::new(b"GPOS"))); let weight = rebuilt.os2(&Location::default()).and_then(|os2| os2.weight_class); assert_eq!(weight, Some(700));daegun::raw::bytes::read_i16_bepub fn read_i16_be(data: &[u8], off: usize) -> Option<i16>Reads a big-endian signed 16-bit number at a byte offset, or
Noneif its two bytes are not all there.The same two bytes
raw::bytes::read_u16_bereads, taken as two's complement, so 0xFFFF is -1. It is the reader for the signed fields of a font: metrics, coordinates and deltas.offcounts bytes from the start ofdata. The call never panics: where the two bytes would run past the end, oroffis too large to add 2 to, the answer isNone.use daegun::raw::bytes::read_i16_be; use daegun::Tag; let hhea = font.table(Tag::new(b"hhea")).ok_or("no hhea")?; // The ascender and the descender are signed 16-bit fields at bytes 4 and 6 of hhea. let ascender = read_i16_be(hhea, 4).ok_or("hhea cut short")?; let descender = read_i16_be(hhea, 6).ok_or("hhea cut short")?; // Inter's reach 1984 units above the baseline and 494 below it. assert_eq!((ascender, descender), (1984, -494)); // One byte from the end there is nothing whole to read. assert_eq!(read_i16_be(hhea, hhea.len() - 1), None);daegun::raw::bytes::read_offset24pub fn read_offset24(data: &[u8], off: usize) -> Option<usize>Reads a big-endian 24-bit offset at a byte offset as a
usize, orNoneif its three bytes are not all there.The same three bytes and the same number as
raw::bytes::read_u24_be. The only difference is the type: this one answers ausize, ready to add to a position and index with, where the other answers au32.No offset is treated as special. A stored 0, which most tables use to say there is nothing to point at, comes back as
Some(0), so test for it yourself.Nonemeans only that the three bytes run past the end ofdata, and the call never panics.use daegun::raw::bytes::{read_i16_be, read_offset24, read_u32_be}; use daegun::Tag; let colr = font.table(Tag::new(b"COLR")).ok_or("no COLR")?; // A version 1 COLR keeps the offset of its clip list at byte 22. The list is a format byte and a // 32-bit count, then records of a first glyph, a last glyph and a 24-bit offset to their clip box. let clips = read_u32_be(colr, 22).ok_or("COLR cut short")? as usize; let to_box = read_offset24(colr, clips + 9).ok_or("clip list cut short")?; assert_eq!(to_box, 96); // The box is a format byte, then its four edges. Its left edge, xMin, is at 100 units. assert_eq!(read_i16_be(colr, clips + to_box + 1), Some(100));daegun::raw::bytes::read_u16_bepub fn read_u16_be(data: &[u8], off: usize) -> Option<u16>Reads a big-endian
u16at a byte offset, orNoneif its two bytes are not all there.A font stores every number big-endian, the most significant byte first, and this reads the commonest of them: counts, glyph ids, flags and 16-bit offsets.
offcounts bytes from the start ofdata.The call never panics. Where the two bytes would run past the end of
datathe answer isNone, never a 0 standing in for what is missing, and so it is for anofftoo large to add 2 to. An offset or a count taken straight from a font can go in unchecked, and?carries the failure out.use daegun::raw::bytes::read_u16_be; use daegun::Tag; let head = font.table(Tag::new(b"head")).ok_or("no head")?; // unitsPerEm is the 16-bit field at byte 18 of head. let units_per_em = read_u16_be(head, 18).ok_or("head cut short")?; assert_eq!(units_per_em, font.units_per_em()); // One byte from the end there is nothing whole to read, and no offset is too large to ask about. assert_eq!(read_u16_be(head, head.len() - 1), None); assert_eq!(read_u16_be(head, usize::MAX), None);daegun::raw::bytes::read_u24_bepub fn read_u24_be(data: &[u8], off: usize) -> Option<u32>Reads a big-endian 24-bit unsigned number at a byte offset as a
u32, orNoneif its three bytes are not all there.A few structures store a number in three bytes: the variation selectors of a format 14
cmapsubtable, the offsets inside a version 1COLR, the glyph ids of Coverage formats 3 and 4. The value is always below 0x1000000.raw::bytes::read_offset24reads the same three bytes and gives the same number as ausize, for a value you will index with. The call never panics: where the three bytes would run past the end ofdata, oroffis too large to add 3 to, the answer isNone.use daegun::raw::bytes::{read_u16_be, read_u24_be, read_u32_be}; use daegun::Tag; let cmap = font.table(Tag::new(b"cmap")).ok_or("no cmap")?; // Among cmap's encoding records, 8 bytes each from byte 4, find the subtable of format 14: the // one that lists variation selectors. let count = usize::from(read_u16_be(cmap, 2).ok_or("cmap cut short")?); let subtable = (0..count) .filter_map(|i| read_u32_be(cmap, 4 + 8 * i + 4)) .map(|offset| offset as usize) .find(|&at| read_u16_be(cmap, at) == Some(14)) .ok_or("no format 14 subtable")?; // Its records start 10 bytes in, and each opens with a selector's code point in 24 bits. let selector = read_u24_be(cmap, subtable + 10).ok_or("subtable cut short")?; assert_eq!(selector, 0xFE00);daegun::raw::bytes::read_u32_bepub fn read_u32_be(data: &[u8], off: usize) -> Option<u32>Reads a big-endian
u32at a byte offset, orNoneif its four bytes are not all there.For the 32-bit fields of a font: tags, checksums, long offsets and the counts of the larger tables.
offcounts bytes from the start ofdata.The call never panics: where the four bytes would run past the end of
data, oroffis too large to add 4 to, the answer isNone. A stored offset becomes one to index with throughas usize.use daegun::raw::bytes::read_u32_be; use daegun::Tag; let head = font.table(Tag::new(b"head")).ok_or("no head")?; // head holds the magic number 0x5F0F3CF5 at byte 12. assert_eq!(read_u32_be(head, 12), Some(0x5F0F_3CF5)); // A read needs all four bytes, so the last offset that works is 4 short of the end. assert!(read_u32_be(head, head.len() - 4).is_some()); assert_eq!(read_u32_be(head, head.len() - 3), None);daegun::raw::bytes::records_fitpub fn records_fit(start: usize, count: usize, stride: usize, len: usize) -> boolWhether an array of
countrecords ofstridebytes each, starting at bytestart, lies withinlenbytes.The check to make before a loop over records whose count came from the font. It answers whether
start + count * strideis at mostlen, the length of the table.What it guards against is the sum going wrong. The product and the sum are worked out with checked arithmetic, so a count large enough to overflow a
usizeanswersfalse, where plain arithmetic would panic or wrap around to a small number that seems to fit.After a
true, every read inside the array succeeds and plain indexing cannot go out of bounds. Zero records fit whereverstartis at mostlen.use daegun::raw::bytes::{read_u16_be, records_fit}; use daegun::Tag; let cmap = font.table(Tag::new(b"cmap")).ok_or("no cmap")?; // cmap opens with a version and a count, then that many 8-byte encoding records from byte 4. let count = usize::from(read_u16_be(cmap, 2).ok_or("cmap cut short")?); if !records_fit(4, count, 8, cmap.len()) { return Err("cmap's records run past its end".into()); } // The whole array lies inside the table now, so plain indexing is safe. let ids = |i: usize| { let record = &cmap[4 + 8 * i..4 + 8 * (i + 1)]; (u16::from_be_bytes([record[0], record[1]]), u16::from_be_bytes([record[2], record[3]])) }; let encodings: Vec<(u16, u16)> = (0..count).map(ids).collect(); // Inter's four, each a platform and an encoding: two for Unicode, platform 0, and two for Windows. assert_eq!(encodings, [(0, 3), (0, 4), (3, 1), (3, 10)]); // A count no table could hold is refused, though count * stride overflows on the way. assert!(!records_fit(4, usize::MAX, 8, cmap.len())); // So is one record that would end a byte past the table. assert!(!records_fit(cmap.len() - 7, 1, 8, cmap.len()));daegun::raw::bytes::search_recordspub fn search_records<F>(count: usize, target: u32, key_at: F) -> Option<Result<usize, usize>> where F: Fn(usize) -> Option<u32>,Binary-searches
countrecords sorted by au32key, reading each key through a closure.The search half of a table reader. Font tables are full of arrays sorted by a key: the table directory by tag, a list of glyphs by glyph id, kerning pairs by the two glyphs packed into one number. You say how many records there are and how to read the key of record
i, and it looks fortarget.The answer has three cases.
Some(Ok(i))is the record whose key equalstarget.Some(Err(i))means no record has it, andiis where it would go to keep the order, asslice::binary_searchreports a miss.Nonemeanskey_atansweredNonefor a record the search needed, which is how a key that lies past the end of the table stops the search without a panic.Only the records the search visits are read, about log2 of
countof them, and never one at or pastcount. The middle of a span is found without adding its two ends, so nocountcan overflow it. No records at all answerSome(Err(0))without a call tokey_at.The keys must rise. Over records out of order the answer is wherever the halving lands. Where a font repeats a key, the search stops at the first middle record that matches, which need not be the first of the equal ones.
use daegun::raw::bytes::{read_u16_be, read_u32_be, records_fit, search_records}; use daegun::Tag; // A whole font file, Inter's here. let file = bytes("inter"); // It opens with a 12-byte header, then a 16-byte record a table, sorted by tag: the tag, a // checksum, the table's offset and its length. let count = usize::from(read_u16_be(&file, 4).ok_or("not a font file")?); assert!(records_fit(12, count, 16, file.len())); let tag_at = |i: usize| read_u32_be(&file, 12 + 16 * i); // A tag compares as the big-endian number its four bytes spell. head is record 12 of Inter's 19. let found = search_records(count, u32::from_be_bytes(*b"head"), tag_at); assert_eq!((count, found), (19, Some(Ok(12)))); let record = 12 + 16 * 12; let offset = read_u32_be(&file, record + 8).ok_or("directory cut short")? as usize; let length = read_u32_be(&file, record + 12).ok_or("directory cut short")? as usize; assert_eq!(file.get(offset..offset + length), font.table(Tag::new(b"head"))); // Inter has no kern table. Err says where its record would go: at 15, after hmtx. assert_eq!(search_records(count, u32::from_be_bytes(*b"kern"), tag_at), Some(Err(15))); // A key that fails to read ends the search with None. assert_eq!(search_records(count, 0, |_| None), None);daegun::raw::bytes::windowpub fn window<const N: usize>(data: &[u8], off: usize) -> Option<&[u8; N]>Borrows
Nbytes at a byte offset as a fixed-size array, orNoneif they run past the end.The reader for a whole record at once. Name the size, as
window::<16>(data, at)or through the pattern or type you bind the result to, and you get a reference to exactly that many bytes ofdata. Take them apart withu16::from_be_bytesand the like, with no bounds check left to make. Nothing is copied.What it guards against is the end of the read going wrong.
off + Nis worked out with a checked add, so an offset nearusize::MAX, which is what a hostile 32-bit offset is on a 32-bit machine, answersNonewhere a plain add would panic or wrap around to a read that seems in range.use daegun::raw::bytes::window; use daegun::{Location, Orientation, Tag}; let hmtx = font.table(Tag::new(b"hmtx")).ok_or("no hmtx")?; let h = font.glyph_id('H').ok_or("no H")?; // hmtx opens with 4-byte records, one for each glyph hhea counts: an advance, then a left side // bearing. The pattern names the size, 4. let &[a, b, c, d] = window(hmtx, 4 * h.0 as usize).ok_or("hmtx cut short")?; let (advance, bearing) = (u16::from_be_bytes([a, b]), i16::from_be_bytes([c, d])); assert_eq!((advance, bearing), (1522, 180)); assert_eq!(font.advance(h, &Location::default(), Orientation::Horizontal), 1522.0); // A window that would run past the end is None, and so is one at an offset too large to add its // size to. assert!(window::<4>(hmtx, hmtx.len() - 3).is_none()); assert!(window::<4>(hmtx, usize::MAX).is_none());daegun::raw::bytes::write_i16_bepub fn write_i16_be(data: &mut [u8], off: usize, val: i16) -> boolWrites a signed 16-bit number big-endian at a byte offset, and says whether it did.
It writes the two's complement bits of
val, the high byte first, the same two bytesraw::bytes::write_u16_bewould write for them, andraw::bytes::read_i16_bereads the value back.It returns
trueonce the two bytes are written. Where they would run past the end ofdatait writes nothing and returnsfalse, and it never panics.use daegun::raw::bytes::{read_i16_be, write_i16_be}; use daegun::Tag; // A copy of hhea to edit. Its descender is the signed 16-bit field at byte 6. let mut hhea = font.table(Tag::new(b"hhea")).ok_or("no hhea")?.to_vec(); assert!(write_i16_be(&mut hhea, 6, -500)); // -500 in two's complement, high byte first. assert_eq!(hhea[6..8], [0xFE, 0x0C]); assert_eq!(read_i16_be(&hhea, 6), Some(-500)); // Both bytes must fit: with one byte left, nothing is written. let mut one = [0x7F]; assert!(!write_i16_be(&mut one, 0, -1)); assert_eq!(one, [0x7F]);daegun::raw::bytes::write_offset24pub fn write_offset24(data: &mut [u8], off: usize, val: usize) -> boolWrites an offset big-endian in the three bytes at a byte offset, and says whether it did.
It returns
false, with nothing written, in two cases: the three bytes would run past the end ofdata, orvalis above 0xFFFFFF and so does not fit in 24 bits. The second is the one to check when you lay a table out yourself, since an offset cut down to 24 bits would point somewhere else.It is the writer for any three-byte field, the counterpart of both
raw::bytes::read_offset24andraw::bytes::read_u24_be. It never panics.use daegun::raw::bytes::{read_offset24, write_offset24}; // A clip record as COLR lays one out: a first glyph, a last glyph, then a 24-bit offset. let mut record = [0u8; 7]; assert!(write_offset24(&mut record, 4, 0x01_2345)); assert_eq!(record, [0, 0, 0, 0, 0x01, 0x23, 0x45]); assert_eq!(read_offset24(&record, 4), Some(0x01_2345)); // An offset past 24 bits is refused, and so is a write with fewer than three bytes left. assert!(!write_offset24(&mut record, 4, 0x100_0000)); assert!(!write_offset24(&mut record, 5, 1)); assert_eq!(record, [0, 0, 0, 0, 0x01, 0x23, 0x45]);daegun::raw::bytes::write_u16_bepub fn write_u16_be(data: &mut [u8], off: usize, val: u16) -> boolWrites a
u16big-endian at a byte offset, and says whether it did.It returns
trueonce the two bytes are written, the high byte first. Where they would run past the end ofdatait writes nothing and returnsfalse, and it never panics, so check the answer where a missed write matters.A font's own tables are read-only. To change a field, copy the table, write into the copy, and hand the copy to
raw::build_fontwith the rest.use daegun::raw::bytes::{read_u16_be, write_u16_be}; use daegun::Tag; // A copy of OS/2 to edit. usWeightClass is the 16-bit field at byte 4. let mut os2 = font.table(Tag::new(b"OS/2")).ok_or("no OS/2")?.to_vec(); assert!(write_u16_be(&mut os2, 4, 700)); assert_eq!(os2[4..6], [0x02, 0xBC]); assert_eq!(read_u16_be(&os2, 4), Some(700)); // Both bytes must fit: with one byte left, nothing is written. let mut one = [0x7F]; assert!(!write_u16_be(&mut one, 0, 0xFFFF)); assert_eq!(one, [0x7F]);daegun::raw::bytes::write_u32_bepub fn write_u32_be(data: &mut [u8], off: usize, val: u32) -> boolWrites a
u32big-endian at a byte offset, and says whether it did.It returns
trueonce the four bytes are written, the high byte first, whereraw::bytes::read_u32_bereads them back. Where they would run past the end ofdatait writes nothing and returnsfalse, and it never panics.use daegun::raw::bytes::{read_u32_be, write_u32_be}; use daegun::Tag; // A copy of head to edit. fontRevision is a 16.16 fixed-point number at byte 4: 0x0002_8000 is 2.5. let mut head = font.table(Tag::new(b"head")).ok_or("no head")?.to_vec(); assert!(write_u32_be(&mut head, 4, 0x0002_8000)); assert_eq!(head[4..8], [0x00, 0x02, 0x80, 0x00]); assert_eq!(read_u32_be(&head, 4), Some(0x0002_8000)); // All four bytes must fit: with three left, nothing is written. let mut three = [0xAA; 3]; assert!(!write_u32_be(&mut three, 0, 1)); assert_eq!(three, [0xAA; 3]);daegun::raw::format::control_pointpub fn control_point(data: &[u8], at: usize) -> Option<AnchorPoint>Reads a point from four bytes at a byte offset: x, then y, each a big-endian signed 16-bit number.
This is the layout Apple's
ankrtable stores each anchor point of a glyph in, and the one akerxsubtable uses where its actions hold the coordinates of a control point. The values are font units, y up.It takes any bytes and an offset into them and knows nothing of the table around them, so finding the offset is your part. For an anchor by glyph and index,
Ankr::anchor_pointdoes the finding.Nonemeans the four bytes run past the end ofdata. The call never panics.use daegun::raw::format::{control_point, AnchorPoint}; // A glyph's entry in ankr: a 32-bit count of points, here 2, then the points at four bytes each. let entry = [0, 0, 0, 2, 0x01, 0x2C, 0x02, 0xBC, 0xFF, 0x9C, 0x00, 0x00]; let points: Vec<AnchorPoint> = (0..2).filter_map(|i| control_point(&entry, 4 + 4 * i)).collect(); assert_eq!(points, [AnchorPoint { x: 300, y: 700 }, AnchorPoint { x: -100, y: 0 }]); // A point needs all four bytes, so one that starts two from the end is None. assert_eq!(control_point(&entry, 10), None);daegun::raw::format::coverage_glyphspub fn coverage_glyphs(buf: &[u8], off: usize) -> Result<Vec<u32>, Error>Lists every glyph of an OpenType Coverage table, in coverage order.
A Coverage table is the list of glyphs a GSUB or GPOS subtable applies to. This reads the one at byte
offofbufand returns its glyph ids: the list of a format 1 or 3 table as stored, or each range of a format 2 or 4 table from its first glyph to its last. Formats 3 and 4 are 1 and 2 with 24-bit glyph ids. In a well-formed table the glyph at placeiof the result is the oneraw::format::coverage_indexgives indexi.It checks what it reads, where
raw::format::coverage_indexanswers from whatever fits. The error isErrorKind::Malformedfor a table cut short, which covers a header, a glyph list or a range array that runs past the end ofbuf, and for ranges that are out of order: one that ends before it starts, or one that does not start after the range before it ends. It isErrorKind::Unsupportedfor a format other than 1 to 4. A glyph list is not checked for order and comes back as it is stored.The result is a new
Vecwith au32for each glyph covered.use daegun::raw::bytes::read_u16_be; use daegun::raw::format::{coverage_glyphs, coverage_index}; use daegun::{ErrorKind, GlyphId, Tag}; let gsub = font.table(Tag::new(b"GSUB")).ok_or("no GSUB")?; let u16_at = |at: usize| read_u16_be(gsub, at).map(usize::from).ok_or("GSUB cut short"); // Walk to the first subtable of lookup 17: the lookup list's offset is at byte 8, and a lookup's // subtable offsets start 6 bytes into it. The subtable holds its Coverage offset at byte 2. let lookups = u16_at(8)?; let lookup = lookups + u16_at(lookups + 2 + 2 * 17)?; let subtable = lookup + u16_at(lookup + 6)?; let coverage_at = subtable + u16_at(subtable + 2)?; let glyphs = coverage_glyphs(gsub, coverage_at)?; // In Inter the lookup covers 43 glyphs, and the first three are a, b and c. assert_eq!(glyphs.len(), 43); let names: Vec<_> = glyphs[..3].iter().map(|&glyph| font.glyph_name(GlyphId(glyph))).collect(); assert_eq!(names, [Some("a"), Some("b"), Some("c")]); // A glyph's place in the list is its coverage index. assert_eq!(coverage_index(&gsub[coverage_at..], glyphs[2]), Some(2)); // A format it does not read is an error here. let unknown = coverage_glyphs(&[0, 9, 0, 0], 0); assert_eq!(unknown.map_err(|e| e.kind()), Err(ErrorKind::Unsupported));daegun::raw::format::coverage_indexpub fn coverage_index(data: &[u8], glyph: u32) -> Option<u32>A glyph's index in an OpenType Coverage table, or
Noneif the table does not cover it.A Coverage table is the list of glyphs a GSUB or GPOS subtable applies to. The subtable keeps what it holds for each glyph in coverage order, so the index this returns is the one to read that with.
datamust start at the Coverage table: slice the layout table at the coverage offset first.It reads all four formats: 1, a sorted list of glyphs, 2, sorted ranges, and 3 and 4, which are the same two with 24-bit glyph ids. In a range the index is the start index the range states plus how far into the range the glyph is. The lookup is a binary search, so it trusts the order: in a table whose glyphs are out of order, a glyph that is listed can be missed.
There is no error.
Nonestands for every way of finding no index: the glyph is not covered, the format is not one of the four, ordatais too short to hold a header. A table cut short is searched over the records that fit, whatever count it states.raw::format::coverage_glyphsis the call that tells those cases apart.use daegun::raw::bytes::read_u16_be; use daegun::raw::format::coverage_index; use daegun::{GlyphId, Tag}; let gsub = font.table(Tag::new(b"GSUB")).ok_or("no GSUB")?; let u16_at = |at: usize| read_u16_be(gsub, at).map(usize::from).ok_or("GSUB cut short"); // Walk to the first subtable of lookup 17, which Inter's sinf feature uses to swap letters for // their subscript forms. The lookup list's offset is at byte 8, each lookup's offset follows the // list's count, and a lookup's subtable offsets start 6 bytes into it. let lookups = u16_at(8)?; let lookup = lookups + u16_at(lookups + 2 + 2 * 17)?; let subtable = lookup + u16_at(lookup + 6)?; // The subtable holds its Coverage offset at byte 2, and its replacement glyphs from byte 6, in // coverage order. let coverage = gsub.get(subtable + u16_at(subtable + 2)?..).ok_or("GSUB cut short")?; let b = font.glyph_id('b').ok_or("no b")?; let index = coverage_index(coverage, b.0).ok_or("the lookup leaves b alone")? as usize; assert_eq!(index, 1); let replacement = GlyphId(u16_at(subtable + 6 + 2 * index)? as u32); assert_eq!(font.glyph_name(replacement), Some("b.subs")); // A glyph the table does not cover, the capital B here, has no index. let capital = font.glyph_id('B').ok_or("no B")?; assert_eq!(coverage_index(coverage, capital.0), None);daegun::raw::format::delta_set_index_map_lookuppub fn delta_set_index_map_lookup(map: &[DeltaSetIndex], idx: usize) -> DeltaSetIndexAn item's entry in a delta set index map, with the rules for an item past the end and for an empty map.
Entry
idxof the mapraw::format::parse_delta_set_index_mapread. Two cases follow the rules for these maps. Anidxpast the end takes the last entry, since a font may leave off a tail of items that share one row. And an empty map is no map at all, where itemidxis rowidxof subtable 0: the answer is anouterof 0 and aninnerofidx, or ofu32::MAXfor anidxtoo large for au32.It never fails and never panics. Whether the row exists is for
ItemVariationStore::deltato say, which answers 0 for an index the store does not hold.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}; let hvar = font.table(Tag::new(b"HVAR")).ok_or("no HVAR")?; let offset = |at: usize| read_u32_be(hvar, at).map(|v| v as usize).ok_or("HVAR cut short"); // HVAR holds the offset of its store at byte 4 and that of its advance width map at byte 8. let store = ItemVariationStore::parse(hvar, offset(4)?)?; let map = parse_delta_set_index_map(hvar, offset(8)?)?; let heavy = font.location(&[(Tag::new(b"wght"), 900.0)]); let scalars = store.region_scalars(heavy.normalized()); let h = font.glyph_id('H').ok_or("no H")?; let delta = store.delta(delta_set_index_map_lookup(&map, h.0 as usize), &scalars); // Inter's H is 14 units wider at weight 900 than at the default. assert_eq!(delta, 14.0); let advance = |at: &Location| font.advance(h, at, Orientation::Horizontal); assert_eq!(advance(&heavy) - advance(&Location::default()), delta); // Past the end the last entry answers. An empty map is no map: item 7 is row 7 of subtable 0. assert_eq!(delta_set_index_map_lookup(&map, usize::MAX), map[map.len() - 1]); let direct = delta_set_index_map_lookup(&[], 7); assert_eq!((direct.outer, direct.inner), (0, 7));daegun::raw::format::ot_roundpub fn ot_round(v: f64) -> i32Rounds to the nearest whole number as the OpenType specification does: a half goes up, toward positive infinity.
It is the floor of
v + 0.5. So 0.5 becomes 1 and 1.5 becomes 2, and below zero -0.5 becomes 0 and -1.5 becomes -1. That is not whatf64::rounddoes: it sends a half away from zero, and gives -1 and -2 for those last two.Use it wherever a tool must land on the same whole number a font compiler would, such as a coordinate or a delta worked out at a location and stored as an integer.
A result outside the range of an
i32stops ati32::MAXori32::MIN, and a value that is not a number gives 0.use daegun::raw::format::ot_round; assert_eq!([0.5, 1.5, -0.5, -1.5].map(ot_round), [1, 2, 0, -1]); // f64::round sends a half away from zero. assert_eq!([0.5, 1.5, -0.5, -1.5].map(f64::round), [1.0, 2.0, -1.0, -2.0]); // Only an exact half is a tie. Anything else goes to the nearer whole number. assert_eq!([-200.5, -200.6, 0.4, 0.6].map(ot_round), [-200, -201, 0, 1]);daegun::raw::format::parse_delta_set_index_mappub fn parse_delta_set_index_map(buf: &[u8], base: usize) -> Result<Vec<DeltaSetIndex>, Error>Reads a DeltaSetIndexMap: for each item of a table, which row of its
ItemVariationStoreholds the deltas.HVARandVVARhave one to map a glyph to the deltas of its advance, andCOLRone for its variable values.bufis the whole table andbasethe byte offset of the map in it. The result has aDeltaSetIndexfor each entry, in order, so entryibelongs to itemi. Look an item up withraw::format::delta_set_index_map_lookup, which also answers for an item past the end.A table states an offset of 0 where it has no map. Test for that before you call, since byte 0 of the table is not a map.
Both formats are read: format 0, with a 16-bit count of entries, and format 1, with a 32-bit one. The error is
ErrorKind::Malformedfor a map cut short, wherebaseis past the end ofbuf, the header does not fit, or the entries the count states run past the end, andErrorKind::Unsupportedfor a format above 1. A map of no entries isOkand empty. The result is a newVec.use daegun::raw::bytes::read_u32_be; use daegun::raw::format::{parse_delta_set_index_map, DeltaSetIndex}; use daegun::{ErrorKind, Tag}; let hvar = font.table(Tag::new(b"HVAR")).ok_or("no HVAR")?; // HVAR holds the offset of its advance width map at byte 8, or 0 where it has none. let map_at = read_u32_be(hvar, 8).ok_or("HVAR cut short")? as usize; if map_at == 0 { return Err("HVAR has no map: glyph g is row g of subtable 0".into()); } let map = parse_delta_set_index_map(hvar, map_at)?; // Inter's map has an entry for each of its 2937 glyphs. Glyph 1 is sent to row 0 of subtable 9. assert_eq!(map.len(), font.glyph_count() as usize); assert_eq!((map.len(), map[1]), (2937, DeltaSetIndex { outer: 9, inner: 0 })); // A map that starts past the end of the table is malformed. let past = parse_delta_set_index_map(hvar, hvar.len()); assert_eq!(past.map_err(|e| e.kind()), Err(ErrorKind::Malformed));daegun::raw::outline_glyf_bytespub fn outline_glyf_bytes( glyf: &[u8], extended: bool, loca: &[usize], gid: u32, pen: &mut dyn OutlinePen, ) -> Result<(), Error>Draws a glyph onto a pen straight from
glyfbytes andlocaoffsets, with noFontin between.For a tool that holds tables and not a font: one that has edited
glyf, built it, or cut it out of a file.glyfis the bytes of the table,locathe offsetsraw::parse_locareturns for it, andgidthe glyph. The outline goes topen, anyOutlinePen, such as aPath, the wayFont::outlinedraws one: a contour at a time, in lines and quadratic curves, and cubic ones whereextendedis set and the glyph flags them, in font units with y up.A composite glyph, one built out of other glyphs, is resolved: each component is read from the same bytes, put in its place and drawn.
extendedsays the bytes are those of aGLYFtable, the wide form whose composites can name a component in 24 bits. Passfalsefor an ordinaryglyf.The glyph is drawn as it is stored. Nothing varies it, so in a variable font this is the default instance, and nothing is scaled or hinted.
A glyph with no data draws nothing and is
Ok. That is a space, and also a glyph whose two offsets run backward or reach past the end ofglyf.The error is
ErrorKind::NoOutlinewheregidis past the glyphslocahas offsets for. It isErrorKind::Malformedfor data that is cut short or contradicts itself: a header of under 10 bytes, a simple glyph or a composite that ends early, a composite that names a glyph pastlocaor holds itself, or more points or contours than an outline can hold. It isErrorKind::LimitExceededfor a composite that asks for more work than daegun allows one glyph. The pen may hold part of the glyph by then, so use what it drew only when the call isOk.use daegun::outline::Path; use daegun::raw::bytes::read_i16_be; use daegun::raw::{outline_glyf_bytes, parse_loca}; use daegun::{ErrorKind, Location, Tag}; let table = |tag: &[u8; 4]| font.table(Tag::new(tag)).ok_or("the font lacks a table"); let (head, loca, glyf) = (table(b"head")?, table(b"loca")?, table(b"glyf")?); let format = read_i16_be(head, 50).ok_or("head cut short")?; let offsets = parse_loca(loca, format, font.glyph_count() as usize); let a = font.glyph_id('a').ok_or("no a")?; let mut path = Path::new(); outline_glyf_bytes(glyf, false, &offsets, a.0, &mut path)?; // The same outline Font::outline draws at the default location. let mut same = Path::new(); font.outline(a, &Location::default(), &mut same)?; assert!(path == same && !path.is_empty()); // A glyph id past the offsets is refused. let past = outline_glyf_bytes(glyf, false, &offsets, font.glyph_count(), &mut Path::new()); assert_eq!(past.map_err(|e| e.kind()), Err(ErrorKind::NoOutline));daegun::raw::parse_locapub fn parse_loca(loca: &[u8], format: i16, num_glyphs: usize) -> Vec<usize>Reads the
locatable into byte offsets intoglyf: one for each glyph, and one more for the end of the last.locasays where the data of each glyph lies inglyf. Glyphgis the bytes fromoffsets[g]up tooffsets[g + 1], and a glyph whose two offsets are equal has no outline, as a space has none.formatisindexToLocFormat, the 16-bit field at byte 50 ofhead. 0 is the short form, which stores each offset halved in 16 bits, and the call doubles them back, so the result is in bytes either way. Any other value is read as the long form, 32 bits an offset.num_glyphsis the font's glyph count, whichFont::glyph_countgives. Up to 65,535 glyphs the result hasnum_glyphs + 1offsets however longlocais, and an entry the table is too short to hold reads 0. Nothing is checked againstglyf: in a broken font an offset can run backward or past its end, andraw::outline_glyf_bytesdraws such a glyph as an empty one.The count sizes the result, so one above 65,535 gives no more offsets than
locaholds entries, or 65,536 where it holds fewer. Any count is safe to pass. The call has no error and returns a newVec.use daegun::raw::bytes::read_i16_be; use daegun::raw::parse_loca; use daegun::Tag; let table = |tag: &[u8; 4]| font.table(Tag::new(tag)).ok_or("the font lacks a table"); let (head, loca, glyf) = (table(b"head")?, table(b"loca")?, table(b"glyf")?); let format = read_i16_be(head, 50).ok_or("head cut short")?; let offsets = parse_loca(loca, format, font.glyph_count() as usize); // An offset for each glyph and one for the end, which is the length of glyf. assert_eq!(offsets.len(), font.glyph_count() as usize + 1); assert_eq!(offsets.last(), Some(&glyf.len())); // Where Inter keeps its a, and its space, which has no data. let data = |c: char| font.glyph_id(c).map(|g| offsets[g.0 as usize]..offsets[g.0 as usize + 1]); assert_eq!(data('a'), Some(17509..17673)); assert!(data(' ').is_some_and(|range| range.is_empty()));raw::format::Ankr::anchor_pointpub fn anchor_point(&self, glyph: u32, index: u16) -> Option<AnchorPoint>One anchor point of a glyph, by its index.
Points are numbered from 0 in the order the table stores them. The
AnchorPointis in font units, y up.Nonemeans the glyph has no such point: the table's lookup doesn't list the glyph,indexis at or past the count the table states for it, or the point lies past the end of the table.use daegun::raw::format::{AnchorPoint, Ankr}; // An ankr table written out by hand, as 16-bit words, for a font of 3 glyphs. 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)?; // The two points of glyph 2, and no third. 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 })); assert_eq!(ankr.anchor_point(2, 2), None); // Glyph 1 is not in the table. assert_eq!(ankr.anchor_point(1, 0), None);raw::format::Ankr::parsepub fn parse(data: &'a [u8], num_glyphs: u32) -> Result<Self, Error>Reads an
ankrtable from its bytes.datais the whole table from its first byte, since the offsets in its header are counted from there.num_glyphsis the font's glyph count, fromFont::glyph_count, which the table's lookup needs when it is stored in format 0. The result borrowsdata.The call reads the 12-byte header and opens the lookup it points to. An error of kind
ErrorKind::Malformedmeans the table is shorter than its header, the lookup's offset points past the end of the table, or fewer than two bytes are left where the lookup should start.ErrorKind::Unsupportedmeans the lookup is in a formatLookupdoesn't read.The version is not checked, and neither is the offset of the points: a glyph whose points lie past the end of the table has an
Ankr::point_countof 0. A lookup offset of 0 is not refused either. The lookup is then read from the top of the table, over the header, so check for that in a font you don't trust. The engine's own shaping sets such a table aside.use daegun::raw::format::Ankr; use daegun::ErrorKind; // An ankr table written out by hand, as 16-bit words, for a font of 3 glyphs. 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)?; // Cut inside its 12-byte header, the table doesn't parse. assert_eq!(Ankr::parse(&table[..10], 3).unwrap_err().kind(), ErrorKind::Malformed);raw::format::Ankr::point_countpub fn point_count(&self, glyph: u32) -> u32How many anchor points of a glyph can be read.
It is the count the table states for the glyph, cut down to the points that fit in the bytes of the table, and to 65,536, the most a 16-bit index can name. So
Ankr::anchor_pointreturns a point for every index below it. A glyph the table doesn't list has 0.use daegun::raw::format::Ankr; // An ankr table written out by hand, as 16-bit words, for a font of 3 glyphs. 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)?; for index in 0..ankr.point_count(2) { let point = ankr.anchor_point(2, index as u16).expect("an index below the count"); // Attach at (point.x, point.y), in font units. } assert_eq!(ankr.point_count(2), 2); // Glyph 1 is not in the table. assert_eq!(ankr.point_count(1), 0); // The same table with the last point cut off: it still says two, and one is there. let cut = Ankr::parse(&table[..28], 3)?; assert_eq!(cut.point_count(2), 1);raw::format::Ankr::versionpub fn version(data: &[u8]) -> Option<u16>The version number at the start of an
ankrtable, orNoneifdatais too short to hold one.It is called on the table's bytes, before anything is parsed: it reads the first two bytes and checks nothing.
Ankr::parsedoes not look at the version, so a tool that wants to refuse a version it doesn't know asks here first.use daegun::raw::format::Ankr; // The first 16-bit word of an ankr table is its version. This table's is 0. let table: [u8; 12] = [0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 20]; assert_eq!(Ankr::version(&table), Some(0)); // One byte is not enough to hold a version. assert_eq!(Ankr::version(&table[..1]), None);raw::format::FeatureVariations::atpub const fn at(layout: &'a [u8], at: usize) -> SelfA FeatureVariations table at an offset you give, with no look at the layout table's header.
layoutis the wholeGSUBorGPOStable andatis where the FeatureVariations table starts in it.FeatureVariations::parsereads that offset from the header and refuses a header older than version 1.1. This call does neither, for when you already hold the offset.It is a
const fnand cannot fail, as it reads nothing. A wrong offset shows later, if at all. Past the end of the table,FeatureVariations::findandFeatureVariations::substituteanswerNone. Inside it, they read whatever bytes are there as a table. Anyusizeis safe to pass.use daegun::raw::bytes::read_u32_be; use daegun::raw::format::{FeatureVariations, Substitution}; // A GSUB header with a FeatureVariations table, written out by hand as 16-bit words. 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(); // The offset the header holds at byte 10, read by hand. let offset = read_u32_be(&gsub, 10).expect("a whole header") as usize; let variations = FeatureVariations::at(&gsub, offset); assert_eq!(variations.find(&[0, 16384], None), Some(0)); assert_eq!(variations.substitute(0, 3), Some(Substitution::Feature(56))); // An offset past the table is not an error. There is nothing to find there. let nowhere = FeatureVariations::at(&gsub, 1000); assert_eq!(nowhere.find(&[0, 16384], None), None);raw::format::FeatureVariations::findpub fn find(&self, coords: &[i32], store: Option<&ItemVariationStore>) -> Option<u32>The index of the first record whose conditions all hold at a location, or
Noneif no record applies there.coordsis the location in normalized coordinates, one for each axis in the order of the font'sfvartable, as integers in F2Dot14, where 16384 stands for 1.0. That is the scale the table states its conditions in. To get it fromLocation::normalized, multiply each value by 16384 and round, which is what shaping does. An axis the slice has no value for is taken at 0, so an empty slice is the default location.Records are tried in order and the first that holds is the answer. A record with no condition set always holds. The usual condition is a range on one axis, which holds when the coordinate is inside it, both ends included. The table's other kinds are read too: all of a list of conditions, any of a list, the opposite of one, and a test on a value that varies.
storematters for that last kind alone. Its value is a default plus a delta from anItemVariationStore, and it holds when the sum is above 0. Pass the store of the font'sGDEFtable, as shaping does, orNonefor a font without one. WithNone, or with every coordinate at 0, the delta is 0.Nonealso comes back where the table can't be read at its offset, or a record's offset to its condition set is cut short. A record whose condition set is null needs no more bytes, so a table cut short after it still finds it. A condition of a kind the call doesn't know counts as not holding, and so does one nested more than 64 deep. A table built to waste time, its conditions repeated without end, uses up the reads the search allows itself, and the answer isNone.use daegun::raw::format::FeatureVariations; use daegun::Tag; // A GSUB header with a FeatureVariations table, written out by hand as 16-bit words. Its one // record holds where axis 1 is from 0.5 to 1. 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"); // A location's normalized coordinates, turned into F2Dot14. Axis 1 of Inter is weight. let f2dot14 = |weight: f64| -> Vec<i32> { let location = font.location(&[(Tag::new(b"wght"), weight)]); location.normalized().iter().map(|&v| (v * 16384.0).round() as i32).collect() }; // Weight 700 is at 0.54 in normalized coordinates, inside the range. Weight 600 is below it. assert_eq!(variations.find(&f2dot14(700.0), None), Some(0)); assert_eq!(variations.find(&f2dot14(600.0), None), None); // The range includes its ends. assert_eq!(variations.find(&[0, 8192], None), Some(0)); assert_eq!(variations.find(&[0, 8191], None), None);raw::format::FeatureVariations::parsepub fn parse(layout: &'a [u8]) -> Option<Self>Finds the FeatureVariations table that a
GSUBorGPOStable names in its header.layoutis the wholeGSUBorGPOStable, asFont::tablereturns it, since every offset is counted from its start. The result borrows it.A layout table names one only from version 1.1 of its header on, which holds the offset at byte 10.
Nonemeans there is none to read: the table is shorter than 14 bytes, its major version is not 1, its minor version is 0, or the offset is null.The offset is not checked against the table's length. One that points past the end still gives a
FeatureVariations, which then finds no record.use daegun::raw::format::FeatureVariations; use daegun::Tag; // Inter's GSUB has a header of version 1.0, which names no FeatureVariations. let gsub = font.table(Tag::new(b"GSUB")).expect("Inter has a GSUB"); assert!(FeatureVariations::parse(gsub).is_none()); // A header of version 1.1 written out by hand, as 16-bit words, with one record. 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"); // With a null offset at byte 10 there is no table. let mut none = gsub.clone(); none[10..14].fill(0); assert!(FeatureVariations::parse(&none).is_none());raw::format::FeatureVariations::substitutepub fn substitute(&self, variation: u32, feature: u16) -> Option<Substitution>What a record puts in place of one feature: an alternate feature table, the empty feature, or
Noneif the record leaves that feature alone.variationis a record's index, asFeatureVariations::findreturns it.featureis the index of a feature in the layout table's list of features.Substitution::Featurecarries the offset of the alternate feature table, counted from the start of the layout table. It is laid out as any feature table is: a 2-byte offset to its parameters, a count of lookups, then the indices of the lookups.Substitution::Emptyis a null offset in the font: the feature is replaced by one with no lookups, which turns it off.Nonemeans the record does not replace this feature, so the table's own feature stands. That covers a record with no substitution table and one with no entry forfeature. Where a record lists a feature twice, its first entry is the one returned.The record index is not checked against the table's count of records. One past the last record reads the bytes that follow the records as if they were another, so pass only an index that
FeatureVariations::findgave you.use daegun::raw::bytes::read_u16_be; use daegun::raw::format::{FeatureVariations, Substitution}; // A GSUB header with a FeatureVariations table, written out by hand as 16-bit words. Its one // record replaces feature 3. 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"); let record = variations.find(&[0, 16384], None).expect("a record that holds here"); match variations.substitute(record, 3) { Some(Substitution::Feature(at)) => { // The alternate feature table is at byte `at` of the GSUB, with its lookup count 2 bytes in. assert_eq!(at, 56); assert_eq!(read_u16_be(&gsub, at + 2), Some(0)); } Some(Substitution::Empty) => { /* feature 3 is turned off here */ } None => { /* feature 3 stands as the GSUB has it */ } } // The record has nothing to say about feature 4. assert_eq!(variations.substitute(record, 4), None);raw::format::ItemVariationStore::deltapub fn delta(&self, index: DeltaSetIndex, region_scalars: &[f64]) -> f64How much one item changes at a location.
indexnames the item: itsouterpicks anIvdofItemVariationStore::ivd_dataand itsinnera row of it.region_scalarsis whatItemVariationStore::region_scalarsreturned for the location. The result is the deltas of the row, each multiplied by the scalar of its region, added up.It is in the units of the value the item varies, font units for an advance or a metric, and it is not rounded. Add it to the value the font stores for its default location. The sum is worked out in 16.16 fixed point, so it is exact to 1/65536 of a unit, and each scalar is first rounded to the nearest 65536th: those
ItemVariationStore::region_scalarsgives already are, and a scalar of your own, such as 1/3, counts as its nearest 65536th. Where a font varies its advances byHVAR,Font::advancereports the advance itshmtxtable stores plus this delta, rounded to a whole unit.An index the store doesn't hold, in either half, gives 0. A region whose scalar is missing from the slice counts as 0, so an empty slice gives 0 for every item.
use daegun::raw::bytes::read_u32_be; use daegun::raw::format::{delta_set_index_map_lookup, parse_delta_set_index_map}; use daegun::raw::format::{DeltaSetIndex, ItemVariationStore}; use daegun::{Location, Orientation, Tag}; // Inter's HVAR table: its store's offset is at byte 4, and its map from glyph to item at byte 8. 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)?; // The map gives the item for a glyph. For A it is row 46 of subtable 3. let a = font.glyph_id('A').expect("an A"); let index = delta_set_index_map_lookup(&map, a.0 as usize); assert_eq!(index, DeltaSetIndex { outer: 3, inner: 46 }); // At weight 700 the advance of A grows by a little over 116 units. The delta is not rounded. let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); let scalars = store.region_scalars(bold.normalized()); let delta = store.delta(index, &scalars); assert!((delta - 116.108).abs() < 0.001); // The font's own answer is the default advance plus the delta, rounded: 1413 and 116 make 1529. let default = font.advance(a, &Location::default(), Orientation::Horizontal); assert_eq!(font.advance(a, &bold, Orientation::Horizontal), (default + delta).round()); // An index the store doesn't hold varies nothing. assert_eq!(store.delta(DeltaSetIndex { outer: 99, inner: 0 }, &scalars), 0.0);raw::format::ItemVariationStore::parsepub fn parse(buf: &[u8], base: usize) -> Result<ItemVariationStore, Error>Decodes the ItemVariationStore that starts
basebytes into a table.bufis the whole table andbaseis where the store starts in it, an offset the table's own header gives: 32 bits at byte 4 ofHVARand ofVVAR, 16 bits at byte 10 ofMVAR, 32 bits at byte 14 of aGDEFof version 1.3.raw::bytes::read_u32_beandraw::bytes::read_u16_beread such an offset. So this call takes a table and an offset, whereLookup::parseandStateTable::parsetake a slice cut at the structure. A slice that starts at the store, with abaseof 0, reads the same.Everything is decoded into the result, which owns its data and borrows nothing from
buf. That allocates in proportion to the store, so parse once and keep it.An error of kind
ErrorKind::Malformedmeansbaseis at or past the end ofbuf, or the store's 8-byte header is cut short.ErrorKind::Unsupportedmeans the two bytes atbaseare not the format number 1. That is also the answer where a single byte is left atbase.Past the header the call is lenient, so that one bad part doesn't lose the rest. A list of regions that doesn't fit in the table gives a store with no regions. A subtable with a null offset, one that doesn't fit, or one that claims more wide deltas than it has regions, becomes an empty
Ivd. Rows that run past the end of the table read as zeros.Size is bounded too, as offsets may repeat and a small hostile table could name the same data many times over. A subtable that would take the store past a million rows in all, or past four values for each byte from the store's start (65,536 at the least), is left empty.
use daegun::raw::bytes::{read_u16_be, read_u32_be}; use daegun::raw::format::ItemVariationStore; use daegun::{ErrorKind, Tag}; // HVAR holds the offset of its store as 32 bits at byte 4. let hvar = font.table(Tag::new(b"HVAR")).expect("Inter is variable"); let at = read_u32_be(hvar, 4).expect("a whole header") as usize; let advances = ItemVariationStore::parse(hvar, at)?; // Inter has 2 axes, and its advances vary over 5 regions, in 10 subtables. assert_eq!((advances.axis_count, advances.regions.len(), advances.ivd_data.len()), (2, 5, 10)); // MVAR holds its own as 16 bits at byte 10. let mvar = font.table(Tag::new(b"MVAR")).expect("Inter varies its metrics"); let at = usize::from(read_u16_be(mvar, 10).expect("a whole header")); let metrics = ItemVariationStore::parse(mvar, at)?; // The same 5 regions, and one subtable. assert_eq!((metrics.regions.len(), metrics.ivd_data.len()), (5, 1)); // An offset past the table, and bytes that say format 2. assert_eq!(ItemVariationStore::parse(hvar, hvar.len()).unwrap_err().kind(), ErrorKind::Malformed); assert_eq!(ItemVariationStore::parse(&[0, 2, 0, 0], 0).unwrap_err().kind(), ErrorKind::Unsupported);raw::format::ItemVariationStore::region_scalarspub fn region_scalars(&self, location: &[f64]) -> Vec<f64>How strongly each region of the store applies at a location: one scalar for each region, from 0 to 1.
locationis in normalized coordinates: one value for each axis in the order of the font'sfvartable, from -1 to 1, with 0 at the default of the axis. That is the sliceLocation::normalizedreturns. An axis the slice has no value for is taken at 0, so the empty slice of the default location works as it is. A value outside -1 to 1 is not clamped: at 1.5 a region that peaks and ends at 1 has a scalar of 0, so clamp a coordinate of your own first.The result has an entry for each region of
ItemVariationStore::regions, at the same index. On one axis a region counts for 1 at its peak and falls in a straight line to 0 at its start and its end, and the region's scalar is the product over its axes. An axis with a peak of 0 is left out of the product, and so is one whose three values are out of order or whose range runs from below 0 to above it.Pass the list to
ItemVariationStore::delta. It depends on the location alone, so work it out once for a location and use it for every item. The arithmetic is done in 16.16 fixed point, as all variation in daegun is, and the scalars come back asf64.use daegun::raw::bytes::read_u32_be; use daegun::raw::format::ItemVariationStore; use daegun::{Location, 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)?; // Inter's axes are optical size, then weight, and region 2 of this store is the heavy side of // weight. At the heaviest weight it applies in full, and the other four regions not at all. let heavy = font.location(&[(Tag::new(b"wght"), 900.0)]); assert_eq!(store.region_scalars(heavy.normalized()), [0.0, 0.0, 1.0, 0.0, 0.0]); // Weight 700 is at 0.54 in normalized coordinates, and the region applies by as much. let bold = font.location(&[(Tag::new(b"wght"), 700.0)]); let scalars = store.region_scalars(bold.normalized()); assert!((scalars[2] - 0.54).abs() < 0.001); // At the default location the normalized slice is empty, and no region applies. assert_eq!(store.region_scalars(Location::default().normalized()), [0.0; 5]);raw::format::Ivd::rowpub fn row(&self, inner: usize) -> Option<&[i32]>The deltas of one item: a slice with one delta for each region in
Ivd::region_indices.inneris the row, the inner half of aDeltaSetIndex.Nonemeans the subtable has no such row. The slice is borrowed from theIvdand is as long asIvd::region_indices: deltajbelongs to regionregion_indices[j].A subtable that uses no regions still has its rows, each an empty slice. A row that the font's table was too short to hold reads as zeros.
use daegun::raw::bytes::read_u32_be; use daegun::raw::format::ItemVariationStore; 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)?; // Row 46 of subtable 3 is the advance of A. let ivd = &store.ivd_data[3]; let row = ivd.row(46).expect("subtable 3 has 148 rows"); for (region, delta) in ivd.region_indices.iter().zip(row) { // The advance changes by `delta` units where region `region` applies in full. } assert_eq!(row, [215, -75, -103, -17, 12]); // Past the last row there is nothing. assert_eq!(ivd.row(148), None);raw::format::Ivd::rowspub const fn rows(&self) -> usizeHow many items the subtable holds, which is how many rows it has.
Rows are numbered from 0, so
Ivd::rowanswers for every index below this andNonefrom there on. An empty subtable, such as one the store named but that could not be read, has 0.use daegun::raw::bytes::read_u32_be; use daegun::raw::format::ItemVariationStore; 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)?; // Its 10 subtables hold 821 rows between them, the largest 317. let rows: Vec<usize> = store.ivd_data.iter().map(|ivd| ivd.rows()).collect(); assert_eq!(rows.len(), 10); assert_eq!((rows.iter().sum::<usize>(), rows.iter().max()), (821, Some(&317)));raw::format::Lookup::entriespub fn entries(&self) -> Vec<GlyphValue>Every glyph the lookup lists, in glyph order, each with its value.
Each
GlyphValuepairs a glyph with whatLookup::valueanswers for it. A glyph comes once however many entries of the font name it, and one thatLookup::valuecan't find is left out. So the list holds at most one entry for each 16-bit glyph id, 65,536 in all, whatever the font repeats.For format 0, which has a slot for every glyph, that is every glyph of the font that the bytes hold a value for, up to glyph 65,535. The searched formats, 2, 4 and 6, never list glyph 0xFFFF, the id AAT keeps for a deleted glyph, whatever
Lookup::valuesays of it.The call walks the whole lookup and allocates the list each time, so keep the result if you need it more than once.
use daegun::raw::format::{GlyphValue, Lookup}; use daegun::Tag; // The lookup of TestMORXOne.ttf's substitution subtable, 60 bytes into morx. let morx = font.table(Tag::new(b"morx")).expect("an AAT font"); let lookup = Lookup::parse(&morx[60..], font.glyph_count())?; // Two glyphs are listed, in glyph order: A becomes A.alt and C becomes C.alt. let entries = lookup.entries(); assert_eq!(entries, [GlyphValue { glyph: 2, value: 5 }, GlyphValue { glyph: 4, value: 7 }]); for GlyphValue { glyph, value } in entries { // `value` is the glyph that replaces `glyph`. }raw::format::Lookup::parsepub fn parse(data: &'a [u8], num_glyphs: u32) -> Result<Self, Error>Reads the lookup that starts at the first byte of
data.datamust begin at the lookup's format word, not at the start of the table that holds it, so slice the table first. The slice may run on past the lookup's end, which is how the engine itself passes one: from the lookup to the end of the table. The result borrowsdata.num_glyphsis the font's glyph count, fromFont::glyph_count. It matters for format 0, a plain array of one value for each glyph with no length of its own: the count is what stops a read past the last glyph. The other formats state their own extent and do not read it.Only the first two bytes are checked here. Fewer than two is an error of kind
ErrorKind::Malformed, and a format other than 0, 2, 4, 6, 8 and 10 is one of kindErrorKind::Unsupported. Anything else wrong with the bytes, such as a count of entries that runs past the data, does not fail the parse: the lookup reads what is there, andLookup::valueanswersNonefor the rest.use daegun::raw::format::Lookup; use daegun::{ErrorKind, Tag}; // The lookup of TestMORXOne.ttf's one morx subtable starts 60 bytes into the table. let morx = font.table(Tag::new(b"morx")).expect("an AAT font"); // Slice the table at the lookup. The slice may run on past the lookup's end. let lookup = Lookup::parse(&morx[60..], font.glyph_count())?; // One byte can't hold a format, and 7 is not a lookup format. let too_short = Lookup::parse(&[0], font.glyph_count()); assert_eq!(too_short.unwrap_err().kind(), ErrorKind::Malformed); let format_7 = Lookup::parse(&[0, 7], font.glyph_count()); assert_eq!(format_7.unwrap_err().kind(), ErrorKind::Unsupported);raw::format::Lookup::valuepub fn value(&self, glyph: u32) -> Option<u16>The value the lookup maps a glyph to, or
Nonefor a glyph it doesn't list.What the value means is up to the table the lookup came from: a replacement glyph, a class, an offset. A glyph the lookup has no entry for is
None, and so is one whose entry lies past the end of the bytes. Bad data never panics.Formats 2, 4 and 6 are searched, by a binary search that trusts the font's order. Where a font lists its entries out of order, a glyph that one of them names can still read
None, as it does in the engine's own shaping. A last entry whose glyphs are 0xFFFF, the terminator such a list may end with, is never searched.In format 0 the glyph must be below the
num_glyphsgiven toLookup::parse. In format 10 a value is stored in 1, 2, 4 or 8 bytes: one that doesn't fit in 16 bits readsNone, as does every value of a lookup that states another size.use daegun::raw::format::Lookup; use daegun::Tag; // The lookup of TestMORXOne.ttf's substitution subtable, 60 bytes into morx. let morx = font.table(Tag::new(b"morx")).expect("an AAT font"); let lookup = Lookup::parse(&morx[60..], font.glyph_count())?; // Glyph 2 is A, and the lookup replaces it with glyph 5, A.alt. assert_eq!(lookup.value(2), Some(5)); // Glyph 3, B, is not listed. Neither is a glyph past the font's last. assert_eq!(lookup.value(3), None); assert_eq!(lookup.value(font.glyph_count()), None);raw::format::StateTable::classpub fn class(&self, glyph: u32) -> u16The class of a glyph, as the table's class lookup gives it.
Glyph 0xFFFF is always
raw::format::class::DELETED_GLYPH, with no look at the class table: it is the mark a deleted glyph leaves. A glyph the class table doesn't list is class 1, which AAT calls out of bounds. Any other glyph gets the class the table stores for it.That stored class comes back as it is, with no check against the table's class count.
StateTable::entryanswersNonefor a class at or past the count, so a font that classes a glyph too high leaves the choice to you. The engine's own shaping reads such a class as out of bounds, class 1.The end of the text is not a glyph, so there is nothing to look up for it. When your machine runs out of glyphs, hand it
raw::format::class::END_OF_TEXTyourself.use daegun::raw::format::{class, StateTable}; use daegun::Tag; // The state table of TestMORXFourtyone.ttf's ligature subtable, 60 bytes into morx. let morx = font.table(Tag::new(b"morx")).expect("an AAT font"); let table = StateTable::parse(&morx[60..], 1, font.glyph_count())?; // The font joins a and c, and b and c, so each of the three letters has a class of its own. let letters = ['a', 'b', 'c'].map(|ch| table.class(font.glyph_id(ch).expect("a letter").0)); assert_eq!(letters, [4, 5, 6]); // The space is not in the class table, so it is out of bounds: class 1. let space = font.glyph_id(' ').expect("a space"); assert_eq!(table.class(space.0), 1); // The mark of a deleted glyph has a class of its own. assert_eq!(table.class(0xFFFF), class::DELETED_GLYPH);raw::format::StateTable::entrypub fn entry(&self, state: u16, klass: u16) -> Option<Entry>The entry for a class in a state: where the machine goes next and what it does on the way.
The state array has a row for each state and a cell for each class, and each cell is the index of an entry in the entry table. The call reads the cell for
stateandklassand returns theEntryit points to.An entry in the font is its new state and its flags, 4 bytes, followed by the
extra_wordswords given toStateTable::parse, so entryistartsi * (4 + 2 * extra_words)bytes into the entry table. The first extra word comes back inword1and the second inword2. A table parsed with fewer leaves the rest 0, and words past the second are stepped over, not returned.Nonemeans there is nothing to read:klassis at or past the table's class count, the row of the state lies past the end of the bytes, or the entry does. The call does not know how many states the table has. A state number past the last real row reads whatever bytes follow the state array as a row, while there are bytes to read. So take a state only fromraw::format::state::START_OF_TEXTor from thenew_stateof an entry you were given.What the flags and the extra words mean is set by the kind of subtable, not by the state table. In every kind the engine runs, flag 0x4000 asks the machine to stay on the current glyph and not move to the next.
use daegun::raw::format::{state, Entry, StateTable}; use daegun::Tag; // The state table of TestMORXFourtyone.ttf's ligature subtable, 60 bytes into morx. A ligature // entry has 1 extra word. let morx = font.table(Tag::new(b"morx")).expect("an AAT font"); let table = StateTable::parse(&morx[60..], 1, font.glyph_count())?; // Walk "ac", which the font joins into one glyph, from the start state. let mut current = state::START_OF_TEXT; let mut entries = Vec::new(); for ch in "ac".chars() { let glyph = font.glyph_id(ch).expect("a letter"); let entry = table.entry(current, table.class(glyph.0)).expect("an entry for this class"); current = entry.new_state; entries.push(entry); } // In a ligature subtable flag 0x8000 remembers the glyph and 0x2000 runs the ligature action that // word1 indexes. The a is remembered. The c is remembered too, then joined with it by action 0. assert_eq!(entries[0], Entry { new_state: 0, flags: 0x8000, word1: 0, word2: 0 }); assert_eq!(entries[1], Entry { new_state: 0, flags: 0xA000, word1: 0, word2: 0 }); // The table has 7 classes, 0 to 6, so class 7 has no entry. assert_eq!(table.entry(state::START_OF_TEXT, 7), None);raw::format::StateTable::parsepub fn parse(data: &'a [u8], extra_words: usize, num_glyphs: u32) -> Result<Self, Error>Reads the state table that starts at the first byte of
data.databegins at the table's header, which in amorxorkerxsubtable of a kind that runs a machine is the first thing in the subtable's body, right after the subtable's own header. The header is four 32-bit words: the number of classes, then the offsets of the class table, the state array and the entry table, each counted from the start ofdata. Sodatahas to reach the end of the state table, and may run on past it. The result borrowsdata.extra_wordsis how many 16-bit words each entry carries after its new state and its flags. The table does not record that: it follows from the kind of subtable. Inmorxit is 0 for a rearrangement subtable, 1 for a ligature subtable and 2 for a contextual or an insertion one. Inkerxit is 1, for formats 1 and 4. Any number above 2 parses too, its words past the second stepped over. With the wrong number the entries are read from the wrong places.num_glyphsis the font's glyph count, fromFont::glyph_count, which bounds a class table stored as a lookup of format 0.An error of kind
ErrorKind::Malformedmeansdatais shorter than the 16 bytes of the header, the header names no classes or more than 65,535, or one of its three offsets points past the end ofdata. The class table is aLookup, read asLookup::parsereads one, and its errors come through:ErrorKind::Malformedwhere fewer than two bytes are left for it, andErrorKind::Unsupportedfor a format that is not a lookup format.ErrorKind::InvalidArgumentmeansextra_wordsis so large that an entry's size can't be counted, far past anything a real table uses.The state array and the entry table are not checked beyond where they start. A state or an entry that lies past the bytes reads as
NonefromStateTable::entry.use daegun::raw::format::StateTable; use daegun::{ErrorKind, Tag}; // TestMORXFourtyone.ttf has one morx subtable, a ligature subtable. Its body starts 60 bytes into // morx and opens with the state table. A ligature entry has 1 extra word. let morx = font.table(Tag::new(b"morx")).expect("an AAT font"); let table = StateTable::parse(&morx[60..], 1, font.glyph_count())?; // Ten bytes can't hold the 16-byte header. let cut = StateTable::parse(&morx[60..70], 1, font.glyph_count()); assert_eq!(cut.unwrap_err().kind(), ErrorKind::Malformed);
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::imagepub fn image(&self) -> Image<'_>The bitmap as an
Image: the same view of pixels a rasterizer lends, borrowed from the bitmap.It copies nothing. The image has the fields of the bitmap and a stride of
width * channels, and it gives youImage::rowto read the pixels a row at a time. Code written to take anImagethen works on a lent image and on a kept one alike.use daegun::raster::{Bitmap, Image, RasterOptions, Rasterizer}; use daegun::Location; // Written once for both: an image a rasterizer lends, and a bitmap you kept. fn ink(image: Image) -> u32 { (0..image.height).flat_map(|y| image.row(y)).map(|&coverage| u32::from(coverage)).sum() } let mut rasterizer = Rasterizer::new(); let glyph = font.glyph_id('g').expect("the font maps g"); let lent = rasterizer.glyph(&font, glyph, &Location::default(), 20.0, &RasterOptions::DEFAULT)?; let lent_ink = ink(lent); let bitmap: Bitmap = lent.to_bitmap(); let image = bitmap.image(); assert_eq!(ink(image), lent_ink); assert_eq!(image.stride, bitmap.width as usize);raster::Image::rowpub fn row(&self, y: u32) -> &[u8]The bytes of one row of the image, row 0 being the top one.
A row is
width * channelsbytes: the stride is taken care of, so any padding between rows is left out. Ayat or pastheightgives an empty slice, not a panic, and so does a row that the pixels of the image are too short to hold.use daegun::raster::{RasterOptions, Rasterizer}; use daegun::Location; let mut rasterizer = Rasterizer::new(); let glyph = font.glyph_id('g').expect("the font maps g"); let image = rasterizer.glyph(&font, glyph, &Location::default(), 20.0, &RasterOptions::DEFAULT)?; let mut ink = 0u32; for y in 0..image.height { // One byte of coverage a pixel here, so a row is `image.width` bytes. let row = image.row(y); ink += row.iter().map(|&coverage| u32::from(coverage)).sum::<u32>(); } // Past the last row there is nothing. assert!(image.row(image.height).is_empty());raster::Image::to_bitmappub fn to_bitmap(self) -> BitmapCopies the image into a
Bitmapthat owns its pixels.A lent image is gone at the rasterizer's next call. This is how you keep one: for a glyph cache of your own, to draw another glyph before you are done with this one, or to send the pixels to another thread. The copy has the same
left,top, size and channels, and its rows are packed one after another with no padding. It allocates once, for the pixels.use daegun::raster::{Bitmap, RasterOptions, Rasterizer}; use daegun::Location; let mut rasterizer = Rasterizer::new(); let (at, options) = (Location::default(), RasterOptions::DEFAULT); let mut kept: Vec<Bitmap> = Vec::new(); for letter in ['a', 'b'] { let glyph = font.glyph_id(letter).expect("the font maps it"); // The lent image ends at the next draw, so copy out what you keep. kept.push(rasterizer.glyph(&font, glyph, &at, 16.0, &options)?.to_bitmap()); } // Both are still here, each with its rows packed. assert_eq!(kept.len(), 2); assert_eq!(kept[0].pixels.len(), (kept[0].width * kept[0].height) as usize);raster::Rasterizer::color_glyphpub fn color_glyph( &mut self, font: &Font, glyph: GlyphId, location: &Location, px: f32, options: &RasterOptions, scene: &SceneOptions, ) -> Result<Option<Image<'_>>>Draws a color glyph from the font's
COLRtable and lends it as RGBA pixels, or givesNonefor a glyph the table does not describe.A
COLRglyph is a small picture: shapes filled with colors and gradients, stacked and blended. This call draws it atpxpixels to the em and lends anImageplaced byleftandtopfrom the glyph's origin, asRasterizer::glyphplaces one. The image is the box of what the glyph paints, cut to its clip box where the font gives it one.A pixel is four bytes, in the order red, green, blue, alpha. The colors are sRGB levels already multiplied by the alpha, so no color byte is above its alpha byte, and a pixel the glyph leaves empty is four zeros. The layers are blended in linear light before they are encoded. The result is ready for a source-over blend of premultiplied pixels:
out = src + dst * (255 - alpha) / 255on each byte.sceneis aSceneOptions: which of the palettes of the font to take colors from, and the foreground color, the color of the text, which a glyph may ask for in place of a palette entry.SceneOptions::DEFAULTis palette 0 and opaque black.Nonemeans the font has no color description for the glyph: an ordinary glyph, whichRasterizer::glyphdraws, a glyph id past the count of the font, or any glyph of a font that keeps its color as bitmaps and has noCOLRtable. A color glyph that paints nothing, such as a space in a color font, isSomeimage with a width and height of 0.Of the options, the transform and the oblique of the outline's and the offset apply. A subpixel layout, hinting, a stroke or an embolden above 0 is an
ErrorKind::InvalidArgumenterror, as is a transform, oblique or offset that is not finite, and apxthat is not finite and above 0, which is checked for every glyph.RasterOptions::darkenandRasterOptions::gammaare not read.ErrorKind::LimitExceededcomes for an image pastMAX_SIDEorMAX_DRAW_BYTES, where every layer the glyph stacks counts toward the bytes, and for a glyph whose composing would pass over each pixel more than 1,024 times on top of a fixed allowance, far more than a real font asks for.Rasterizer::color_glyph_intodraws one of any size. A glyph whose paints do not read fails as it does inFont::color_scene.With a budget on the font's
Cache::Raster, the image is kept there under the glyph, location, size, options, palette and foreground, and lent again for the same request.use daegun::color::SceneOptions; use daegun::raster::{RasterOptions, Rasterizer}; use daegun::Location; let mut rasterizer = Rasterizer::new(); let glyph = font.glyph_id('A').expect("the font maps A"); let (at, options) = (Location::default(), RasterOptions::DEFAULT); match rasterizer.color_glyph(&font, glyph, &at, 16.0, &options, &SceneOptions::DEFAULT)? { Some(image) => { // Four bytes a pixel: red, green, blue and alpha, the colors already multiplied by alpha. assert_eq!(image.channels, 4); for y in 0..image.height { for pixel in image.row(y).chunks_exact(4) { let (red, green, blue, alpha) = (pixel[0], pixel[1], pixel[2], pixel[3]); // Blend it over your canvas here. } } // Bungee Tint's A at 16 px is 11 by 12 pixels, and the fourth pixel of row 1 is an opaque red. } // Not a color glyph: draw its outline with `Rasterizer::glyph`. None => {} }raster::Rasterizer::color_glyph_intopub fn color_glyph_into( &mut self, font: &Font, glyph: GlyphId, location: &Location, px: f32, options: &RasterOptions, scene: &SceneOptions, target: Target<'_>, ) -> Result<bool>Draws a color glyph as
Rasterizer::color_glyphdoes, straight into RGBA pixels you own, whatever their size.The
Targetis read as four bytes a pixel, red, green, blue and alpha, premultiplied as in the lent image. Itsleftandtopsay where its rectangle lies from the origin of the glyph: aleftof-oxand atopofoyput the origin at columnoxof rowoy.Ok(true)means the glyph was drawn. Every pixel of the rectangle is then written, the picture where it falls inside and four zeros, fully transparent, everywhere else. What the pixels held is replaced, not blended with, so draw into a buffer of its own and composite that.Ok(false)means the font has no color description for the glyph, and the target is left as it was. A target with a width or height of 0 is fine: nothing is written, and the answer still says whether the glyph has color.ErrorKind::InvalidArgumentcomes for a target whose pixels do not hold its rows, which means a stride shorter thanwidth * 4or a slice shorter than(height - 1) * stride + width * 4, and for the options and sizesRasterizer::color_glyphrefuses. Its limits on the size of an image do not apply here, as the picture is worked out a band of rows at a time. An error that comes while the bands are drawn, such as theErrorKind::LimitExceededof a glyph too heavy to compose, can leave some rows written.The call never reads or fills the font's
Cache::Raster.use daegun::color::SceneOptions; use daegun::raster::{RasterOptions, Rasterizer, Target}; use daegun::Location; let mut rasterizer = Rasterizer::new(); let glyph = font.glyph_id('A').expect("the font maps A"); let (at, options, scene) = (Location::default(), RasterOptions::DEFAULT, SceneOptions::DEFAULT); // 16 by 16 pixels of RGBA, with the glyph's origin at column 2 of row 14. let (width, height) = (16, 16); let mut pixels = vec![0u8; width * height * 4]; let target = Target::new(-2, 14, width as u32, height as u32, width * 4, &mut pixels); if rasterizer.color_glyph_into(&font, glyph, &at, 16.0, &options, &scene, target)? { // `pixels` holds the picture, transparent where the glyph paints nothing. } else { // Not a color glyph, and `pixels` is untouched: draw its outline with `Rasterizer::glyph_into`. }raster::Rasterizer::distance_fieldpub fn distance_field( &mut self, font: &Font, glyph: GlyphId, location: &Location, px: f32, field: Field, ) -> Result<Image<'_>>Draws a glyph as a distance field: an image whose every pixel holds how far its center is from the glyph's outline.
A distance field is what a GPU text renderer keeps in its atlas in place of coverage. A shader reads the distance, smoothly interpolated between pixels, and turns it into an edge at whatever size the text is drawn, so one image serves many sizes, and outlines and glows come from the same data.
Fieldpicks the kind:Field::Sdfis one byte a pixel, andField::Msdfis three, whose median is the distance, which keeps corners sharp when the image is scaled up.The distance is measured in pixels from the center of each pixel to the nearest point of the outline, positive inside the glyph and negative outside. It is stored as
127.5 + 127.5 * distance / spread, rounded to a byte and kept within 0 to 255. So the outline lies where the value crosses from 127 to 128, a pixelspreadpixels or more inside reads 255, and onespreador more outside reads 0. The image reachesspreadpixels past the outline on every side, and itsleftandtopplace it from the glyph's origin as those ofRasterizer::glyphdo.The glyph is drawn as the font holds it, at
pxpixels to the em with its origin on a pixel corner. The call takes noRasterOptions: no hinting, no offset, no transform. A largerpxgives a finer field, andspreadis in pixels of this image, so it scales with the image when a shader draws it at another size.A glyph with no outline gives an image with a width and height of 0.
ErrorKind::InvalidArgumentcomes for apxor a spread that is not finite and above 0, andErrorKind::NoOutlinefor a glyph id past the count of the font and for any glyph of a font with no outlines, such as an emoji font made of bitmaps.ErrorKind::LimitExceededcomes for an image pastMAX_SIDEon a side, for one whose working memory would passMAX_DRAW_BYTES, which a multi-channel field reaches at a far smaller size than a single-channel one, and for an outline whose pieces cross or touch each other more than 64 times a piece, as a crafted glyph can. A glyph whose data does not decode fails as it does inFont::prepared_outline.The image is lent until the rasterizer's next call. With a budget on the font's
Cache::Rasterit is kept there under the glyph, location, size, kind and spread.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 field = Field::Sdf { spread: 4.0 }; let image = rasterizer.distance_field(&font, glyph, &Location::default(), 128.0, field)?; // One byte a pixel. Across the middle of Inter's I it climbs from 8, well outside the stem, through // 104 and 135 on either side of its edge, to 255 inside it. let row = image.row(image.height / 2); assert_eq!(row[..9], [8, 40, 72, 104, 135, 167, 199, 231, 255]); // The field reaches 4 pixels past the glyph's coverage on every side. let field = image.to_bitmap(); let glyph_image = rasterizer.glyph(&font, glyph, &Location::default(), 128.0, &Default::default())?; assert_eq!((field.left, field.top), (glyph_image.left - 4, glyph_image.top + 4)); assert_eq!((field.width, field.height), (glyph_image.width + 8, glyph_image.height + 8));raster::Rasterizer::glyphpub fn glyph( &mut self, font: &Font, glyph: GlyphId, location: &Location, px: f32, options: &RasterOptions, ) -> Result<Image<'_>>Draws one glyph at a pixel size and lends the image: a byte of coverage for each pixel, placed from the glyph's origin.
The call most drawing starts from.
fontandglyphsay what to draw, the glyph id coming fromFont::glyph_idor from a shaped run.locationpicks the instance of a variable font,&Location::default()being the default one.pxis the size in pixels to the em.optionssay how, and&RasterOptions::DEFAULTgives plain coverage: no hinting, the origin on a pixel corner, one byte a pixel.The
Imagethat comes back holds only the pixels the glyph touches, and itsleftandtopsay where they go. Both are measured from the glyph's origin, the point on the baseline where the pen stands. The left edge of the image isleftpixels to the right of the origin, and its top edge istoppixels above it.topcounts upward, so a letter whose lowest point is on the baseline, as an L's is, has atopequal to its height, and one that reaches below the line, as a g or an o does, has atopsmaller than its height. The rows themselves run down from the top, as on a screen. With the pen at(pen_x, baseline_y)on a canvas whose y grows downward, pixel(x, y)of the image belongs at(pen_x + left + x, baseline_y - top + y). How far the pen moves afterward is not here: that is the glyph's advance, which shaping gives.Each pixel is one byte, 0 where the glyph covers none of the pixel and 255 where it covers all of it. Rows come top first and are
widthbytes each, and in an image this call lends the stride is the same, with no padding between rows. Under a subpixel layout set byRasterOptions::with_layouta pixel is three bytes, for red, green and blue, and the image grows on each side by the pixels ofSubpixelLayout::pad.The image is lent. It borrows the rasterizer and is valid until the rasterizer's next call, so copy what you keep:
Image::to_bitmapgives aBitmapyou own.A glyph with no outline, such as a space, is not an error. You get an image with a width and height of 0 and no pixels. The errors are these.
ErrorKind::NoOutlinefor a glyph id past the count of the font, and for any glyph of a font with no outlines at all, such as an emoji font made of bitmaps.ErrorKind::InvalidArgumentfor apxthat is 0, negative or not finite, and for options that hold a value that is not finite.ErrorKind::LimitExceededfor an image wider or taller thanMAX_SIDEpixels or lying more than 2^31 pixels from the origin, for one whose drawing would hold more thanMAX_DRAW_BYTESbytes, and for an outline so tangled that resolving its overlaps would take more than 2^27 passes over a pixel, plus 512 for each point and 8 for each pixel.Rasterizer::glyph_intodraws a glyph of any size. Options whose transform, stroke or embolden take a point or an advance past the range off32fail withErrorKind::InvalidArgumentorErrorKind::Overflow, by where it is caught. A glyph whose data does not decode fails as it does inFont::prepared_outline.The first draw of a glyph decodes its outline and works out where its contours overlap. The rasterizer keeps both, under the budget of
Rasterizer::set_cache_budget, so later draws of that glyph at any size start from there. The drawn image is not kept unless theCache::Rasterof the font has a budget. With one, a call with the same glyph, location, size and options is lent the image from that cache in place of drawing it again.use daegun::raster::{RasterOptions, Rasterizer}; use daegun::Location; let mut rasterizer = Rasterizer::new(); let glyph = font.glyph_id('g').expect("the font maps g"); let image = rasterizer.glyph(&font, glyph, &Location::default(), 20.0, &RasterOptions::DEFAULT)?; // Inter's g at 20 px is 10 by 17 pixels. Its left edge is 1 pixel right of the origin and its top // edge 12 pixels above the baseline, so its last 5 rows hang below the line. assert_eq!((image.left, image.top, image.width, image.height), (1, 12, 10, 17)); // Copy it to a canvas whose y grows downward, with the pen at column 4 of the baseline on row 16. let (pen_x, baseline_y, canvas_width) = (4, 16, 24); let mut canvas = vec![0u8; canvas_width * 24]; for y in 0..image.height { let row = image.row(y); // one byte a pixel: 0 is empty, 255 fully covered let line = (baseline_y - image.top + y as i32) as usize; let start = line * canvas_width + (pen_x + image.left) as usize; canvas[start..start + row.len()].copy_from_slice(row); }raster::Rasterizer::glyph_intopub fn glyph_into( &mut self, font: &Font, glyph: GlyphId, location: &Location, px: f32, options: &RasterOptions, mut target: Target<'_>, ) -> Result<()>Draws a glyph as
Rasterizer::glyphdoes, straight into pixels you own, whatever their size.The
Targetnames a rectangle of pixels and says where it lies from the origin of the glyph, the way an image'sleftandtopdo. To put the origin at columnoxand rowoyof your pixels, counting rows down from the top, pass aleftof-oxand atopofoy.Every pixel of that rectangle is written: the coverage of the glyph where it falls inside, and 0 everywhere else. What the pixels held before is replaced, not added to or blended with, so a target is a place for one glyph. To set several glyphs into one canvas, draw each into its own stretch of it or combine lent images yourself, as the example for
Rasterizerdoes. The part of the glyph outside the rectangle is cut off. Where the stride is longer than the width, the bytes of each row past the width are left alone. A target with a width or height of 0 is fine, and nothing is drawn.It is one byte of coverage a pixel, so options with a subpixel layout are an
ErrorKind::InvalidArgumenterror. So is a target whose pixels do not hold its rows: a stride shorter than the width, or a slice shorter than(height - 1) * stride + width. The other options apply as they do inRasterizer::glyph, the offset, darkening and gamma included.The other errors are those of
Rasterizer::glyph, without the two limits on size: the outline is cut to the target, then worked out a band of rows at a time, soMAX_SIDEandMAX_DRAW_BYTESdo not apply. An error leaves the target as it was, with one exception: an outline too tangled for its overlaps to be resolved, theErrorKind::LimitExceededofRasterizer::path, can stop partway and leave some rows written.The call places the outline in
f64, whereRasterizer::glyphusesf32, so a byte can differ from the lent image's by one level. It keeps what it learns of the glyph as that call does, but never reads or fills the font'sCache::Raster.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"); // 16 by 24 pixels, with the glyph's origin at column 2 of row 16. let (width, height) = (16, 24); let mut pixels = vec![0u8; width * height]; let target = Target::new(-2, 16, width as u32, height as u32, width, &mut pixels); rasterizer.glyph_into(&font, glyph, &Location::default(), 20.0, &RasterOptions::DEFAULT, target)?; // Inter's g at 20 px now fills columns 3 to 12 of rows 4 to 20, and every other pixel is 0.raster::Rasterizer::newpub fn new() -> RasterizerA new rasterizer, with nothing drawn and nothing learned yet.
The same as
Rasterizer::default(). It takes no settings: what to draw and how goes to each call, the how in aRasterOptions. Make one and keep it, as its buffers and what it has learned of each glyph are what make later draws cheap.use daegun::raster::{RasterOptions, Rasterizer}; use daegun::Location; let mut rasterizer = Rasterizer::new(); for letter in ['a', 'b', 'c'] { let glyph = font.glyph_id(letter).expect("the font maps it"); let image = rasterizer.glyph(&font, glyph, &Location::default(), 16.0, &RasterOptions::DEFAULT)?; // Use the image here: the next draw takes its place. }raster::Rasterizer::pathpub fn path(&mut self, path: &Path, rule: FillRule, transform: Option<&[f64; 6]>) -> Result<Image<'_>>Fills a
Pathyou built and lends its coverage, a byte for each pixel.The path is read in pixels with y up, and the image comes back placed from the origin of the path, point (0, 0): its
leftis how far right of the origin its left edge lies and itstophow far above. One unit of the path is one pixel unless you pass atransform.transformis a 2 by 3 matrix[a, b, c, d, dx, dy]applied to every point first:x = a * px + c * py + dxandy = b * px + d * py + dy. A path in font units is drawn at a pixel size by[s, 0.0, 0.0, s, 0.0, 0.0], withsthe size over the units per em of the font.rulesays what counts as inside. UnderFillRule::NonZeroa place that two contours wound the same way both cover is filled, and filled once: its coverage is that of the two shapes joined, not their sum. UnderFillRule::EvenOddit is a hole, and two contours wound opposite ways leave a hole under either rule. A contour left open is closed with a straight line. An empty path, or one whose contours have fewer than three distinct points, gives an image with a width and height of 0.The coverage is plain: this call takes no
RasterOptions, and nothing is cached.ErrorKind::InvalidArgumentcomes for a point that is not finite once transformed.ErrorKind::LimitExceededcomes for an image pastMAX_SIDEon a side or lying more than 2^31 pixels from the origin, for a draw that would hold more thanMAX_DRAW_BYTESbytes, the points of the path counted in, and for a path so tangled that resolving its overlaps would take more work than the call allows: 2^27 passes over a pixel, plus 512 for each point and 8 for each pixel.Rasterizer::path_intodraws an image past the two limits on size.use daegun::outline::{FillRule, OutlinePen, Path}; use daegun::raster::Rasterizer; // A rectangle 4 pixels wide and 3 tall, with y up. let mut path = Path::new(); path.move_to(0.0, 0.0); path.line_to(4.0, 0.0); path.line_to(4.0, 3.0); path.line_to(0.0, 3.0); path.close(); let mut rasterizer = Rasterizer::new(); let image = rasterizer.path(&path, FillRule::NonZero, None)?; // 4 by 3 pixels, each fully covered, the top edge 3 pixels above the path's origin. assert_eq!((image.left, image.top, image.width, image.height), (0, 3, 4, 3)); assert!(image.pixels.iter().all(|&coverage| coverage == 255)); // Moved half a pixel right and up, it covers half of each pixel along its edges and a quarter of // each corner. let moved = rasterizer.path(&path, FillRule::NonZero, Some(&[1.0, 0.0, 0.0, 1.0, 0.5, 0.5]))?; assert_eq!(moved.row(0), [64, 128, 128, 128, 64]); assert_eq!(moved.row(1), [128, 255, 255, 255, 128]);raster::Rasterizer::path_intopub fn path_into( &mut self, path: &Path, rule: FillRule, transform: Option<&[f64; 6]>, mut target: Target<'_>, ) -> Result<()>Fills a
PathasRasterizer::pathdoes, straight into pixels you own, whatever their size.The
Targetnames a rectangle of pixels, one byte each, and says where it lies from the origin of the path: aleftof-oxand atopofoyput the origin at columnoxof rowoy, counting rows down from the top.transformandrulemean what they mean inRasterizer::path.Every pixel of the rectangle is written: the coverage of the path where it falls inside, and 0 elsewhere. What the pixels held is replaced, not added to. The part of the path outside the rectangle is cut off, and it may reach as far out as it likes: the path is cut to the target first, then worked out a band of rows at a time, so neither
MAX_SIDEnorMAX_DRAW_BYTESapplies. A target with a width or height of 0 is fine, and nothing is drawn.ErrorKind::InvalidArgumentcomes for a target whose pixels do not hold its rows, a stride shorter than the width or a slice shorter than(height - 1) * stride + width, and for a point that is not finite once transformed. Both leave the target as it was.ErrorKind::LimitExceededcomes for a path too tangled for its overlaps to be resolved within the work the call allows, and can leave some rows written.use daegun::outline::{FillRule, OutlinePen, Path}; use daegun::raster::{Rasterizer, Target}; // A triangle with its corners at (1, 1), (7, 1) and (4, 5), in pixels with y up. let mut path = Path::new(); path.move_to(1.0, 1.0); path.line_to(7.0, 1.0); path.line_to(4.0, 5.0); path.close(); // 8 by 6 pixels with the path's origin at the bottom left corner: column 0 of row 6. let (width, height) = (8, 6); let mut pixels = vec![0u8; width * height]; let target = Target::new(0, 6, width as u32, height as u32, width, &mut pixels); let mut rasterizer = Rasterizer::new(); rasterizer.path_into(&path, FillRule::NonZero, None, target)?; // The first row, above the triangle's tip, is empty, and the row its base stands on is full between // its slanted sides. assert_eq!(pixels[..width], [0; 8]); assert_eq!(pixels[4 * width + 3..4 * width + 5], [255, 255]);raster::Rasterizer::set_cache_budgetpub fn set_cache_budget(&mut self, bytes: usize)Sets how many bytes of learned glyph outlines the rasterizer may keep.
What this budget bounds is not drawn images. The first time a rasterizer draws a glyph of a font at a location, it decodes the outline in font units and works out whether its contours overlap, removing the overlaps where it can. It keeps both, so every later draw of that glyph, at any size, skips the decoding and the overlap work. That is what the budget holds, across all the fonts the rasterizer has drawn.
The default is 4 MiB, room for several thousand glyphs. Past the budget the glyphs drawn least recently are let go, whichever font they belong to, and a lower budget applies at once. A budget of 0 keeps nothing: each draw learns its glyph again, and the pixels are the same either way.
Drawn images are kept by another cache, which belongs to the font:
Cache::Raster. It is off, at a budget of 0, untilFont::set_cache_budgetgives it one, and a budget of 0 set later empties it and turns it off again. With a budget,Rasterizer::glyph,Rasterizer::color_glyphandRasterizer::distance_fieldeach keep the image they draw, under the glyph, the location, the size and every option that changes the pixels, and lend it again for the same request in place of drawing, whichever rasterizer asks. The_intocalls andRasterizer::pathdo not use it.use daegun::raster::{RasterOptions, Rasterizer}; use daegun::{Cache, Location}; let mut rasterizer = Rasterizer::new(); // A megabyte for the outlines it learns. rasterizer.set_cache_budget(1 << 20); let glyph = font.glyph_id('g').expect("the font maps g"); let (at, options) = (Location::default(), RasterOptions::DEFAULT); let kept = rasterizer.glyph(&font, glyph, &at, 20.0, &options)?.to_bitmap(); // A budget of 0 changes the work, never the pixels. rasterizer.set_cache_budget(0); assert_eq!(rasterizer.glyph(&font, glyph, &at, 20.0, &options)?.to_bitmap(), kept); // Drawn images are the font's to keep, and it keeps none until its raster cache has a budget. assert_eq!(font.cache_stats(Cache::Raster).entries, 0); font.set_cache_budget(Cache::Raster, 1 << 20); rasterizer.glyph(&font, glyph, &at, 20.0, &options)?; rasterizer.glyph(&font, glyph, &at, 20.0, &options)?; // Two draws of one request left one image, and the second was lent from the cache. assert_eq!(font.cache_stats(Cache::Raster).entries, 1);raster::RasterOptions::with_darkenpub const fn with_darken(mut self, darken: bool) -> SelfThese options with stem darkening on or off: thin stems widened at small sizes, so small text does not read too light.
A stem thinner than a pixel can never fill one, so small text drawn exactly looks gray and spindly. Darkening thickens the whole glyph a little to make up for it. How much depends on how wide the stems of the font are in pixels at this size: 0.4 pixels for a stem of half a pixel or less, falling evenly to 0.275 pixels for a stem of one pixel, 0.275 from there to a stem of 1⅔ pixels, then falling evenly to nothing at 2⅓ pixels. From there on the option changes nothing, so it is safe to leave on at every size.
The stem is measured once for each font and location: the width of the lowercase
lacross the middle of its height, or of the capitalIwhere the font has nolthat draws, or 0.075 em where it has neither. Inter measures 180 units of its 2048, so its text is darkened below 26.55 px.The glyph is thickened as an embolden in the
OutlineOptionsthickens it, by that many pixels, added to any embolden the options already ask for. A stroked glyph is not darkened, andRasterizer::color_glyphandRasterizer::distance_fielddo not read the option.use daegun::raster::{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 darkened = RasterOptions::DEFAULT.with_darken(true); // At 10 px Inter's stem is under a pixel wide. Across the middle of the l, plain coverage adds up to // 0.88 of a pixel, and darkened to 1.18. let plain = rasterizer.glyph(&font, glyph, &at, 10.0, &RasterOptions::DEFAULT)?; assert_eq!(plain.row(4), [58, 166]); let dark = rasterizer.glyph(&font, glyph, &at, 10.0, &darkened)?; assert_eq!(dark.row(4), [97, 205]); // At 40 px the stem is over 3 pixels wide, and the option changes nothing. let large = rasterizer.glyph(&font, glyph, &at, 40.0, &RasterOptions::DEFAULT)?.to_bitmap(); assert_eq!(rasterizer.glyph(&font, glyph, &at, 40.0, &darkened)?.to_bitmap(), large);raster::RasterOptions::with_gammapub const fn with_gamma(mut self, gamma: Gamma) -> SelfThese options with how coverage becomes the alpha you blend with: as it is, or corrected for a compositor that blends sRGB values.
Coverage is a share of area, and it is only right to blend with as it stands if the blend happens in linear light. Most simple compositors blend the sRGB bytes directly, which makes dark text on a light ground heavier than it should be and light text on a dark ground thinner.
Gamma::Srgbfixes the bytes for such a compositor, given the color of the text.Gamma::Linear, the default, leaves coverage as it is.The difference is large in the middle of the range. A pixel half covered is 128 as coverage. Under
Gamma::Srgbwith no contrast it becomes 68 for black text and 188 for white text. A pixel not covered stays 0 and one fully covered stays 255.The correction is applied to the image after it is drawn, in
Rasterizer::glyphandRasterizer::glyph_into. The gamma is part of what keys an image in theCache::Rasterof a font, the text color included, so text of each color is an image of its own there.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 coverage = rasterizer.glyph(&font, glyph, &at, 12.0, &RasterOptions::DEFAULT)?.to_bitmap(); // One of the o's pixels is half covered. let half = coverage.pixels.iter().position(|&level| level == 128).expect("a pixel half covered"); // For black text blended in sRGB, that pixel's alpha is 68. let black = Gamma::Srgb { text: Rgba::opaque(0, 0, 0), contrast: 0.0 }; let alpha = rasterizer.glyph(&font, glyph, &at, 12.0, &RasterOptions::DEFAULT.with_gamma(black))?; assert_eq!(alpha.pixels[half], 68); // For white text it is 188. let white = Gamma::Srgb { text: Rgba::opaque(255, 255, 255), contrast: 0.0 }; let alpha = rasterizer.glyph(&font, glyph, &at, 12.0, &RasterOptions::DEFAULT.with_gamma(white))?; assert_eq!(alpha.pixels[half], 188);raster::RasterOptions::with_layoutpub const fn with_layout(mut self, layout: &'a SubpixelLayout) -> SelfThese options with a
SubpixelLayout, which says how many bytes a pixel has and how they are filtered.The default,
SubpixelLayout::grayscale, is one byte of coverage a pixel.SubpixelLayout::horizontalandSubpixelLayout::verticalare for a display whose pixels are three colored stripes: the glyph is sampled three times a pixel and filtered, and the image has three bytes a pixel, the coverage of the red, the green and the blue stripe, in that order whicheverStripeOrderthe display has. Blend each channel of the text color by its own byte.Such an image is larger than the gray one by the padding its filter needs,
SubpixelLayout::padpixels on each side, and itsleftandtopaccount for that. The options borrow the layout, so it has to outlive them.Only
Rasterizer::glyphdraws through a layout.Rasterizer::glyph_into,Rasterizer::color_glyphandRasterizer::color_glyph_intoanswerErrorKind::InvalidArgumentto options whose layout is not grayscale.use daegun::raster::{RasterOptions, Rasterizer, StripeOrder, SubpixelLayout}; use daegun::Location; let mut rasterizer = Rasterizer::new(); let glyph = font.glyph_id('l').expect("the font maps l"); let at = Location::default(); let gray = rasterizer.glyph(&font, glyph, &at, 20.0, &RasterOptions::DEFAULT)?.to_bitmap(); let layout = SubpixelLayout::horizontal(StripeOrder::Rgb); let options = RasterOptions::DEFAULT.with_layout(&layout); let striped = rasterizer.glyph(&font, glyph, &at, 20.0, &options)?; // Three bytes a pixel, and a pixel more on the left and on the right for the filter. assert_eq!((striped.channels, striped.stride), (3, 15)); assert_eq!((gray.left, gray.width), (1, 3)); assert_eq!((striped.left, striped.width), (0, 5));raster::RasterOptions::with_offsetpub const fn with_offset(mut self, x: f32, y: f32) -> SelfThese options with the glyph moved right by
xpixels and up byybefore it is drawn.A pen position rarely falls on a whole pixel. Pass its fraction here and place the image by its whole part, and text keeps the spacing shaping gave it in place of snapping every glyph to the pixel grid. The fraction changes the coverage, as the edges of the glyph now cross the pixels elsewhere.
Any finite value is taken, not only 0 to 1. A whole number of pixels moves the image by that much, adding to
left, and totopfory. Its bytes come out the same or a level apart, as the outline is placed inf32, and further apart as the offset grows, as much as 3 levels at 12,345 pixels, so pass the fraction alone. A value that is not finite makes the draw fail withErrorKind::InvalidArgument.The offset is part of what keys an image in the
Cache::Rasterof a font, so each distinct fraction is an image of its own there. Rounding the fraction to a few steps, quarters of a pixel for one, keeps that number down.use daegun::raster::{RasterOptions, Rasterizer}; use daegun::Location; let mut rasterizer = Rasterizer::new(); let glyph = font.glyph_id('g').expect("the font maps g"); let at = Location::default(); let plain = rasterizer.glyph(&font, glyph, &at, 20.0, &RasterOptions::DEFAULT)?.to_bitmap(); // Half a pixel to the right, the g spills into one more column. let half = RasterOptions::DEFAULT.with_offset(0.5, 0.0); let moved = rasterizer.glyph(&font, glyph, &at, 20.0, &half)?; assert_eq!((plain.width, moved.width), (10, 11)); // Whole pixels move the image, 3 right and 2 down. This g's bytes come out the same. let whole = RasterOptions::DEFAULT.with_offset(3.0, -2.0); let shifted = rasterizer.glyph(&font, glyph, &at, 20.0, &whole)?; assert_eq!((shifted.left, shifted.top), (plain.left + 3, plain.top - 2)); assert_eq!(shifted.pixels, plain.pixels);raster::RasterOptions::with_outlinepub const fn with_outline(mut self, outline: OutlineOptions) -> SelfThese options with the outline options: hinting, a transform, a stroke, an embolden or an oblique lean.
The
OutlineOptionsyou pass replace any set before. They are applied to the outline before it is filled and mean what they mean inFont::prepared_outline:HintModefits the outline to the pixel grid at this size, a transform moves or reshapes the glyph in font units, a stroke draws the outline as a line of a given width in place of filling it, an embolden thickens the glyph and an oblique leans it. The image comes back as large as the changed outline needs.An embolden makes an outline that overlaps itself, and so does a stroke wherever a corner is too tight for its width or two parts lie closer than it is wide. The rasterizer resolves that on every draw, so the coverage stays exact. A color glyph takes the transform and the oblique alone.
use daegun::outline::{OutlineOptions, StrokeStyle}; use daegun::raster::{RasterOptions, Rasterizer}; use daegun::Location; let mut rasterizer = Rasterizer::new(); let glyph = font.glyph_id('g').expect("the font maps g"); let at = Location::default(); let filled = rasterizer.glyph(&font, glyph, &at, 20.0, &RasterOptions::DEFAULT)?.to_bitmap(); // The same g drawn as a line 40 font units wide along its outline. let outline = OutlineOptions::DEFAULT.with_stroke(StrokeStyle::new(40.0)); let options = RasterOptions::DEFAULT.with_outline(outline); let stroked = rasterizer.glyph(&font, glyph, &at, 20.0, &options)?; // The line reaches past the outline, so the image is a pixel wider, and it holds under half the ink. assert_eq!((filled.width, stroked.width), (10, 11));raster::ShelfPacker::insertpub fn insert(&mut self, w: usize, h: usize) -> Option<Rect>Finds room for a rectangle of this width and height and takes it, or returns
Nonewhere it has none.The answer is a
Rect: where the rectangle goes, with thewandhyou passed.It looks at every open shelf for one that is at least
htall and haswleft across. Among those it takes the shortest, and the one opened first where two are equally short. The rectangle goes at the top of that shelf, right after what is already on it. A rectangle shorter than its shelf leaves the strip under it unused.Where no shelf will do, it opens a new one right below the last, as tall as the rectangle, and puts the rectangle at its left end. The first rectangle of all lands at the top left corner,
(0, 0).Nonecomes in three cases:worhis 0, the rectangle is wider or taller than the whole atlas, or the atlas is full for it, which means no open shelf can take it and a new shelf of its height would end below the bottom. ANonechanges nothing, so a smaller rectangle may still fit afterward. The packer never moves what it has placed to make room.A glyph with nothing to draw, such as a space, has an image 0 pixels wide and 0 tall. Skip those before you insert: the
Nonethey get doesn't mean the atlas is full.use daegun::raster::{Rect, ShelfPacker}; let mut packer = ShelfPacker::new(64, 32); // The first rectangle opens a shelf 10 tall at the top left corner. assert_eq!(packer.insert(20, 10), Some(Rect { x: 0, y: 0, w: 20, h: 10 })); // A taller one can't go on that shelf, so it opens the next shelf below. assert_eq!(packer.insert(30, 12), Some(Rect { x: 0, y: 10, w: 30, h: 12 })); // A shorter one fits both shelves and takes the shorter, to the right of what is there. assert_eq!(packer.insert(20, 8), Some(Rect { x: 20, y: 0, w: 20, h: 8 })); // Full for this one: no shelf has 50 left across, and a new shelf 12 tall would end below the atlas. assert_eq!(packer.insert(50, 12), None); // A smaller one still fits after that. assert_eq!(packer.insert(24, 10), Some(Rect { x: 40, y: 0, w: 24, h: 10 })); // None as well for an empty rectangle, and for one larger than the atlas. assert_eq!(packer.insert(0, 10), None); assert_eq!(packer.insert(65, 1), None);raster::ShelfPacker::newpub const fn new(width: usize, height: usize) -> ShelfPackerAn empty packer for an atlas of this width and height, in pixels.
The two numbers are all it takes. There is no padding or gutter to set, and the size cannot change later: a larger atlas is a new packer.
It is a
const fn, and it allocates nothing until the first rectangle goes in. A size of 0 either way gives a packer that never has room.use daegun::raster::ShelfPacker; // A 1024 by 1024 atlas. Its pixels are yours to allocate: one byte each for grayscale glyphs. let mut packer = ShelfPacker::new(1024, 1024); let atlas = vec![0u8; 1024 * 1024]; let first = packer.insert(12, 17).expect("an empty atlas has room"); assert_eq!((first.x, first.y), (0, 0));raster::ShelfPacker::resetpub fn reset(&mut self)Empties the atlas, keeping its size.
It forgets every rectangle and every shelf, so the next
ShelfPacker::insertstarts again at the top left corner. EveryRectit handed out before may be given out again, so forget which glyph was where, and clear the pixels if your renderer needs them clear.This is the way to reuse a full atlas, since no call frees a single rectangle.
use daegun::raster::{Rect, ShelfPacker}; let mut packer = ShelfPacker::new(64, 64); assert!(packer.insert(64, 64).is_some()); // Full now. assert_eq!(packer.insert(1, 1), None); packer.reset(); // Empty again, and the same size: the next rectangle starts at the top left corner. assert_eq!(packer.insert(10, 10), Some(Rect { x: 0, y: 0, w: 10, h: 10 }));raster::SubpixelLayout::channelspub const fn channels(&self) -> u8How many bytes each pixel of an image drawn with this layout has: 1 for grayscale, 3 for any other layout.
It is the
Image::channelsof whatRasterizer::glyphreturns with this layout. A row of an imagewidthpixels wide iswidth * channelsbytes, and an atlas for these glyphs needs that many bytes for each pixel.It is also how many channels
SubpixelLayout::weightshas.use daegun::raster::{RasterOptions, Rasterizer, StripeOrder, SubpixelLayout}; use daegun::Location; assert_eq!(SubpixelLayout::grayscale().channels(), 1); let lcd = SubpixelLayout::horizontal(StripeOrder::Rgb); assert_eq!(lcd.channels(), 3); let mut rasterizer = Rasterizer::new(); let g = font.glyph_id('g').expect("Inter maps g"); let options = RasterOptions::DEFAULT.with_layout(&lcd); let image = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?; assert_eq!(image.channels, lcd.channels()); // The bytes this glyph takes in an atlas: 12 by 17 pixels, three bytes each. let bytes = image.width as usize * image.height as usize * usize::from(lcd.channels()); assert_eq!(bytes, 12 * 17 * 3);raster::SubpixelLayout::from_weightspub fn from_weights( oversample: (u8, u8), taps: (u8, u8), origin: (i8, i8), weights: [&[f32]; 3], ) -> Result<Self>A layout from a filter you state yourself: the samples for each pixel, the size and place of the window, and the weights of each of three channels.
oversampleis how many samples the glyph is drawn at for each pixel, across and down, each from 1 toMAX_OVERSAMPLE.tapsis the size of the window of samples that every channel reads, across and down, each from 1 toMAX_TAPS.originis where the window starts, counted in samples from the first sample of the pixel, its top left one: a negative number starts the window that many samples to the left of it or above it, a positive one to the right of it or below.weightsholds one slice for each channel, in the order the bytes of a pixel come out, so red, green, blue for a display. Each slice has exactlytaps.0 * taps.1weights: the top row of the window first, each row from the left. A channel of a pixel is the sum, over its window, of the coverage of each sample times its weight, where a covered sample counts 255. The sum is rounded, and one above 255 comes out as 255.The weights are used as given, and nothing normalizes them. Make each channel sum to 1 for a fully covered window to come out as 255: a larger sum saturates early, and a smaller one never gets there. A weight may be negative, as in a filter that sharpens, and a sum below 0 comes out as 0.
The result always has three channels. Three equal slices give a gray image at three bytes a pixel, and
SubpixelLayout::is_grayscaleis false for it.It fails with
ErrorKind::InvalidArgumentwhere an oversample is 0 or aboveMAX_OVERSAMPLE, a tap count is 0 or aboveMAX_TAPS, a slice is not exactlytaps.0 * taps.1long, or a weight is NaN or infinite. Anyoriginis taken. One far from the pixel makesSubpixelLayout::padlarger, and with it every image.use daegun::raster::{RasterOptions, Rasterizer, SubpixelLayout}; use daegun::{ErrorKind, Location}; // RGB stripes side by side through a three-tap filter in place of the built-in five. Three samples // across a pixel, and a window of five that starts one sample left of the pixel. let red = [0.25, 0.5, 0.25, 0.0, 0.0]; let green = [0.0, 0.25, 0.5, 0.25, 0.0]; let blue = [0.0, 0.0, 0.25, 0.5, 0.25]; let layout = SubpixelLayout::from_weights((3, 1), (5, 1), (-1, 0), [&red, &green, &blue])?; assert_eq!((layout.channels(), layout.pad()), (3, (1, 0))); let mut rasterizer = Rasterizer::new(); let g = font.glyph_id('g').expect("Inter maps g"); let options = RasterOptions::DEFAULT.with_layout(&layout); let image = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?; assert_eq!((image.width, image.height, image.channels), (12, 17, 3)); // A slice that is not taps.0 * taps.1 long is refused. let short = [0.5, 0.5]; let refused = SubpixelLayout::from_weights((3, 1), (5, 1), (-1, 0), [&short, &green, &blue]); assert_eq!(refused.unwrap_err().kind(), ErrorKind::InvalidArgument);raster::SubpixelLayout::grayscalepub const fn grayscale() -> SelfThe plain layout: one sample and one byte of coverage for each pixel.
Each byte is the share of its pixel the glyph covers, from 0 for none of it to 255 for all of it, before any
Gammais applied. It suits any display in any rotation. It is whatRasterOptions::DEFAULTdraws with and whatSubpixelLayout::default()returns, and being aconst fnit can go in a constant.It is the only layout
Rasterizer::glyph_into,Rasterizer::color_glyphandRasterizer::color_glyph_intoaccept.use daegun::raster::{RasterOptions, Rasterizer, SubpixelLayout}; use daegun::Location; const GRAY: SubpixelLayout = SubpixelLayout::grayscale(); assert!(GRAY.is_grayscale()); assert_eq!((GRAY.channels(), GRAY.oversample(), GRAY.pad()), (1, (1, 1), (0, 0))); // The default options already carry it. assert_eq!(RasterOptions::DEFAULT.layout.key(), GRAY.key()); let mut rasterizer = Rasterizer::new(); let g = font.glyph_id('g').expect("Inter maps g"); let options = RasterOptions::DEFAULT.with_layout(&GRAY); let image = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?; // One byte a pixel: 10 by 17 pixels at 20 px, each row 10 bytes. assert_eq!((image.width, image.height, image.channels), (10, 17, 1)); assert_eq!(image.row(0).len(), 10);raster::SubpixelLayout::horizontalpub fn horizontal(order: StripeOrder) -> SelfThe layout for a display whose stripes sit side by side: three samples across each pixel, filtered to soften color fringes.
This is the layout for an LCD in its usual rotation. The glyph is drawn at three samples across each pixel and one down, so each sample is the coverage of one stripe.
ordersays which stripe is on the left.Giving each stripe its own sample and nothing else would color the edges of stems: an edge that covers the red stripe of a pixel and not the blue lights them unequally, and the eye sees a fringe. So each channel is a weighted sum of five samples centered on its own stripe, with the weights 8, 77, 86, 77 and 8 out of 256. That spreads each sample onto its neighbors and evens out the color, for slightly softer edges.
SubpixelLayout::unfilteredleaves the filter out.The filter reaches two samples past the pixel on each side, so
SubpixelLayout::padis(1, 0): the image is one pixel larger on the left and one on the right than the glyph's own box, and no taller. Each pixel is three bytes: red, green, blue.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 gray = rasterizer.glyph(&font, g, &Location::default(), 20.0, &RasterOptions::DEFAULT)?; let (left, width, height) = (gray.left, gray.width, gray.height); let lcd = SubpixelLayout::horizontal(StripeOrder::Rgb); let options = RasterOptions::DEFAULT.with_layout(&lcd); let image = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?; // Three bytes a pixel, and one pixel more than the grayscale image on the left and on the right. assert_eq!(image.channels, 3); assert_eq!((image.left, image.width, image.height), (left - 1, width + 2, height)); assert_eq!(image.row(0).len(), 3 * image.width as usize);raster::SubpixelLayout::is_grayscalepub const fn is_grayscale(&self) -> boolWhether the layout has one channel: a single byte of coverage for each pixel.
True for
SubpixelLayout::grayscalealone. Every other constructor gives three channels, andSubpixelLayout::from_weightsdoes too, even from three equal sets of weights.Rasterizer::glyph_into,Rasterizer::color_glyphandRasterizer::color_glyph_intorefuse a layout for which this is false withErrorKind::InvalidArgument, so test it before you take one of those paths.use daegun::raster::{RasterOptions, Rasterizer, StripeOrder, SubpixelLayout, Target}; use daegun::{ErrorKind, Location}; let gray = SubpixelLayout::grayscale(); let lcd = SubpixelLayout::horizontal(StripeOrder::Rgb); assert!(gray.is_grayscale()); assert!(!lcd.is_grayscale()); // Drawing into pixels of your own takes the grayscale layout only. let mut rasterizer = Rasterizer::new(); let g = font.glyph_id('g').expect("Inter maps g"); let mut pixels = vec![0u8; 16 * 24]; let target = Target::new(0, 16, 16, 24, 16, &mut pixels); let options = RasterOptions::DEFAULT.with_layout(&lcd); let refused = rasterizer.glyph_into(&font, g, &Location::default(), 20.0, &options, target); assert_eq!(refused.unwrap_err().kind(), ErrorKind::InvalidArgument);raster::SubpixelLayout::keypub const fn key(&self) -> u64The layout's identity as a 64-bit number, to go in a cache key.
It is a hash of everything that defines the layout: the oversampling, the taps, the origin, the number of channels and the bits of every weight. Two layouts built from the same parameters have the same key, and two that differ in any of them have different keys, short of a collision in 64 bits. Put it in the key of any cache or atlas of glyphs drawn through a layout, beside the font, the glyph and the size, so an image drawn for one layout is never served for another.
daegun does the same. The cache a font keeps under
Cache::Rasterfiles each image under the layout's key along with the other options, and==on twoRasterOptionscompares their layouts by key. So two layouts with the same key share their cached images: a glyph drawn through one is served for the other.The hash reads the parameters as they were given, not what they do. The same filter written another way is another layout to it: a window one tap wider with a zero weight added, or a weight of
-0.0in place of0.0, gets a key of its own. That costs a cache a second copy, never a wrong image.The key depends on the parameters alone, so a layout gets the same key each time it is built. Nothing in the engine says the number stays the same in a later release.
use daegun::raster::{StripeOrder, SubpixelLayout}; use std::collections::HashMap; let rgb = SubpixelLayout::horizontal(StripeOrder::Rgb); let bgr = SubpixelLayout::horizontal(StripeOrder::Bgr); // Built twice, the same key. Another stripe order, another key. assert_eq!(rgb.key(), SubpixelLayout::horizontal(StripeOrder::Rgb).key()); assert_ne!(rgb.key(), bgr.key()); // A glyph cache of your own, keyed by layout, glyph and size in pixels. let g = font.glyph_id('g').expect("Inter maps g"); let mut cache: HashMap<(u64, u32, u32), Vec<u8>> = HashMap::new(); cache.insert((rgb.key(), g.0, 20), Vec::new()); assert!(!cache.contains_key(&(bgr.key(), g.0, 20)));raster::SubpixelLayout::originpub const fn origin(&self) -> (i8, i8)Where the filter's window starts, in samples from the first sample of the pixel, across and down.
The first sample of a pixel is its top left one.
(0, 0)starts the window there, as in grayscale andSubpixelLayout::unfiltered. A negative number starts it before the pixel:(-2, 0)forSubpixelLayout::horizontalis two samples to the left, and(0, -2)forSubpixelLayout::verticalis two samples above. A positive number starts it to the right or below.So for the pixel in column
xof an image, counting sample columns from the first sample of the image's first pixel, the window coverstaps.0columns fromx * oversample.0 + origin.0, and likewise down. A window that reaches past its own pixel lets the pixels beside the glyph's box pick up some of its coverage, andSubpixelLayout::padis the room for those.use daegun::raster::{StripeOrder, SubpixelLayout}; assert_eq!(SubpixelLayout::grayscale().origin(), (0, 0)); let lcd = SubpixelLayout::horizontal(StripeOrder::Rgb); // Two samples left of the pixel's first. assert_eq!(lcd.origin(), (-2, 0)); // The sample columns that the pixel in column 4 reads: seven of them, from column 10. let x = 4; let first = x * i32::from(lcd.oversample().0) + i32::from(lcd.origin().0); assert_eq!((first, lcd.taps().0), (10, 7));raster::SubpixelLayout::oversamplepub const fn oversample(&self) -> (u8, u8)How many samples the glyph is drawn at for each pixel, across and down.
(1, 1)for grayscale. A stripe layout takes three one way and one the other:(3, 1)for stripes side by side and(1, 3)for stacked ones. A layout fromSubpixelLayout::from_weightshas what it was given, at mostMAX_OVERSAMPLEeach way.A rasterizer of your own scales the outline by these two factors before it samples, so that a glyph 10 pixels wide spans 30 samples at
(3, 1). daegun's rasterizer does that by itself, and the images it returns are in whole pixels whatever the oversampling.use daegun::raster::{StripeOrder, SubpixelLayout}; assert_eq!(SubpixelLayout::grayscale().oversample(), (1, 1)); let lcd = SubpixelLayout::horizontal(StripeOrder::Rgb); assert_eq!(lcd.oversample(), (3, 1)); assert_eq!(SubpixelLayout::vertical(StripeOrder::Rgb).oversample(), (1, 3)); // For a rasterizer of your own: the samples a glyph box of 10 by 17 pixels spans. let (across, down) = lcd.oversample(); assert_eq!((10 * usize::from(across), 17 * usize::from(down)), (30, 17));raster::SubpixelLayout::padpub fn pad(&self) -> (usize, usize)How many whole pixels an image needs on each side of the glyph's own box so the filter's window has room, across and down.
Both numbers are in pixels, not samples. The first is added on the left and again on the right, the second at the top and again at the bottom, so an image is
2 * pad.0pixels wider and2 * pad.1taller than the glyph's own box.(0, 0)for grayscale andSubpixelLayout::unfiltered,(1, 0)forSubpixelLayout::horizontaland(0, 1)forSubpixelLayout::vertical.Rasterizer::glyphadds it by itself: theImageit returns is already that much larger, with itsleftandtopmoved out to match. So size an atlas cell from the image's own width and height. Readpadto budget cells before you draw, or in a rasterizer of your own.It comes from the window: how far it reaches past the pixel, in samples, on the side where it reaches farther, divided by the samples for each pixel and rounded up. The same pad goes on both sides, also where the window reaches out on one side only.
use daegun::raster::{RasterOptions, Rasterizer, StripeOrder, SubpixelLayout}; use daegun::Location; assert_eq!(SubpixelLayout::grayscale().pad(), (0, 0)); let lcd = SubpixelLayout::horizontal(StripeOrder::Rgb); let (pad_x, pad_y) = lcd.pad(); assert_eq!((pad_x, pad_y), (1, 0)); let mut rasterizer = Rasterizer::new(); let g = font.glyph_id('g').expect("Inter maps g"); let gray = rasterizer.glyph(&font, g, &Location::default(), 20.0, &RasterOptions::DEFAULT)?; let (width, height) = (gray.width as usize, gray.height as usize); let options = RasterOptions::DEFAULT.with_layout(&lcd); let image = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?; // The image has the pad on both sides already: 12 by 17 pixels where the grayscale one is 10 by 17. assert_eq!((image.width as usize, image.height as usize), (width + 2 * pad_x, height + 2 * pad_y));raster::SubpixelLayout::tapspub const fn taps(&self) -> (u8, u8)The size of the filter's window: how many samples each channel reads, across and down.
(1, 1)for grayscale, where a pixel is its one sample.(7, 1)forSubpixelLayout::horizontal: the three samples of the pixel and two more on each side, which is the room a five-tap filter around each stripe takes.(1, 7)forSubpixelLayout::vertical, and three one way forSubpixelLayout::unfiltered. Neither number is aboveMAX_TAPS.Every channel has
taps.0 * taps.1weights, the length of each sliceSubpixelLayout::weightsreturns. All channels share the one window, and a channel that reads fewer samples has zeros for the rest.use daegun::raster::{StripeOrder, SubpixelLayout}; use daegun::Orientation; assert_eq!(SubpixelLayout::grayscale().taps(), (1, 1)); let lcd = SubpixelLayout::horizontal(StripeOrder::Rgb); assert_eq!(lcd.taps(), (7, 1)); assert_eq!(SubpixelLayout::vertical(StripeOrder::Rgb).taps(), (1, 7)); assert_eq!(SubpixelLayout::unfiltered(StripeOrder::Rgb, Orientation::Horizontal).taps(), (3, 1)); // Each channel has taps.0 * taps.1 weights. let (across, down) = lcd.taps(); assert_eq!(lcd.weights(0).map(<[f32]>::len), Some(usize::from(across) * usize::from(down)));raster::SubpixelLayout::unfilteredpub fn unfiltered(order: StripeOrder, orientation: Orientation) -> SelfA stripe layout with no filter: three samples for each pixel, and each channel is its own stripe's sample and nothing else.
orientationpicks the direction:Orientation::Horizontalfor stripes side by side, with three samples across each pixel, andOrientation::Verticalfor stacked ones, with three samples down.orderis the order of the stripes, as inSubpixelLayout::horizontal.With no filter nothing reaches past the pixel, so
SubpixelLayout::padis(0, 0)and the image is the size of the grayscale one, at three bytes a pixel. Edges are as sharp as the stripes allow, and nothing evens out the color: an edge that falls inside a pixel lights its stripes unequally and shows as a fringe of color.Use it when you filter the samples yourself. With
StripeOrder::RgbandOrientation::Horizontal, a row of the image is the glyph's coverage at three times the resolution across, one byte a sample from left to right. To draw text as it is,SubpixelLayout::horizontalandSubpixelLayout::verticalare the ones to use.use daegun::raster::{RasterOptions, Rasterizer, StripeOrder, SubpixelLayout}; use daegun::{Location, Orientation}; let raw = SubpixelLayout::unfiltered(StripeOrder::Rgb, Orientation::Horizontal); // The window is the three samples of the pixel, so there is no padding. assert_eq!((raw.oversample(), raw.taps(), raw.origin(), raw.pad()), ((3, 1), (3, 1), (0, 0), (0, 0))); // Red reads the first sample alone. assert_eq!(raw.weights(0), Some(&[1.0, 0.0, 0.0][..])); let mut rasterizer = Rasterizer::new(); let g = font.glyph_id('g').expect("Inter maps g"); let options = RasterOptions::DEFAULT.with_layout(&raw); let image = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?; // The same 10 by 17 pixels as in grayscale, three bytes each. assert_eq!((image.width, image.height, image.channels), (10, 17, 3));raster::SubpixelLayout::verticalpub fn vertical(order: StripeOrder) -> SelfThe layout for a display whose stripes are stacked: three samples down each pixel, through the same filter as
SubpixelLayout::horizontal.A panel turned a quarter turn, as a tablet held upright may be, has the three stripes of each pixel one above the other. The glyph is then drawn at one sample across each pixel and three down.
ordersays which stripe is on top: red forStripeOrder::Rgb, blue forStripeOrder::Bgr.The five weights run down in place of across, so
SubpixelLayout::padis(0, 1): the image is one pixel larger at the top and one at the bottom than the glyph's own box, and no wider. Each pixel is three bytes: red, green, blue.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 gray = rasterizer.glyph(&font, g, &Location::default(), 20.0, &RasterOptions::DEFAULT)?; let (top, width, height) = (gray.top, gray.width, gray.height); let stacked = SubpixelLayout::vertical(StripeOrder::Rgb); assert_eq!((stacked.oversample(), stacked.pad()), ((1, 3), (0, 1))); let options = RasterOptions::DEFAULT.with_layout(&stacked); let image = rasterizer.glyph(&font, g, &Location::default(), 20.0, &options)?; // Three bytes a pixel, and one pixel more than the grayscale image at the top and at the bottom. assert_eq!(image.channels, 3); assert_eq!((image.top, image.width, image.height), (top + 1, width, height + 2));raster::SubpixelLayout::weightspub fn weights(&self, channel: usize) -> Option<&[f32]>One channel's filter weights, row by row, or
Nonefor a channel the layout doesn't have.The slice has
taps.0 * taps.1weights: the top row of the window first, each row from the left.channelcounts from 0, and one at or pastSubpixelLayout::channelsgivesNone. So grayscale has channel 0 alone, and every other layout has 0, 1 and 2, which in the stripe layouts are red, green and blue.In the layouts daegun builds, each channel sums to 1, so a fully covered window comes out as 255. A layout from
SubpixelLayout::from_weightsreturns the weights you gave it, unchanged.use daegun::raster::{StripeOrder, SubpixelLayout}; assert_eq!(SubpixelLayout::grayscale().weights(0), Some(&[1.0][..])); assert_eq!(SubpixelLayout::grayscale().weights(1), None); let lcd = SubpixelLayout::horizontal(StripeOrder::Rgb); let red = lcd.weights(0).expect("a stripe layout has three channels"); // Seven taps, from two samples left of the pixel: the five-tap filter around the pixel's first // sample, the red stripe, then two zeros. let in_256ths: Vec<f32> = red.iter().map(|w| w * 256.0).collect(); assert_eq!(in_256ths, [8.0, 77.0, 86.0, 77.0, 8.0, 0.0, 0.0]); assert_eq!(red.iter().sum::<f32>(), 1.0); // Blue has the same filter two samples to the right. let blue = lcd.weights(2).expect("a stripe layout has three channels"); assert_eq!(blue[2..], red[..5]); assert_eq!(lcd.weights(3), None);raster::Target::newpub fn new(left: i32, top: i32, width: u32, height: u32, stride: usize, pixels: &'a mut [u8]) -> SelfDescribes a slice of pixels as a target: its size, its stride, and where its top left corner lies from the origin.
leftandtopcome first: how far right of the origin the left edge of the rectangle is, and how far above it the top edge. Then thewidthandheightin pixels, thestridein bytes from one row to the next, and the pixels themselves.It checks nothing. The call you hand the target to does, and answers
ErrorKind::InvalidArgumentif the stride is shorter than a row, which iswidthbytes for a glyph or a path andwidth * 4for a color glyph, or if the slice is shorter than(height - 1) * strideplus one row. The last row needs no padding after it.A stride longer than a row lets you aim at part of a larger canvas: start the slice at the first pixel of the part and pass the stride of the canvas.
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 canvas 64 pixels wide. Draw into the 16 by 24 part of it whose corner is at column 40 of row 4: // the slice starts there, and the stride is the canvas's. let canvas_width = 64; let mut canvas = vec![0u8; canvas_width * 32]; let part = &mut canvas[4 * canvas_width + 40..]; let target = Target::new(-2, 16, 16, 24, canvas_width, part); rasterizer.glyph_into(&font, glyph, &Location::default(), 20.0, &RasterOptions::DEFAULT, target)?; // The part is written, the glyph and the zeros around it, and the canvas beside it is untouched.