Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Y: variable fonts — named instances as styles, shaped, drawn and embedded at their axes

Brandon Thomasbddaaac88755
diff --git a/ROADMAP.md b/ROADMAP.md
index 2f2fb6dca..a9f0215cd 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -36,6 +36,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Tagged PDF (`file.exportPdf {tagged}`, on by default from the UI): structure tree with stories as paragraphs in reading order, figures carrying their alt text, parent-page items and printer's marks as artifacts.
- Global Light (`object.globalLight`, `globalLight` on drop/inner shadows; Use Global Light in the Effects panel) and Generate Static Caption (`object.caption`: template over name, path, alt text, label, effective ppi, dimensions, format; any side, offset, style).
- Control panel scale X/Y, rotation and shear fields (`transform.info`, absolute `transform.set {scaleX, scaleY, rotation, shear}` about the reference point) and Preferences › Transformations are Totals for nested objects and placed graphics.
+- Variable fonts: each named instance is a style (Font menu, shaping with feature variations, metrics, outlines) and embeds at its axis settings in PDF; free axis sliders still to come.
- Drag and drop text editing: drag selected text to move it (Alt copies) with its formatting (`text.release`).
- Image Import Options: place any page of a multi-page PDF (`file.place {pdfPage}`; the app asks which page), shown on screen and embedded as that page in PDF export.
- Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index 0f2c6bf28..84dee623d 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -188,3 +188,25 @@ mod tagged_tests {
assert!(!pdf(&mut s, false).contains("/StructTreeRoot"));
}
}
+
+#[cfg(test)]
+mod variable_font_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ #[test]
+ fn variable_font_instance_exports_to_pdf() {
+ let Ok(data) = std::fs::read("/System/Library/Fonts/Supplemental/Skia.ttf") else { return };
+ designcraft_fonts::FontDb::global().add_font(data);
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Variable"})).unwrap();
+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 8})).unwrap();
+ s.execute("type.char", &json!({"fontFamily": "Skia", "fontStyle": "Black"})).unwrap();
+ let out = s.execute("file.exportPdf", &json!({})).unwrap();
+ assert!(out["bytes"].as_u64().unwrap() > 1000);
+ let fonts = s.execute("font.list", &json!({})).unwrap();
+ assert!(fonts.to_string().contains("Black"), "{fonts}");
+ }
+}
diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs
index 9dc4bbbf6..f401c4955 100644
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@ -5,7 +5,7 @@ use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use kurbo::BezPath;
-use skrifa::instance::{LocationRef, Size};
+use skrifa::instance::{Location, LocationRef, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
use skrifa::raw::FileRef;
use skrifa::string::StringId;
@@ -62,6 +62,11 @@ pub struct FontFace {
pub cap_height: f64,
pub x_height: f64,
pub shaper: harfrust::ShaperData,
+ /// Variable fonts: the named instance's axis settings (user units; empty = default instance),
+ /// the normalised location and the shaper's view of it.
+ pub coords: Vec<([u8; 4], f32)>,
+ location: Location,
+ pub instance: Option<harfrust::ShaperInstance>,
/// Basic Multilingual Plane coverage bitset, built on first use.
bmp: std::sync::OnceLock<Box<[u64]>>,
}
@@ -134,6 +139,14 @@ impl FontFace {
pub fn hb(&self) -> Option<harfrust::FontRef<'_>> {
harfrust::FontRef::from_index(self.data(), self.index).ok()
}
+ /// Where in the design space glyphs, metrics and outlines come from.
+ pub fn location(&self) -> LocationRef<'_> {
+ (&self.location).into()
+ }
+ /// Is this a named instance of a variable font?
+ pub fn is_variable(&self) -> bool {
+ !self.coords.is_empty()
+ }
/// Face index within the font file (collections); 0 for plain fonts.
pub fn index(&self) -> u32 {
self.index
@@ -180,7 +193,7 @@ impl FontFace {
/// Advance width of glyph `gid` in font units.
pub fn advance(&self, gid: u32) -> f64 {
self.skrifa()
- .and_then(|f| f.glyph_metrics(Size::unscaled(), LocationRef::default()).advance_width(GlyphId::new(gid)))
+ .and_then(|f| f.glyph_metrics(Size::unscaled(), self.location()).advance_width(GlyphId::new(gid)))
.map(|a| a as f64)
.unwrap_or(self.upem * 0.5)
}
@@ -254,44 +267,77 @@ fn name(font: &skrifa::FontRef<'_>, ids: &[StringId]) -> Option<String> {
ids.iter().find_map(|id| font.localized_strings(*id).english_or_first().map(|s| s.to_string()).filter(|s| !s.is_empty()))
}
-/// Parse every face in `data` (a font file or collection). Returns `(index, family, style)`.
-fn enumerate_faces(data: &[u8]) -> Vec<(u32, String, String)> {
+/// One face found in a font file: index, family, style and (variable fonts) the named instance's
+/// axis settings.
+type Found = (u32, String, String, Vec<([u8; 4], f32)>);
+
+/// Parse every face in `data` (a font file or collection); a variable font yields one face per
+/// named instance (InDesign lists them as styles).
+fn enumerate_faces(data: &[u8]) -> Vec<Found> {
let count = match FileRef::new(data) {
Ok(FileRef::Font(_)) => 1,
Ok(FileRef::Collection(c)) => c.len(),
Err(_) => 0,
};
- (0..count)
- .filter_map(|i| {
- let f = skrifa::FontRef::from_index(data, i).ok()?;
- let family = name(&f, &[StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME])?;
+ let mut out = Vec::new();
+ for i in 0..count {
+ let Ok(f) = skrifa::FontRef::from_index(data, i) else { continue };
+ let Some(family) = name(&f, &[StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME]) else { continue };
+ let axes = f.axes();
+ let mut named = Vec::new();
+ for ni in f.named_instances().iter() {
+ let Some(style) = name(&f, &[ni.subfamily_name_id()]) else { continue };
+ if named.iter().any(|(_, s, _): &(u32, String, _)| s.eq_ignore_ascii_case(&style)) {
+ continue;
+ }
+ let coords: Vec<([u8; 4], f32)> = axes.iter().zip(ni.user_coords()).map(|(a, v)| (a.tag().to_be_bytes(), v)).collect();
+ named.push((i, style, coords));
+ }
+ if named.is_empty() {
let style = name(&f, &[StringId::TYPOGRAPHIC_SUBFAMILY_NAME, StringId::SUBFAMILY_NAME]).unwrap_or_else(|| "Regular".into());
- Some((i, family, style))
- })
- .collect()
+ out.push((i, family, style, Vec::new()));
+ } else {
+ out.extend(named.into_iter().map(|(i, s, c)| (i, family.clone(), s, c)));
+ }
+ }
+ out
}
-fn make_face(bytes: FontBytes, index: u32, family: String, style: String) -> Option<FontFace> {
+fn make_face(bytes: FontBytes, index: u32, family: String, style: String, coords: Vec<([u8; 4], f32)>) -> Option<FontFace> {
let data: &[u8] = match &bytes {
FontBytes::Static(b) => b,
FontBytes::Owned(v) => v.as_slice(),
};
let f = skrifa::FontRef::from_index(data, index).ok()?;
- let m = f.metrics(Size::unscaled(), LocationRef::default());
+ let settings: Vec<(skrifa::Tag, f32)> = coords.iter().map(|(t, v)| (skrifa::Tag::new(t), *v)).collect();
+ let location = if coords.is_empty() { Location::default() } else { f.axes().location(settings.iter().copied()) };
+ let m = f.metrics(Size::unscaled(), &location);
let a = f.attributes();
- let shaper = harfrust::ShaperData::new(&harfrust::FontRef::from_index(data, index).ok()?);
+ let hb = harfrust::FontRef::from_index(data, index).ok()?;
+ let shaper = harfrust::ShaperData::new(&hb);
+ let instance = (!coords.is_empty())
+ .then(|| harfrust::ShaperInstance::from_variations(&hb, settings.iter().map(|(t, v)| harfrust::Variation { tag: *t, value: *v })));
+ let axis = |tag: &[u8; 4]| coords.iter().find(|(t, _)| t == tag).map(|(_, v)| *v);
+ let weight = axis(b"wght").unwrap_or(if coords.is_empty() { a.weight.value() } else { style_weight(&style) });
+ let italic = axis(b"ital")
+ .map(|v| v >= 0.5)
+ .or(axis(b"slnt").map(|v| v.abs() > 0.1))
+ .unwrap_or(!matches!(a.style, skrifa::attribute::Style::Normal) || style_italic(&style));
Some(FontFace {
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
family,
style,
- weight: a.weight.value(),
- italic: !matches!(a.style, skrifa::attribute::Style::Normal),
+ weight,
+ italic,
upem: m.units_per_em.max(1) as f64,
ascent: m.ascent as f64,
descent: -(m.descent as f64),
cap_height: m.cap_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.72),
x_height: m.x_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.5),
shaper,
+ coords,
+ location,
+ instance,
bytes,
index,
bmp: std::sync::OnceLock::new(),
@@ -332,8 +378,8 @@ impl FontDb {
fn new_bundled() -> Self {
let mut faces = Vec::new();
for data in BUNDLED {
- for (i, family, style) in enumerate_faces(data) {
- if let Some(f) = make_face(FontBytes::Static(data), i, family, style) {
+ for (i, family, style, coords) in enumerate_faces(data) {
+ if let Some(f) = make_face(FontBytes::Static(data), i, family, style, coords) {
faces.push(Arc::new(f));
}
}
@@ -399,11 +445,11 @@ impl FontDb {
pub fn add_font(&self, bytes: Vec<u8>) -> usize {
let data = Arc::new(bytes);
let mut added = 0;
- for (i, family, style) in enumerate_faces(&data) {
+ for (i, family, style, coords) in enumerate_faces(&data) {
if self.read_faces().iter().any(|f| f.family.eq_ignore_ascii_case(&family) && f.style.eq_ignore_ascii_case(&style)) {
continue;
}
- if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, family, style) {
+ if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, family, style, coords) {
self.faces.write().unwrap_or_else(|e| e.into_inner()).push(Arc::new(f));
added += 1;
}
@@ -451,7 +497,7 @@ impl FontDb {
continue;
}
let Ok(data) = std::fs::read(&p) else { continue };
- for (_, family, style) in enumerate_faces(&data) {
+ for (_, family, style, _) in enumerate_faces(&data) {
found.push(CatalogEntry { family, style, path: p.clone() });
}
}
@@ -582,7 +628,7 @@ impl FontDb {
}
let Ok(data) = std::fs::read(&p) else { continue };
let hit =
- enumerate_faces(&data).iter().any(|(i, _, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()));
+ enumerate_faces(&data).iter().any(|(i, _, _, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()));
if hit && self.add_font(data) > 0 && covered(self) {
return true;
}
@@ -601,7 +647,7 @@ impl FontDb {
if let Some(f) = face.skrifa()
&& let Some(g) = f.outline_glyphs().get(GlyphId::new(gid))
{
- let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), LocationRef::default()), &mut pen);
+ let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen);
}
let p = Arc::new(pen.0);
let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner());
diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs
index 9f0a7ea75..3fe821c26 100644
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@ -13,7 +13,7 @@ pub use harfrust::Feature;
use harfrust::{Direction, ShapeOptions, Tag, UnicodeBuffer};
pub use kurbo::BezPath;
use skrifa::MetadataProvider;
-use skrifa::instance::{LocationRef, Size};
+use skrifa::instance::Size;
/// InDesign's default text font is a serif; ours is Source Serif 4.
pub const DEFAULT_FAMILY: &str = "Source Serif 4";
@@ -47,7 +47,7 @@ pub fn feature(tag: &str) -> Option<Feature> {
pub fn shape(face: &FontFace, text: &str, features: &[Feature], map: impl Fn(char) -> char) -> Vec<ShapedGlyph> {
let mut out = Vec::with_capacity(text.len());
let shaped = face.hb().map(|hb| {
- let shaper = face.shaper.shaper(&hb).build();
+ let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
let mut buf = UnicodeBuffer::new();
for (i, c) in text.char_indices() {
buf.add(map(c), i as u32);
@@ -69,7 +69,7 @@ pub fn shape(face: &FontFace, text: &str, features: &[Feature], map: impl Fn(cha
&& let Some(f) = face.skrifa()
{
let cmap = f.charmap();
- let gm = f.glyph_metrics(Size::unscaled(), LocationRef::default());
+ let gm = f.glyph_metrics(Size::unscaled(), face.location());
for (i, c) in text.char_indices() {
let g = cmap.map(map(c)).unwrap_or_default();
let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5);
@@ -126,6 +126,38 @@ mod tests {
assert_eq!(g[1].cluster, 1);
}
+ #[test]
+ fn variable_font_named_instances_are_styles() {
+ // Uses a variable system font when one is installed (macOS ships several).
+ let Some(data) =
+ ["/System/Library/Fonts/Supplemental/Skia.ttf", "/System/Library/Fonts/NewYork.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"]
+ .iter()
+ .find_map(|p| std::fs::read(p).ok())
+ else {
+ return;
+ };
+ let db = FontDb::global();
+ db.add_font(data.clone());
+ let Some(fam) = skrifa::FontRef::new(&data).ok().and_then(|f| {
+ (f.named_instances().len() > 1)
+ .then(|| f.localized_strings(skrifa::string::StringId::FAMILY_NAME).english_or_first().map(|s| s.to_string()))?
+ }) else {
+ return;
+ };
+ let styles = db.styles(&fam);
+ assert!(styles.len() > 1, "{styles:?}");
+ let faces: Vec<_> = styles.iter().map(|s| db.face(&fam, s)).filter(|f| f.is_variable()).collect();
+ let light = faces.iter().min_by(|a, b| a.weight.total_cmp(&b.weight)).unwrap();
+ let heavy = faces.iter().max_by(|a, b| a.weight.total_cmp(&b.weight)).unwrap();
+ assert!(heavy.weight > light.weight, "{light:?} {heavy:?}");
+ let ink = |f: &FontFace| {
+ let g = shape(f, "H", &[], |c| c);
+ let b = kurbo::Shape::bounding_box(&*db.outline(f, g[0].gid));
+ ((b.area() * 100.0).round() as i64, g[0].x_advance)
+ };
+ assert_ne!(ink(light), ink(heavy), "instances draw differently");
+ }
+
#[test]
fn outlines_and_metrics() {
let db = FontDb::global();
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index 0057c518c..d391e78ee 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -37,7 +37,18 @@ fn same_run(a: &PlacedGlyph, b: &PlacedGlyph) -> bool {
impl Exporter<'_> {
pub(crate) fn font(&mut self, face: &FontFace) -> Option<Font> {
- self.fonts.entry(face.id()).or_insert_with(|| Font::new(face.data().to_vec().into(), face.index())).clone()
+ self.fonts
+ .entry(face.id())
+ .or_insert_with(|| {
+ if face.is_variable() {
+ // A named instance: krilla embeds the font at these axis settings.
+ let coords: Vec<(krilla::text::Tag, f32)> = face.coords.iter().map(|(t, v)| (krilla::text::Tag::new(t), *v)).collect();
+ Font::new_variable(face.data().to_vec().into(), face.index(), &coords)
+ } else {
+ Font::new(face.data().to_vec().into(), face.index())
+ }
+ })
+ .clone()
}
fn reverse_cmap(&mut self, face: &FontFace) -> Arc<HashMap<u32, char>> {
diff --git a/docs/parity.md b/docs/parity.md
index 1bb7241f7..64d8b2727 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -10,7 +10,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
| Priority | Features | Done | Partial | Missing | Parity |
|---|---|---|---|---|---|
| P0 | 102 | 99 | 3 | 0 | 99% |
-| P1 | 97 | 68 | 26 | 3 | 84% |
+| P1 | 97 | 68 | 27 | 2 | 84% |
| P2 | 76 | 12 | 13 | 51 | 24% |
| Area | Parity |
@@ -24,7 +24,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
| Effects & transparency | 62% |
| Placing & links | 82% |
| Type & text frames | 88% |
-| Typography | 85% |
+| Typography | 87% |
| Styles | 92% |
| Tables | 85% |
| Long documents | 79% |
@@ -218,7 +218,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t
| Typography | Character attributes | P0 | D |
| Typography | Underline/Strikethrough options | P1 | D |
| Typography | OpenType features | P0 | D |
-| Typography | Variable fonts | P1 | M |
+| Typography | Variable fonts | P1 | P |
| Typography | Paragraph attributes | P0 | D |
| Typography | Paragraph Composer (total-fit) | P0 | D |
| Typography | Single-line Composer | P0 | D |