From f02557e8f9af96ebda90a44e94d428a1d8e823e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jindr=CC=8Cich=20S=CC=8Cars=CC=8Con?= Date: Wed, 21 Oct 2026 23:26:27 +0200 Subject: [PATCH] M6: Sketch import: fonts by PostScript name, Sketch's natural line The font database knows each face's PostScript name; the Sketch import finds the installed face a file's font names (CourierNewPSMT is Courier New Regular) and reads the family from the name only when it isn't installed. Text without a fixed line height takes the line Sketch draws: ascent and descent rounded to whole pixels, the line gap left out, a fifth more for classic Mac fonts, the baseline where Sketch puts it (measured on sketchtool renders of 80 fonts). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/file.rs | 81 ++++++++++++++++++++++-- crates/engine/src/sketch_import_tests.rs | 40 ++++++++++++ crates/format/src/sketch/mod.rs | 32 ++++++++-- crates/format/src/sketch/text.rs | 19 +++++- crates/format/src/sketch/text_tests.rs | 15 +++++ crates/format/src/sketch/tree.rs | 7 +- crates/text/src/fontdb.rs | 38 +++++++++-- crates/text/src/fontdb_tests.rs | 31 ++++++++- docs/file-format-parity.md | 2 +- 9 files changed, 244 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 5de7e0fd..8db15cee 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -556,13 +556,18 @@ fn load_with( /// Gives `None` when `bytes` are not a `.sketch` file. Then other readers can try. fn load_sketch(bytes: &[u8], name: &str) -> Option> { - let r = figcraft_format::sketch::try_import(bytes, name)?; + if !figcraft_format::sketch::is_sketch(bytes) { + return None; + } + // The import and what follows read the installed fonts: the system's must be known first (the + // desktop app scans them in the background; this waits for that scan). + figcraft_text::fontdb::scan_system_fonts(); + let fonts: figcraft_format::sketch::FontLookup = Box::new(figcraft_text::fontdb::postscript_face); + let r = figcraft_format::sketch::try_import_with_fonts(bytes, name, Some(fonts))?; Some(r.map_err(|e| EngineError::Other(e.to_string())).map(|(mut doc, warnings)| { - // Both read the installed fonts: the system's must be known first (the desktop app scans - // them in the background; this waits for that scan). - figcraft_text::fontdb::scan_system_fonts(); match_font_families(&mut doc); platform_tracking(&mut doc); + sketch_line_heights(&mut doc); link_instances(&mut doc); reflow_overridden_text(&mut doc); figcraft_format::Loaded { issues: warnings, ..doc.into() } @@ -665,6 +670,74 @@ fn platform_tracking(doc: &mut Document) { } } +/// Families Sketch (Apple's text system) gives a fifth more than their ascent and descent as their +/// natural line: classic Mac fonts, found on `sketchtool` renders. Other fonts show none of this. +const TALL_LINE_FAMILIES: [&str; 11] = + ["Academy Engraved LET", "Courier", "Helvetica", "Hoefler Text", "Palatino", "Sathu", "Silom", "Skia", "Times", "Webdings", "Zapf Dingbats"]; + +/// Sketch's natural line for a font of `ascent` and `descent` in `upem` units at `size` px: its +/// height in px and how far down the text moves so its baseline sits where Sketch puts it. Sketch +/// rounds the ascent and descent to whole pixels each and leaves the font's line gap out (a fifth +/// more for [`TALL_LINE_FAMILIES`]), with the baseline above the rounded descent; FigCraft centres +/// the font's own ascent and descent in the line. `(0, 0)` without metrics. +pub(crate) fn sketch_line(ascent: f64, descent: f64, upem: f64, family: &str, size: f64) -> (f64, f64) { + let k = size / upem; + let (a, d) = (ascent * k, descent * k); + if !(a.is_finite() && d.is_finite()) || a + d <= 0.0 { + return (0.0, 0.0); + } + let natural = a.round() + d.round(); + let line = if TALL_LINE_FAMILIES.iter().any(|f| f.eq_ignore_ascii_case(family)) { (natural * 1.2).round() } else { natural }; + let sketch_baseline = line - d.round(); + let figcraft_baseline = (line - (a + d)) / 2.0 + a; + (line, sketch_baseline - figcraft_baseline) +} + +/// Text without a fixed line height takes the line Sketch drew it with (FigCraft's natural line, +/// like Figma's, counts the font's line gap and centres the font in it; Sketch's doesn't), as a +/// share of its size so it still follows the size, and moves to Sketch's baseline. Shared text +/// styles take the line too. +fn sketch_line_heights(doc: &mut Document) { + // Per family and style: the face's ascent, descent and units per em. + type Metrics = Option<(f64, f64, f64)>; + let mut cache: std::collections::BTreeMap<(String, String), Metrics> = std::collections::BTreeMap::new(); + let mut set = |style: &mut TextStyle| -> f64 { + if style.line_height != LineHeight::Auto || !style.font_size.is_finite() || style.font_size <= 0.0 { + return 0.0; + } + let m = *cache.entry((style.font_family.clone(), style.font_style.clone())).or_insert_with(|| { + figcraft_text::fontdb::has_family(&style.font_family) + .then(|| figcraft_text::fontdb::find_face(&style.font_family, &style.font_style)) + .flatten() + .map(|f| (f.ascent, f.descent, f.upem)) + }); + let Some((a, d, upem)) = m else { return 0.0 }; + let (line, down) = sketch_line(a, d, upem, &style.font_family, style.font_size); + if line > 0.0 { + style.line_height = LineHeight::Percent(line / style.font_size * 100.0); + } + down + }; + let ids: Vec = doc.nodes().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id).collect(); + for id in ids { + let Some(n) = doc.node_mut(id) else { continue }; + let NodeKind::Text(td) = &mut n.kind else { continue }; + let down = set(&mut td.style); + for r in &mut td.runs { + set(&mut r.style); + } + // Down in the layer's own frame (a rotated text moves along its own axis). + if down.is_finite() && down != 0.0 { + n.transform *= figcraft_doc::geom::Affine::translate((0.0, down)); + } + } + for st in &mut doc.styles { + if let StyleKind::Text { style } = &mut st.kind { + set(style); + } + } +} + /// The installed family `family` means when it isn't installed under that exact name: the one /// whose name is the same without spaces, ignoring case. pub(crate) fn installed_family(family: &str, installed: &[String]) -> Option { diff --git a/crates/engine/src/sketch_import_tests.rs b/crates/engine/src/sketch_import_tests.rs index 5dc4b31a..36b200a5 100644 --- a/crates/engine/src/sketch_import_tests.rs +++ b/crates/engine/src/sketch_import_tests.rs @@ -401,3 +401,43 @@ fn sketch_resized_stack_instances_reflow() { assert!((b.x0 - a.x1 - 8.0).abs() < 0.5, "{a:?} {b:?}"); assert!((doc.world_bounds(inst).unwrap().x1 - 342.0).abs() < 1e-6); } + +/// Sketch's natural line: the font's ascent and descent each rounded to whole pixels, without its +/// line gap, the baseline at the rounded ascent; the classic Mac fonts get a fifth more, all of it +/// above the text. +#[test] +fn sketch_natural_line_rule() { + use crate::cmd::file::sketch_line; + // Helvetica Neue Medium (975 + 217 of 1000, a gap of 29 left out) at 17 px: 16.575 → 17 and + // 3.689 → 4, a line of 21 with the baseline at 17. FigCraft puts the baseline at + // (21 − 20.264) / 2 + 16.575 = 16.943, so the text moves down 0.057. + let (line, down) = sketch_line(975.0, 217.0, 1000.0, "Helvetica Neue", 17.0); + assert!((line - 21.0).abs() < 1e-9 && (down - 0.057).abs() < 1e-9, "{line} {down}"); + // Helvetica at 100 px: 77 + 23 and a fifth more, 120, all of it above: the baseline at 97 + // where FigCraft centres it at 87. + let (line, down) = sketch_line(1577.0, 471.0, 2048.0, "helvetica", 100.0); + assert!((line - 120.0).abs() < 1e-9 && (down - 10.0).abs() < 0.05, "{line} {down}"); + assert_eq!(sketch_line(0.0, 0.0, 0.0, "X", 12.0), (0.0, 0.0), "no metrics, no change"); + assert_eq!(sketch_line(900.0, 200.0, 1000.0, "X", f64::NAN), (0.0, 0.0)); +} + +/// Text without a fixed line height gets Sketch's natural line as a share of its size, in the +/// layer and in shared text styles. +#[test] +fn sketch_text_gets_sketchs_natural_line() { + if !std::path::Path::new("/System/Library/Fonts/HelveticaNeue.ttc").exists() { + return; + } + figcraft_text::fontdb::scan_system_fonts(); + let font = json!({"name": "HelveticaNeue", "size": 100}); + let run = json!({"location": 0, "length": 2, "attributes": {"MSAttributedStringFontAttribute": {"attributes": font}}}); + let t = shape("text", "Label", [0.0, 0.0, 200.0, 120.0], json!({"attributedString": {"string": "Hi", "attributes": [run]}, "textBehaviour": 0})); + let data = base64::engine::general_purpose::STANDARD.encode(sketch_with("64", &[("A", "Page")], &[t])); + let mut s = Session::new(); + s.execute("file.open", &json!({"data": data, "name": "x.sketch"})).unwrap(); + let doc = s.doc().unwrap(); + let NodeKind::Text(td) = &doc.nodes().find(|n| n.name == "Label").unwrap().kind else { panic!("not text") }; + // 95.2 → 95 and 21.3 → 21: 116 px, as a share of the size. + let figcraft_doc::LineHeight::Percent(p) = td.style.line_height else { panic!("{:?}", td.style.line_height) }; + assert!((p - 116.0).abs() < 1e-9, "{p}"); +} diff --git a/crates/format/src/sketch/mod.rs b/crates/format/src/sketch/mod.rs index 15df9d22..18332afd 100644 --- a/crates/format/src/sketch/mod.rs +++ b/crates/format/src/sketch/mod.rs @@ -81,35 +81,55 @@ pub fn is_sketch(bytes: &[u8]) -> bool { })) } +/// Finds the installed face a PostScript name belongs to: its family and style. +pub type FontLookup = Box Option<(String, String)>>; + /// Import `bytes` when they are a `.sketch` file; `None` when they are something else. pub fn try_import(bytes: &[u8], name: &str) -> Option), FormatError>> { - is_sketch(bytes).then(|| import(bytes, name)) + try_import_with_fonts(bytes, name, None) +} + +/// [`try_import`] with `fonts` finding the installed faces the file's fonts (PostScript names) +/// belong to; families of fonts it doesn't find are read from their names. +pub fn try_import_with_fonts(bytes: &[u8], name: &str, fonts: Option) -> Option), FormatError>> { + is_sketch(bytes).then(|| import_with_fonts(bytes, name, fonts)) } /// Build a document from a `.sketch` file. Returns it with the warnings about what was skipped or /// approximated. `name`: the document name. pub fn import(bytes: &[u8], name: &str) -> Result<(Document, Vec), FormatError> { - import_parts(bytes, name, MAX_JSON_MEMBER, crate::fig::layer_budget(bytes.len())) + import_with_fonts(bytes, name, None) +} + +/// [`import`] with a font lookup (see [`try_import_with_fonts`]). +pub fn import_with_fonts(bytes: &[u8], name: &str, fonts: Option) -> Result<(Document, Vec), FormatError> { + import_parts(bytes, name, MAX_JSON_MEMBER, crate::fig::layer_budget(bytes.len()), fonts) } /// [`import`] reading pages of at most `max_member` bytes of JSON each. #[cfg(test)] pub(crate) fn import_within(bytes: &[u8], name: &str, max_member: u64) -> Result<(Document, Vec), FormatError> { - import_parts(bytes, name, max_member, crate::fig::layer_budget(bytes.len())) + import_parts(bytes, name, max_member, crate::fig::layer_budget(bytes.len()), None) } /// [`import`] with at most `max_nodes` layers. #[cfg(test)] pub(crate) fn import_within_nodes(bytes: &[u8], name: &str, max_nodes: usize) -> Result<(Document, Vec), FormatError> { - import_parts(bytes, name, MAX_JSON_MEMBER, max_nodes) + import_parts(bytes, name, MAX_JSON_MEMBER, max_nodes, None) } -fn import_parts(bytes: &[u8], name: &str, max_member: u64, max_nodes: usize) -> Result<(Document, Vec), FormatError> { +fn import_parts( + bytes: &[u8], + name: &str, + max_member: u64, + max_nodes: usize, + fonts: Option, +) -> Result<(Document, Vec), FormatError> { if bytes.starts_with(b"SQLite format 3\0") { return Err(FormatError::Io(TOO_OLD.into())); } let archive = Archive::open(bytes, max_member)?; - let map = tree::to_rest(&archive, name, max_nodes); + let map = tree::to_rest(&archive, name, max_nodes, fonts); if map.too_old { return Err(FormatError::Io(TOO_OLD.into())); } diff --git a/crates/format/src/sketch/text.rs b/crates/format/src/sketch/text.rs index 76692790..027de660 100644 --- a/crates/format/src/sketch/text.rs +++ b/crates/format/src/sketch/text.rs @@ -124,7 +124,7 @@ pub(crate) fn type_style(cx: &mut Cx, a: &Value) -> Value { let font = a.get("MSAttributedStringFontAttribute").and_then(|f| f.get("attributes")); let ps = font.and_then(|f| f.get("name")).and_then(Value::as_str).unwrap_or(""); let size = font.and_then(|f| f.get("size")).and_then(Value::as_f64).filter(|s| s.is_finite() && *s > 0.0).unwrap_or(12.0); - let (family, style) = font_name(ps); + let (family, style) = installed(cx, ps).unwrap_or_else(|| font_name(ps)); if ps.is_empty() { cx.warn("text without a font uses Helvetica"); } @@ -180,6 +180,23 @@ fn variations(v: &Value) -> Option { (!axes.is_empty()).then_some(Value::Object(axes)) } +/// The installed family and style of PostScript name `ps`, when the import has a font lookup and +/// the font is installed. +fn installed(cx: &mut Cx, ps: &str) -> Option<(String, String)> { + if ps.is_empty() { + return None; + } + if let Some(found) = cx.font_cache.get(ps) { + return found.clone(); + } + let found = cx.fonts.as_ref().and_then(|f| f(ps)); + // A file names a few hundred fonts at most; junk ones don't grow the cache past that. + if cx.font_cache.len() < 4096 { + cx.font_cache.insert(ps.to_string(), found.clone()); + } + found +} + /// Family and style of a font from its PostScript name: "HelveticaNeue-Bold" → ("Helvetica Neue", /// "Bold"). Words of the family are split at case changes, which can't always match the real name /// (a CJK family would split as "Ping Fang SC"); the engine matches families against the installed diff --git a/crates/format/src/sketch/text_tests.rs b/crates/format/src/sketch/text_tests.rs index 53ca5235..8adef1ea 100644 --- a/crates/format/src/sketch/text_tests.rs +++ b/crates/format/src/sketch/text_tests.rs @@ -235,3 +235,18 @@ fn font_references_without_data_are_no_embedded_fonts() { let (_, warnings) = import(&z, "f").unwrap(); assert!(!warnings.iter().any(|w| w.contains("embedded")), "{warnings:?}"); } + +/// With a font lookup, a PostScript name gives the installed family and style it belongs to (the +/// name alone can't always tell: "CourierNewPSMT" is Courier New Regular); without one, or for a +/// font that isn't installed, the family is read from the name. +#[test] +fn postscript_names_find_installed_fonts() { + let mk = |name: &str, ps: &str| text(name, 0.0, 0.0, 100.0, 20.0, "Hi", &[(0, 2, ps, 14.0, BLACK)]); + let z = sketch_zip("83.2", 139, document(&["P"]), &[page("P", "Page", vec![mk("A", "CourierNewPSMT"), mk("B", "BrandSans-Bold")])], &[]); + let lookup: crate::sketch::FontLookup = Box::new(|ps: &str| (ps == "CourierNewPSMT").then(|| ("Courier New".to_string(), "Regular".to_string()))); + let (doc, _) = crate::sketch::import_with_fonts(&z, "f", Some(lookup)).unwrap(); + assert_eq!((data(&doc, "A").style.font_family.as_str(), data(&doc, "A").style.font_style.as_str()), ("Courier New", "Regular")); + assert_eq!(data(&doc, "B").style.font_family, "Brand Sans"); + let (doc, _) = import(&z, "f").unwrap(); + assert_eq!(data(&doc, "A").style.font_family, "Courier New PSMT"); +} diff --git a/crates/format/src/sketch/tree.rs b/crates/format/src/sketch/tree.rs index 3d6a48d3..e651463d 100644 --- a/crates/format/src/sketch/tree.rs +++ b/crates/format/src/sketch/tree.rs @@ -58,6 +58,9 @@ pub(crate) struct Cx { /// Layers mapped so far, and the most the file may give. pub nodes: usize, pub max_nodes: usize, + /// Finds installed faces by PostScript name, and what it found (or didn't) so far. + pub fonts: Option, + pub font_cache: std::collections::BTreeMap>, } impl Cx { @@ -90,7 +93,7 @@ impl Cx { } /// Map the pages of `archive` to a REST file JSON named `name`. -pub(crate) fn to_rest(archive: &Archive, name: &str, max_nodes: usize) -> Map { +pub(crate) fn to_rest(archive: &Archive, name: &str, max_nodes: usize, fonts: Option) -> Map { let symbols = super::symbols::Symbols::read(&archive.document, &archive.pages); let shared = super::shared::Shared::read(&archive.document); let mut cx = Cx { @@ -109,6 +112,8 @@ pub(crate) fn to_rest(archive: &Archive, name: &str, max_nodes: usize) -> Map { too_old: false, nodes: 0, max_nodes, + fonts, + font_cache: std::collections::BTreeMap::new(), }; let defs = super::shared::Shared::definitions(&mut cx); cx.style_defs = defs.iter().filter_map(|d| d.get("id").and_then(Value::as_str).map(str::to_string)).collect(); diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 22ca4b84..34d76b12 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -86,6 +86,8 @@ pub struct Face { pub id: u32, pub family: String, pub style: String, + /// The face's PostScript name ("HelveticaNeue-Bold"). + pub postscript: Option, pub weight: u16, pub italic: bool, pub bytes: FontBytes, @@ -185,6 +187,7 @@ impl Face { id: NEXT_FACE.fetch_add(1, Ordering::Relaxed), italic: !matches!(attrs.style, skrifa::attribute::Style::Normal) || style.to_ascii_lowercase().contains("italic"), weight, + postscript: name_string(&f, StringId::POSTSCRIPT_NAME), family, style, index, @@ -493,6 +496,8 @@ struct Pending { path: std::path::PathBuf, index: u32, style: String, + /// The face's PostScript name. + postscript: Option, } #[derive(Default)] @@ -570,6 +575,16 @@ impl FontDb { (0..count).filter_map(|i| Face::from_bytes(FontBytes::Shared(shared.clone()), i, None, None)).map(|f| self.add(f)).collect() } + /// The family and style of the face whose PostScript name is `ps` (ignoring case), loaded or + /// only scanned. + pub fn postscript_face(&self, ps: &str) -> Option<(String, String)> { + let is = |p: &Option| p.as_deref().is_some_and(|p| p.eq_ignore_ascii_case(ps)); + if let Some(f) = self.faces.iter().find(|f| is(&f.postscript)) { + return Some((f.family.clone(), f.style.clone())); + } + self.pending.values().find_map(|(display, entries)| entries.iter().find(|e| is(&e.postscript)).map(|e| (display.clone(), e.style.clone()))) + } + /// Family display names, sorted (loaded and known system families). pub fn families(&self) -> Vec { let mut v: Vec = self.families.values().map(|(d, _)| d.clone()).collect(); @@ -897,8 +912,13 @@ fn scan_dir(dir: &std::path::Path, depth: usize, out: &mut BTreeMap Option> { Some(buf) } -/// (index, family, style) of each face in a font file: outline fonts and colour fonts (Apple Color +/// (index, family, style, PostScript name) of each face in a font file: outline fonts and colour fonts (Apple Color /// Emoji draws most emoji from `sbix`, Noto Color Emoji has no outlines at all). -fn faces_in(bytes: &[u8]) -> Vec<(u32, String, String)> { +fn faces_in(bytes: &[u8]) -> Vec<(u32, String, String, Option)> { let count = match FileRef::new(bytes) { Ok(FileRef::Collection(c)) => c.len(), Ok(FileRef::Font(_)) => 1, @@ -959,7 +979,7 @@ fn faces_in(bytes: &[u8]) -> Vec<(u32, String, String)> { .then_some(())?; let (family, style) = names(&f); let family = public_family(&family?)?; - Some((i, family, style.unwrap_or_else(|| "Regular".into()))) + Some((i, family, style.unwrap_or_else(|| "Regular".into()), name_string(&f, StringId::POSTSCRIPT_NAME))) }) .collect() } @@ -989,6 +1009,14 @@ fn apple_alias(key: &str) -> Option<&'static str> { } /// Convenience: find a face with the global db. +/// The family and style of the installed face whose PostScript name is `ps`. +pub fn postscript_face(ps: &str) -> Option<(String, String)> { + if ps.is_empty() { + return None; + } + db().read().unwrap_or_else(std::sync::PoisonError::into_inner).postscript_face(ps) +} + pub fn find_face(family: &str, style: &str) -> Option> { let mut db = db().write().unwrap_or_else(std::sync::PoisonError::into_inner); db.find(family, style).or_else(|| db.default_face()) diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index 0b83e1d3..5ff1e2e6 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -2,7 +2,8 @@ use super::*; fn pending(styles: &[&str]) -> FontDb { let mut db = FontDb::default(); - let entries = styles.iter().map(|s| Pending { path: format!("no-such-dir/{s}.ttf").into(), index: 0, style: (*s).into() }).collect(); + let entries = + styles.iter().map(|s| Pending { path: format!("no-such-dir/{s}.ttf").into(), index: 0, style: (*s).into(), postscript: None }).collect(); db.pending.insert("cjk ui".into(), ("CJK UI".into(), entries)); db } @@ -221,7 +222,7 @@ fn user_font_dirs_preserve_non_utf8_paths() { /// A rescan offers new families and the styles installed since, and never a file twice. #[test] fn a_rescan_offers_fonts_installed_since() { - let entry = |s: &str| Pending { path: format!("no-such-dir/{s}.ttf").into(), index: 0, style: s.into() }; + let entry = |s: &str| Pending { path: format!("no-such-dir/{s}.ttf").into(), index: 0, style: s.into(), postscript: None }; let mut db = pending(&["Regular"]); let found = |fams: &[(&str, &[&str])]| -> BTreeMap)> { fams.iter().map(|(f, styles)| (f.to_lowercase(), ((*f).to_string(), styles.iter().map(|s| entry(s)).collect()))).collect() @@ -271,7 +272,7 @@ fn apple_system_font_names_find_the_system_font() { let mut db = FontDb::default(); db.pending.insert( "system font".into(), - ("System Font".into(), vec![Pending { path: "no-such-dir/SFNS.ttf".into(), index: 0, style: "Regular".into() }]), + ("System Font".into(), vec![Pending { path: "no-such-dir/SFNS.ttf".into(), index: 0, style: "Regular".into(), postscript: None }]), ); for name in ["SF Pro", "SF Pro Text", "SF Pro Display", "SF UI Text", "SF UI Display", ".SF NS Text", "San Francisco"] { assert!(db.has_family(name), "{name}"); @@ -324,3 +325,27 @@ fn trak_tracking_by_size() { let _ = f.tracking(12.0); } } + +/// A face is found by its PostScript name (ignoring case), loaded or only scanned: the family and +/// style it is offered under. +#[test] +fn faces_by_postscript_name() { + let mut db = FontDb::default(); + db.pending.insert( + "brand sans".into(), + ( + "Brand Sans".into(), + vec![Pending { path: "no-such-dir/b.ttf".into(), index: 0, style: "Bold".into(), postscript: Some("BrandSans-Bold".into()) }], + ), + ); + assert_eq!(db.postscript_face("brandsans-bold"), Some(("Brand Sans".to_string(), "Bold".to_string()))); + assert_eq!(db.postscript_face("BrandSans-Light"), None); + if let Some(f) = CRAFT_FONTS.first() + && let Some(face) = Face::from_bytes(FontBytes::Static(f.bytes), 0, Some(f.family), Some(f.style)) + && let Some(ps) = face.postscript.clone() + { + db.add(face); + assert_eq!(db.postscript_face(&ps), Some((f.family.to_string(), f.style.to_string()))); + } + assert!(postscript_face("").is_none()); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 998b6091..d1038576 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -18,7 +18,7 @@ and prototype interactions are still unchecked there. | Format | Figma | FigCraft read | FigCraft write | Fidelity / testing | Hours | |---|---|---|---|---|---| | `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes, shapes with text, connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message. Budgets come from the file's own size (one value per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows), so a 15.4 MB synthetic file with 300,000 layers opens whole; the file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Not read: elbowed or curved connectors without a saved path (drawn straight) and labels of connectors without a saved snapshot, table cells beyond their own layers, filled areas with their own fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed) and by reading back what the export writes; no real-world files yet | read tail 5–10, write: checks against real files 5–15 | -| `.sketch` (Sketch 48 and newer) | — (Figma's own Sketch import runs in its web app) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (with their colour adjustments as image filters), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer and background blurs, opacity and blend modes; clipping masks (a mask that shows its own style draws a copy under itself, as Sketch does; broken mask chains wrapped); text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts from PostScript names matched to installed families, variable font axes; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, layer and text styles, nested paths), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only where Sketch shows them; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids. Instances of a stack laid out at their size and texts an override changed measured again on open. Warnings: noise fills, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 47, 68 and 83 (70,000 layers open in ~3 s, debug build); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 70 in at most 4.4%, a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 1.2% on average (at most 3.2%) | 5–10 (Smart Layout as auto layout, progressive layer opacity, motion and zoom blurs) | +| `.sketch` (Sketch 48 and newer) | — (Figma's own Sketch import runs in its web app) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (with their colour adjustments as image filters), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer and background blurs, opacity and blend modes; clipping masks (a mask that shows its own style draws a copy under itself, as Sketch does; broken mask chains wrapped); text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, layer and text styles, nested paths), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only where Sketch shows them; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids. Instances of a stack laid out at their size and texts an override changed measured again on open. Warnings: noise fills, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 47, 68 and 83 (70,000 layers open in ~3 s, debug build); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 70 in at most 4.4%, a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 1.2% on average (at most 3.2%) | 5–10 (Smart Layout as auto layout, progressive layer opacity, motion and zoom blurs) | | `.jam` (FigJam), `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | | REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`) | — |