From 7cb4168e13dca45817b31c4ab26d892dd82d8612 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jindr=CC=8Cich=20S=CC=8Cars=CC=8Con?= Date: Thu, 22 Oct 2026 09:03:17 +0200 Subject: [PATCH] M6: Sketch import: fixes from the PR review - --no-system-fonts holds for .sketch imports too: the CLI opts the process out, so the import's font matching doesn't scan. - Shared text styles get the installed family and platform tracking their linked layers get. - Each text run writes its letter spacing, line height and font axes, neutral when it has none, instead of taking the first run's. - The unsupported-drop hint and its catalogs list .sketch. - A test sends damaged .sketch data through file.open and file.import. - Stack items are matched to their source layers through a map. - Docs: .sketch is a convert input; the Carbon kit's Sketch 47 edition is refused (the 68 and 83 ones open). Co-Authored-By: Claude Opus 5.5 --- apps/figcraft-cli/src/main.rs | 3 ++ apps/figcraft-cli/tests/fonts.rs | 26 +++++++++++++ crates/engine/src/cmd/file.rs | 11 ++++++ crates/engine/src/sketch_import_tests.rs | 49 +++++++++++++++++++++++- crates/engine/src/tests.rs | 13 +++++++ crates/format/src/sketch/stack.rs | 11 ++++-- crates/format/src/sketch/text.rs | 12 +++--- crates/format/src/sketch/text_tests.rs | 21 ++++++++++ crates/text/src/fontdb.rs | 13 ++++++- crates/text/src/lib.rs | 4 +- crates/ui-egui/locales/bn.toml | 2 +- crates/ui-egui/locales/de.toml | 2 +- crates/ui-egui/locales/en.toml | 2 +- crates/ui-egui/locales/es.toml | 2 +- crates/ui-egui/locales/fi.toml | 2 +- crates/ui-egui/locales/fr.toml | 2 +- crates/ui-egui/locales/ka.toml | 2 +- crates/ui-egui/locales/nl.toml | 2 +- crates/ui-egui/locales/pl.toml | 2 +- crates/ui-egui/locales/pt-BR.toml | 2 +- crates/ui-egui/locales/ru.toml | 2 +- crates/ui-egui/locales/sv.toml | 2 +- crates/ui-egui/src/home.rs | 2 +- crates/ui-egui/src/home_tests.rs | 2 +- docs/cli.md | 2 +- docs/file-format-parity.md | 4 +- 26 files changed, 166 insertions(+), 31 deletions(-) diff --git a/apps/figcraft-cli/src/main.rs b/apps/figcraft-cli/src/main.rs index badc5bc3..fb96cd85 100644 --- a/apps/figcraft-cli/src/main.rs +++ b/apps/figcraft-cli/src/main.rs @@ -108,6 +108,9 @@ fn run(argv: &[String]) -> CliResult { // Text lays out with the installed fonts, like the desktop app, so headless renders and // auto layout sizes match what users see. figcraft_text::scan_system_fonts_on_demand(); + } else { + // Nothing scans them then, not even a `.sketch` import matching its fonts. + figcraft_text::opt_out_of_system_fonts(); } let Some((cmd, rest)) = argv.split_first() else { return Err(CliError::Usage("missing subcommand".into())) }; match cmd.as_str() { diff --git a/apps/figcraft-cli/tests/fonts.rs b/apps/figcraft-cli/tests/fonts.rs index ef5c638f..e01dac10 100644 --- a/apps/figcraft-cli/tests/fonts.rs +++ b/apps/figcraft-cli/tests/fonts.rs @@ -67,3 +67,29 @@ fn info_lists_the_fonts_a_file_uses_that_are_missing() { let shown = String::from_utf8_lossy(&out.stdout); assert!(shown.contains("missing font \"FigCraft Missing CLI\": 2 text layers"), "{shown}"); } + +/// A synthetic `.sketch` file: one page with one Helvetica text. +const SKETCH: &str = "UEsDBBQAAAAIAOFFVl2B8d55RwAAAFcAAAANAAAAZG9jdW1lbnQuanNvbqtWik/OSSwuVrJSUErJTy7NTc0rUdJRUCpITE8FCUZXIynwDfYK9vdzy8xJDUpNSy1KzUtOBamNL0pNA0mD9egHKNXG1gIAUEsDBBQAAAAIAOFFVl0B3thgPQAAAEkAAAAJAAAAbWV0YS5qc29uq1ZKLChQslJQSs7P1UvKz0jNzUzMS85PycxL1yvOTi1JzjBW0lEAKQpLLSrOzM8DqTUzAYmVwQUMjUxrAVBLAwQUAAAACADhRVZdo5nc2bkAAABnAQAADAAAAHBhZ2VzL1AuanNvbm1PQQrCMBD8StmzB1voxZsgUg+CUG8iJU3XNhITaVZtLf27SWylFEPIzgyzs5sOMi6ZMbAK4M5KhEUAhc50fkVOu42TD05T7IaeDB7JWqxd16mbJBA29CfhOE3w5FJ/WQeNfZdWaYf6EgVVFseOVCjKiiwL495SRlSL/EFYpBao0geYEUIiYGoatpOaMxJaDfkSVekHRHNvB/t0PZuw1Yp+mvfMWsZfJSifSIIzt4IRbyeGUW/P2d0PUEsBAhQDFAAAAAgA4UVWXYHx3nlHAAAAVwAAAA0AAAAAAAAAAAAAAIABAAAAAGRvY3VtZW50Lmpzb25QSwECFAMUAAAACADhRVZdAd7YYD0AAABJAAAACQAAAAAAAAAAAAAAgAFyAAAAbWV0YS5qc29uUEsBAhQDFAAAAAgA4UVWXaOZ3Nm5AAAAZwEAAAwAAAAAAAAAAAAAAIAB1gAAAHBhZ2VzL1AuanNvblBLBQYAAAAAAwADAKwAAAC5AQAAAAA="; + +/// Opening a `.sketch` file (whose import matches fonts against the installed ones) keeps to +/// `--no-system-fonts` too: the run still knows only the built-in families. +#[test] +fn sketch_imports_keep_to_no_system_fonts() { + let d = std::env::temp_dir().join(format!("figcraft-cli-fonts-sketch-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + let script = d.join("open.json"); + let steps = json!([{"command": "file.open", "params": {"data": SKETCH, "name": "x.sketch"}}, {"command": "text.fonts"}]); + std::fs::write(&script, steps.to_string()).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_figcraft-cli")) + .arg("run") + .arg(&script) + .arg("--no-system-fonts") + .env_remove("FIGCRAFT_NO_SYSTEM_FONTS") + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let lines: Vec = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(lines[0]["ok"], json!(true), "{lines:?}"); + let fonts: Vec = serde_json::from_value(lines[1]["result"].clone()).unwrap(); + assert_eq!(fonts, families(&["--no-system-fonts"], false), "the import didn't scan the system fonts"); +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 8f7da824..8bbdc735 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -633,6 +633,12 @@ fn match_font_families(doc: &mut Document) { } } } + // Shared text styles too, so they stay like the layers linked to them. + for st in &mut doc.styles { + if let StyleKind::Text { style } = &mut st.kind { + fix(style); + } + } } /// Sketch draws text with the tracking a font's `trak` table gives at its size (Apple's text engine @@ -668,6 +674,11 @@ fn platform_tracking(doc: &mut Document) { } } } + for st in &mut doc.styles { + if let StyleKind::Text { style } = &mut st.kind { + track(style); + } + } } /// Families Sketch (Apple's text system) gives a fifth more than their ascent and descent as their diff --git a/crates/engine/src/sketch_import_tests.rs b/crates/engine/src/sketch_import_tests.rs index 292cd019..7ecdd467 100644 --- a/crates/engine/src/sketch_import_tests.rs +++ b/crates/engine/src/sketch_import_tests.rs @@ -17,13 +17,22 @@ fn sketch(app_version: &str, pages: &[(&str, &str)]) -> Vec { /// [`sketch`] with `layers` on the first page. fn sketch_with(app_version: &str, pages: &[(&str, &str)], layers: &[Value]) -> Vec { + sketch_with_doc(app_version, pages, layers, json!({})) +} + +/// [`sketch_with`] with the fields of `extra` added to `document.json` (shared styles…). +fn sketch_with_doc(app_version: &str, pages: &[(&str, &str)], layers: &[Value], extra: Value) -> Vec { let refs: Vec = pages.iter().map(|(id, _)| json!({"_class": "MSJSONFileReference", "_ref": format!("pages/{id}")})).collect(); + let mut document = json!({"_class": "document", "pages": refs}); + for (k, v) in extra.as_object().into_iter().flatten() { + document[k] = v.clone(); + } let mut out = Vec::new(); { let mut z = zip::ZipWriter::new(std::io::Cursor::new(&mut out)); let o = zip::write::SimpleFileOptions::default(); z.start_file("document.json", o).unwrap(); - z.write_all(json!({"_class": "document", "pages": refs}).to_string().as_bytes()).unwrap(); + z.write_all(document.to_string().as_bytes()).unwrap(); z.start_file("meta.json", o).unwrap(); // The format version that Sketch writes (103 for 50; 110 and up from 52). let version = if app_version.split('.').next().and_then(|v| v.parse::().ok()).is_some_and(|v| v >= 52) { 125 } else { 103 }; @@ -476,3 +485,41 @@ fn sketch_text_in_a_stack_stays_put() { let after = doc.world_bounds(label).unwrap(); assert!((before.y0 - after.y0).abs() < 1e-6, "{before:?} → {after:?}"); } + +/// Shared text styles get what their linked layers get on import: the installed family's name and +/// the platform's tracking (a layer and its style stay alike). +#[test] +fn sketch_shared_text_styles_match_their_layers() { + if !std::path::Path::new("/System/Library/Fonts/SFNS.ttf").exists() { + return; + } + figcraft_text::fontdb::scan_system_fonts(); + let attrs = json!({"MSAttributedStringFontAttribute": {"attributes": {"name": "SFUIText-Regular", "size": 13}}}); + let style = json!({"_class": "style", "textStyle": {"_class": "textStyle", "encodedAttributes": attrs.clone()}}); + let shared = json!({"_class": "sharedStyle", "do_objectID": "TS", "name": "Body", "value": style.clone()}); + let run = json!({"location": 0, "length": 2, "attributes": attrs}); + let mut linked = style; + linked["sharedObjectID"] = json!("TS"); + let t = shape( + "text", + "Label", + [0.0, 0.0, 100.0, 20.0], + json!({"attributedString": {"string": "Hi", "attributes": [run]}, "textBehaviour": 0, "style": linked}), + ); + let extra = json!({"layerTextStyles": {"_class": "sharedTextStyleContainer", "objects": [shared]}}); + let data = base64::engine::general_purpose::STANDARD.encode(sketch_with_doc("64", &[("A", "Page")], &[t], extra)); + 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") }; + let st = doc + .styles + .iter() + .find_map(|st| match &st.kind { + figcraft_doc::StyleKind::Text { style } if st.name == "Body" => Some(style.clone()), + _ => None, + }) + .unwrap(); + assert_eq!(st.font_family, td.style.font_family); + assert_eq!(st.letter_spacing.resolve(13.0), td.style.letter_spacing.resolve(13.0), "{st:?}"); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index eeec9f04..6cf598a0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -633,3 +633,16 @@ fn find_replace_changing_only_the_case_replaces_every_occurrence() { assert_eq!(s.doc().unwrap().node(t).unwrap().kind.text().unwrap().characters, "FigCraft and FigCraft, FigCraft"); assert_eq!(s.doc().unwrap().node(f).unwrap().name, "FigCraft / FigCraft"); } + +/// Damaged and too-old `.sketch` data sent to the file commands (which the junk sweep skips) fail +/// with an ordinary error, not a caught panic. +#[test] +fn damaged_sketch_data_fails_without_panicking() { + for data in ["UEsDBBQAAAAIAP////8=", "U1FMaXRlIGZvcm1hdCAzAA=="] { + for cmd in ["file.open", "file.import"] { + let mut s = sess(); + let r = s.execute(cmd, &json!({"data": data, "name": "x.sketch"})); + assert!(matches!(r, Err(ref e) if !matches!(e, EngineError::Internal { .. })), "{cmd}: {r:?}"); + } + } +} diff --git a/crates/format/src/sketch/stack.rs b/crates/format/src/sketch/stack.rs index a6b2ddb2..89f67ca8 100644 --- a/crates/format/src/sketch/stack.rs +++ b/crates/format/src/sketch/stack.rs @@ -62,12 +62,17 @@ pub(crate) fn apply(l: &Value, node: &mut JsonMap) { node.insert("primaryAxisSizingMode".into(), json!(mode(main))); node.insert("counterAxisSizingMode".into(), json!(mode(cross))); // Items: flow order, sizing, absolute ones. - let sources: Vec<&Value> = super::tree::layers(l).iter().collect(); + // Source layers by id (the first of a repeated id). + let mut sources: std::collections::BTreeMap<&str, &Value> = std::collections::BTreeMap::new(); + for src in super::tree::layers(l) { + if let Some(id) = src.get("do_objectID").and_then(Value::as_str) { + sources.entry(id).or_insert(src); + } + } if let Some(kids) = node.get_mut("children").and_then(Value::as_array_mut) { // Children were built one per source layer, skipped ones aside: match them by id. for kid in kids.iter_mut() { - let id = kid.get("id").and_then(Value::as_str).map(str::to_string); - let Some(src) = sources.iter().find(|s| id.is_some() && s.get("do_objectID").and_then(Value::as_str) == id.as_deref()) else { continue }; + let Some(src) = kid.get("id").and_then(Value::as_str).and_then(|id| sources.get(id).copied()) else { continue }; let Some(m) = kid.as_object_mut() else { continue }; item(src, m, row, stretch); } diff --git a/crates/format/src/sketch/text.rs b/crates/format/src/sketch/text.rs index 027de660..74cfa21c 100644 --- a/crates/format/src/sketch/text.rs +++ b/crates/format/src/sketch/text.rs @@ -129,18 +129,18 @@ pub(crate) fn type_style(cx: &mut Cx, a: &Value) -> Value { cx.warn("text without a font uses Helvetica"); } let mut s = json!({"fontFamily": family, "fontStyle": style, "fontSize": size.min(10_000.0)}); - if let Some(v) = font.and_then(|f| f.get("variation")).and_then(variations) { - s["fontVariations"] = v; - } + // Every field is written, neutral when the run has none: a run's style starts from the text's + // (its first run's), and an unwritten field would keep that one's value. + s["fontVariations"] = font.and_then(|f| f.get("variation")).and_then(variations).unwrap_or_else(|| json!({})); let p = a.get("paragraphStyle"); let line = |k: &str| p.and_then(|p| p.get(k)).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0); if let Some(lh) = line("maximumLineHeight").or_else(|| line("minimumLineHeight")) { s["lineHeightPx"] = json!(lh.min(1e4)); s["lineHeightUnit"] = json!("PIXELS"); + } else { + s["lineHeightUnit"] = json!("INTRINSIC_%"); } - if let Some(k) = a.get("kerning").and_then(Value::as_f64).filter(|k| k.is_finite()) { - s["letterSpacing"] = json!(k); - } + s["letterSpacing"] = json!(a.get("kerning").and_then(Value::as_f64).filter(|k| k.is_finite()).unwrap_or(0.0).clamp(-1e4, 1e4)); let set = |k: &str| a.get(k).and_then(Value::as_i64).is_some_and(|v| v != 0); s["textDecoration"] = json!(if set("underlineStyle") { "UNDERLINE" diff --git a/crates/format/src/sketch/text_tests.rs b/crates/format/src/sketch/text_tests.rs index 8adef1ea..0e8a4a27 100644 --- a/crates/format/src/sketch/text_tests.rs +++ b/crates/format/src/sketch/text_tests.rs @@ -250,3 +250,24 @@ fn postscript_names_find_installed_fonts() { let (doc, _) = import(&z, "f").unwrap(); assert_eq!(data(&doc, "A").style.font_family, "Courier New PSMT"); } + +/// A run without kerning, a fixed line height or font axes has none: it doesn't take the first +/// run's (the text's base style) as its own. +#[test] +fn later_runs_dont_inherit_the_first_runs_settings() { + let mut t = text("Mixed", 0.0, 0.0, 200.0, 40.0, "AaBb", &[(0, 2, "Skia", 20.0, BLACK), (2, 2, "Helvetica", 14.0, BLACK)]); + let first = &mut t["attributedString"]["attributes"][0]["attributes"]; + first["kerning"] = json!(2); + first["paragraphStyle"]["minimumLineHeight"] = json!(24); + first["paragraphStyle"]["maximumLineHeight"] = json!(24); + first["MSAttributedStringFontAttribute"]["attributes"]["variation"] = json!({"2003265652": 3}); + let (doc, _) = open(vec![t]); + let td = data(&doc, "Mixed"); + let at = |i: usize| td.runs.iter().find(|r| r.start <= i && i < r.end).map_or(&td.style, |r| &r.style); + assert_eq!(at(0).letter_spacing.resolve(20.0), 2.0); + let second = at(2); + assert_eq!(second.font_family, "Helvetica"); + assert_eq!(second.letter_spacing.resolve(14.0), 0.0, "{second:?}"); + assert_eq!(second.line_height, figcraft_doc::LineHeight::Auto, "{second:?}"); + assert!(second.variations.is_empty(), "{second:?}"); +} diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 34d76b12..b004d7e1 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -526,6 +526,8 @@ pub struct Rescan { static DB: OnceLock> = OnceLock::new(); /// Set by [`scan_system_fonts_on_demand`]. static ON_DEMAND: AtomicBool = AtomicBool::new(false); +/// Set by [`opt_out_of_system_fonts`]. +static OPTED_OUT: AtomicBool = AtomicBool::new(false); /// Done once per process: concurrent callers wait for the one scan. static SCANNED: OnceLock<()> = OnceLock::new(); /// Directory walks done (at most one). @@ -1111,10 +1113,17 @@ pub fn load_font_bytes(bytes: Vec) -> Vec { families } -/// `FIGCRAFT_NO_SYSTEM_FONTS` is set (and not `0`): renders use only the embedded fonts. +/// `FIGCRAFT_NO_SYSTEM_FONTS` is set (and not `0`), or the process opted out +/// ([`opt_out_of_system_fonts`]): renders use only the embedded fonts. #[cfg(not(target_arch = "wasm32"))] fn system_fonts_opted_out() -> bool { - std::env::var_os("FIGCRAFT_NO_SYSTEM_FONTS").is_some_and(|v| !v.is_empty() && v != "0") + OPTED_OUT.load(Ordering::Relaxed) || std::env::var_os("FIGCRAFT_NO_SYSTEM_FONTS").is_some_and(|v| !v.is_empty() && v != "0") +} + +/// Use only the embedded fonts for the rest of the process, as `FIGCRAFT_NO_SYSTEM_FONTS` does +/// (headless runs with `--no-system-fonts`): no call scans the system fonts after this. +pub fn opt_out_of_system_fonts() { + OPTED_OUT.store(true, Ordering::Relaxed); } /// Every font text can use is known: the system fonts were indexed, or there are none to index diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 50cd28dd..1663ab13 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -17,8 +17,8 @@ pub use breaks::grapheme_step; pub use color::{ColorBitmap, ColorInk, ColorLayer}; pub use fontdb::{ Axis, CRAFT_FONTS, Coords, Face, FontDb, NamedInstance, Rescan, axis_label, db, face_with_char, family_names, family_styles, find_face, - has_family, installed_fonts_known, load_font_bytes, no_coords, rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, - system_fonts_scanned, + has_family, installed_fonts_known, load_font_bytes, no_coords, opt_out_of_system_fonts, rescan_system_fonts, scan_system_fonts, + scan_system_fonts_on_demand, system_fonts_scanned, }; pub use layout::{Decoration, Glyph, Line, TextLayout, layout}; pub use onpath::OnPath; diff --git a/crates/ui-egui/locales/bn.toml b/crates/ui-egui/locales/bn.toml index adedc983..eb3a88db 100644 --- a/crates/ui-egui/locales/bn.toml +++ b/crates/ui-egui/locales/bn.toml @@ -416,7 +416,7 @@ status = "draft — needs native review" "Draw" = "আঁকুন" "Draw a frame" = "একটি ফ্রেম আঁকুন" "Drawing tools" = "অঙ্কন টুলস" -"Drop a .figcraft, .fig, .json, .svg or image file." = "একটি .figcraft, .fig, .json, .svg বা ছবির ফাইল ড্রপ করুন।" +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "একটি .figcraft, .fig, .sketch, .json, .svg বা ছবির ফাইল ড্রপ করুন।" "Drop to import" = "ইম্পোর্ট করতে ড্রপ করুন" "Drop to open" = "খুলতে ড্রপ করুন" "Drop shadow" = "ড্রপ শ্যাডো" diff --git a/crates/ui-egui/locales/de.toml b/crates/ui-egui/locales/de.toml index f61464b8..04d1af62 100644 --- a/crates/ui-egui/locales/de.toml +++ b/crates/ui-egui/locales/de.toml @@ -397,7 +397,7 @@ status = "draft — needs native review" "Drag the stroke to add a width point" = "Ziehen Sie an der Kontur, um einen Breitenpunkt hinzuzufügen" "Draw" = "Zeichnen" "Drawing tools" = "Zeichenwerkzeuge" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Legen Sie eine .figcraft-, .fig-, .json-, .svg- oder Bilddatei ab." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Legen Sie eine .figcraft-, .fig-, .sketch-, .json-, .svg- oder Bilddatei ab." "Drop to import" = "Zum Importieren ablegen" "Drop to open" = "Zum Öffnen ablegen" "Drop shadow" = "Schlagschatten" diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index ae566fc8..1180bf41 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -417,7 +417,7 @@ name = "English" "Draw" = "Draw" "Draw a frame" = "Draw a frame" "Drawing tools" = "Drawing tools" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Drop a .figcraft, .fig, .json, .svg or image file." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Drop a .figcraft, .fig, .sketch, .json, .svg or image file." "Drop to import" = "Drop to import" "Drop to open" = "Drop to open" "Drop shadow" = "Drop shadow" diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index 596feda6..7ed208b0 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -418,7 +418,7 @@ status = "draft — needs native review" "Draw" = "Dibujar" "Draw a frame" = "Dibuja un marco" "Drawing tools" = "Herramientas de dibujo" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Suelta un archivo .figcraft, .fig, .json, .svg o de imagen." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Suelta un archivo .figcraft, .fig, .sketch, .json, .svg o de imagen." "Drop to import" = "Suelta para importar" "Drop to open" = "Suelta para abrir" "Drop shadow" = "Sombra paralela" diff --git a/crates/ui-egui/locales/fi.toml b/crates/ui-egui/locales/fi.toml index 205a9d29..3102fbf4 100644 --- a/crates/ui-egui/locales/fi.toml +++ b/crates/ui-egui/locales/fi.toml @@ -418,7 +418,7 @@ status = "draft — needs native review" "Draw" = "Piirrä" "Draw a frame" = "Piirrä kehys" "Drawing tools" = "Piirtotyökalut" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Pudota .figcraft-, .fig-, .json-, .svg- tai kuvatiedosto." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Pudota .figcraft-, .fig-, .sketch-, .json-, .svg- tai kuvatiedosto." "Drop shadow" = "Heittovarjo" "Drop to import" = "Tuo pudottamalla" "Drop to open" = "Avaa pudottamalla" diff --git a/crates/ui-egui/locales/fr.toml b/crates/ui-egui/locales/fr.toml index b038b335..0cc87213 100644 --- a/crates/ui-egui/locales/fr.toml +++ b/crates/ui-egui/locales/fr.toml @@ -415,7 +415,7 @@ status = "draft — needs native review" "Draw" = "Dessin" "Draw a frame" = "Tracer un cadre" "Drawing tools" = "Outils de dessin" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Déposez un fichier .figcraft, .fig, .json, .svg ou une image." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Déposez un fichier .figcraft, .fig, .sketch, .json, .svg ou une image." "Drop shadow" = "Ombre portée" "Drop to import" = "Déposer pour importer" "Drop to open" = "Déposer pour ouvrir" diff --git a/crates/ui-egui/locales/ka.toml b/crates/ui-egui/locales/ka.toml index 5b73b4fb..20b4bce6 100644 --- a/crates/ui-egui/locales/ka.toml +++ b/crates/ui-egui/locales/ka.toml @@ -418,7 +418,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv "Draw" = "ხატვა" "Draw a frame" = "დახატეთ ჩარჩო" "Drawing tools" = "ხატვის ხელსაწყოები" -"Drop a .figcraft, .fig, .json, .svg or image file." = "ჩააგდეთ .figcraft, .fig, .json, .svg ან გამოსახულების ფაილი." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "ჩააგდეთ .figcraft, .fig, .sketch, .json, .svg ან გამოსახულების ფაილი." "Drop to import" = "ჩააგდეთ იმპორტისთვის" "Drop to open" = "ჩააგდეთ გასახსნელად" "Drop shadow" = "ჩრდილი" diff --git a/crates/ui-egui/locales/nl.toml b/crates/ui-egui/locales/nl.toml index 54851043..6d276911 100644 --- a/crates/ui-egui/locales/nl.toml +++ b/crates/ui-egui/locales/nl.toml @@ -418,7 +418,7 @@ status = "draft — needs native review" "Draw" = "Tekenen" "Draw a frame" = "Teken een frame" "Drawing tools" = "Tekengereedschap" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Laat een .figcraft-, .fig-, .json-, .svg- of afbeeldingsbestand los." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Laat een .figcraft-, .fig-, .sketch-, .json-, .svg- of afbeeldingsbestand los." "Drop shadow" = "Slagschaduw" "Drop to import" = "Loslaten om te importeren" "Drop to open" = "Loslaten om te openen" diff --git a/crates/ui-egui/locales/pl.toml b/crates/ui-egui/locales/pl.toml index 23f7dee8..0453ee7b 100644 --- a/crates/ui-egui/locales/pl.toml +++ b/crates/ui-egui/locales/pl.toml @@ -415,7 +415,7 @@ status = "draft — needs native review" "Draw" = "Rysuj" "Draw a frame" = "Narysuj ramkę" "Drawing tools" = "Narzędzia rysowania" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Upuść plik .figcraft, .fig, .json, .svg lub plik obrazu." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Upuść plik .figcraft, .fig, .sketch, .json, .svg lub plik obrazu." "Drop to import" = "Upuść, aby zaimportować" "Drop to open" = "Upuść, aby otworzyć" "Drop shadow" = "Cień" diff --git a/crates/ui-egui/locales/pt-BR.toml b/crates/ui-egui/locales/pt-BR.toml index d8f857e0..424a4337 100644 --- a/crates/ui-egui/locales/pt-BR.toml +++ b/crates/ui-egui/locales/pt-BR.toml @@ -1662,7 +1662,7 @@ status = "draft — needs native review" "Dec" = "dez." "Design system starter" = "Ponto de partida para sistema de design" "Draw a frame" = "Desenhe um quadro" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Solte um arquivo .figcraft, .fig, .json, .svg ou uma imagem." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Solte um arquivo .figcraft, .fig, .sketch, .json, .svg ou uma imagem." "Drop to import" = "Solte para importar" "Drop to open" = "Solte para abrir" "Edited {when}" = "Editado {when}" diff --git a/crates/ui-egui/locales/ru.toml b/crates/ui-egui/locales/ru.toml index 6e173a92..2d5169a0 100644 --- a/crates/ui-egui/locales/ru.toml +++ b/crates/ui-egui/locales/ru.toml @@ -417,7 +417,7 @@ name = "Русский" "Draw" = "Рисование" "Draw a frame" = "Нарисовать Frame" "Drawing tools" = "Инструменты рисования" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Перетащите файл .figcraft, .fig, .json, .svg или изображение." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Перетащите файл .figcraft, .fig, .sketch, .json, .svg или изображение." "Drop shadow" = "Внешняя тень" "Drop to import" = "Отпустите, чтобы импортировать" "Drop to open" = "Отпустите, чтобы открыть" diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index d86779e0..2f8f3d95 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -412,7 +412,7 @@ name = "Svenska" "Draw" = "Rita" "Draw a frame" = "Rita en ram" "Drawing tools" = "Ritverktyg" -"Drop a .figcraft, .fig, .json, .svg or image file." = "Släpp en .figcraft-, .fig-, .json- eller .svg-fil eller en bildfil." +"Drop a .figcraft, .fig, .sketch, .json, .svg or image file." = "Släpp en .figcraft-, .fig-, .sketch-, .json- eller .svg-fil eller en bildfil." "Drop to import" = "Släpp för att importera" "Drop to open" = "Släpp för att öppna" "Drop shadow" = "Släppskugga" diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index b532d9a7..664ca159 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -181,7 +181,7 @@ fn dropped(app: &mut FigApp, ctx: &egui::Context) { let files = ctx.input(|i| i.raw.dropped_files.clone()); for f in files { if !crate::opens(f.path()) { - app.toast(tr("Drop a .figcraft, .fig, .json, .svg or image file.")); + app.toast(tr("Drop a .figcraft, .fig, .sketch, .json, .svg or image file.")); continue; } crate::pending_open::open_dropped(app, &f); diff --git a/crates/ui-egui/src/home_tests.rs b/crates/ui-egui/src/home_tests.rs index fc51bfb1..71225db4 100644 --- a/crates/ui-egui/src/home_tests.rs +++ b/crates/ui-egui/src/home_tests.rs @@ -898,7 +898,7 @@ fn dropping_an_unsupported_file_on_the_home_screen_opens_nothing() { drop_file(&mut u, &path); assert!(u.app.session.docs.is_empty()); assert!(u.app.ui.home); - assert_eq!(u.app.ui.toast.as_ref().map(|t| t.0.as_str()), Some("Drop a .figcraft, .fig, .json, .svg or image file.")); + assert_eq!(u.app.ui.toast.as_ref().map(|t| t.0.as_str()), Some("Drop a .figcraft, .fig, .sketch, .json, .svg or image file.")); } #[test] diff --git a/docs/cli.md b/docs/cli.md index bf783d11..84f4617f 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -87,7 +87,7 @@ figcraft-cli export app.figcraft -o handoff.fig ### `convert ` -By extension. Inputs: `.figcraft`, `.json` (FigCraft or REST API file JSON), `.fig` (best effort), `.svg` (an editable frame: groups, +By extension. Inputs: `.figcraft`, `.json` (FigCraft or REST API file JSON), `.fig` (best effort), `.sketch` (Sketch 48 or newer, best effort), `.svg` (an editable frame: groups, shapes, text, gradients, masks and effects; `info` lists what it left out as `note:` lines), `.png/.jpg/.webp/.gif/.tif/.bmp` (an image layer). Outputs: `.figcraft`, `.json` (FigCraft JSON, pretty-printed), `.svg`, `.png/.jpg/.webp` (the current page rendered at 1x with its background), `.pdf` (the current page's diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 11867d88..5fb7532c 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) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **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 with Sketch's geometry, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer and background blurs, opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; 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 (hidden, as Sketch shows them only in its layout view). 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 (0.8% on average) (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 0.9% on average (at most 1.9%) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session) | +| `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **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 with Sketch's geometry, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer and background blurs, opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; 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 (hidden, as Sketch shows them only in its layout view). 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 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); 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 (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session) | | `.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`) | — | @@ -166,7 +166,7 @@ each. | Date | Change | Summary | |---|---|---| -| 2026-10-21 | minor | `.sketch` import (best effort): files saved by Sketch 48 and newer open and import like `.fig` files (open, import, drop, CLI, MCP), mapped onto the REST importer: layers, paths, shape groups and booleans, styles and effects, masks, text, symbols with overrides (live instances), shared styles, Color Variables, prototype links, export settings and grids; older files are refused with a message. Sketch 2025 and newer: frames, graphics, stacks as auto layout, corners, pins and sizing, tints, per-side borders, blur lists. Checked on fixtures and locally on real Sketch 50, 64 and 2026 files and the IBM Carbon Design Kit (Sketch 47, 68, 83). Numbers unchanged | +| 2026-10-21 | minor | `.sketch` import (best effort): files saved by Sketch 48 and newer open and import like `.fig` files (open, import, drop, CLI, MCP), mapped onto the REST importer: layers, paths, shape groups and booleans, styles and effects, masks, text, symbols with overrides (live instances), shared styles, Color Variables, prototype links, export settings and grids; older files are refused with a message. Sketch 2025 and newer: frames, graphics, stacks as auto layout, corners, pins and sizing, tints, per-side borders, blur lists. Checked on fixtures and locally on real Sketch 50, 64 and 2026 files and the IBM Carbon Design Kit (Sketch 68 and 83 open; the Sketch 47 edition is refused). Numbers unchanged | | 2026-10-18 | minor | REST file JSON import keeps `SLOT` layers (#792): they were dropped with everything placed in them, which emptied every instance's slot. A slot in a main component becomes a slot frame bound to its `SLOT` property (the one it references, else the one named like it, else the only one left), and an instance's slot holds the instance's own content, kept across syncs, moves of the mains and saving, unless the instance's property value is the main's default content (without values, a slot that holds layers keeps them). Instances in slot content link to their own mains. Slot content limits, preferred-only and preferred components are warnings. Synthetic files only. Numbers unchanged | | 2026-10-17 | minor | REST file JSON import reads grid track sizes from the CSS track strings `gridColumnsSizing` / `gridRowsSizing` (fixed px, fill fr, hug `auto`, `minmax(0, 1fr)`, `repeat()`; other tracks stay equal) (#465). Numbers unchanged | | 2026-10-17 | minor | The community batches #727 and #728 in the `.fig` row: instance identity and cached library components, overrides by key, text style precedence, grid track sizes, slot content, labels of connectors saved with their path, skip ink, paragraph options, list start numbers, vertical trim, per-point stroke joins, text on a path, image adjustments (also REST), images in the message; budgets from the file's size; the journal keeps no file bytes; the import report. Not read cut to what's left. A `.fig` copy from Save as. Pasted content: layers copied from another design app, best effort (tested only with clipboard HTML made from our own export), and images under Wayland (not run there). All on synthetic files: summary and hours unchanged |