From 0a94b092eb56decd9ca85779fa8f6b1a0553ec23 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 10:08:47 -0500 Subject: [PATCH 01/11] refactor(svg): share XML escaping and character validation --- Cargo.lock | 10 ++++++++++ Cargo.toml | 1 + crates/svg/Cargo.toml | 1 + crates/svg/src/lib.rs | 13 +++---------- crates/svg/src/tests.rs | 12 ++++++++++++ docs/target-app-parity.md | 2 ++ 6 files changed, 29 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 40e8410ff..d6d010579 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1236,6 +1236,15 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -2141,6 +2150,7 @@ name = "figcraft-svg" version = "0.18.1" dependencies = [ "base64 0.22.1", + "craft-xml", "figcraft-color", "figcraft-doc", "figcraft-geom", diff --git a/Cargo.toml b/Cargo.toml index aa4c0f79a..05aa2d393 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/figcraft" [workspace.dependencies] +craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } # internal figcraft-geom = { path = "crates/geom" } diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index d248bdf07..57f578249 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -9,6 +9,7 @@ description = "FigCraft SVG export (shapes, gradients, images, strokes, effects workspace = true [dependencies] +craft-xml = { workspace = true } figcraft-geom = { workspace = true } figcraft-color = { workspace = true } figcraft-doc = { workspace = true } diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 680f0eb4a..97c8ba0f7 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -195,16 +195,9 @@ fn blend_style(b: figcraft_color::BlendMode) -> String { } } -/// `s` escaped for XML text and attribute values; characters XML 1.0 forbids (control characters -/// other than tab, newline and carriage return, U+FFFE and U+FFFF) are left out. -fn esc(s: &str) -> String { - s.chars().filter(|&c| xml_char(c)).collect::().replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) -} - -/// Whether XML 1.0 allows `c` (see [`esc`]). -fn xml_char(c: char) -> bool { - !matches!(c, '\u{0}'..='\u{8}' | '\u{b}' | '\u{c}' | '\u{e}'..='\u{1f}' | '\u{fffe}' | '\u{ffff}') -} +// Shared XML wire escaping and character validity; layer-name policy stays below. +// Attribute escaping also preserves tabs/LF/CR through XML readers' whitespace normalization. +use craft_xml::{esc_attr as esc, is_xml_char as xml_char}; fn hex(c: Color) -> String { format!("#{}", c.to_hex()) diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index 8bce898da..e2a262890 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -451,3 +451,15 @@ fn a_whole_ellipse_drawn_backwards_keeps_its_simple_stroke() { assert_eq!(backwards, forwards, "{align:?}"); } } + +#[test] +fn shared_xml_escaping_keeps_markup_controls_and_attribute_whitespace() { + let input = "A<&\"'\t\n\r\u{1}\u{fffe}🦊"; + assert_eq!(super::esc(input), "A<&"' 🦊"); + let markup = format!("", super::esc(input)); + let root = craft_xml::parse(markup.as_bytes()).unwrap(); + assert_eq!(root.attr("label"), Some("A<&\"'\t\n\r🦊")); + for c in ['\0', '\u{b}', '\u{fffe}', '\u{ffff}'] { + assert!(!super::xml_char(c)); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f7f1d7054..c88776361 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -11,6 +11,8 @@ summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu c [`prototyping-parity.md`](prototyping-parity.md), [`dev-mode-parity.md`](dev-mode-parity.md), [`collaboration-parity.md`](collaboration-parity.md), [`boards-parity.md`](boards-parity.md). +> SVG XML wire follow-up (2026-11-16): export escaping and XML 1.0 character checks delegate to pinned `craft-xml`. Attribute tab/LF/CR are emitted as references to survive XML normalization. Local SVG document/path serialization and import mapping remain; this scoped change does not raise the parity grade. Hosted validation is pending. + ## Headline | Number | Value | Kind | From f0a34a1221438b9615cf535eb907b016f1960547 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:55:24 +0100 Subject: [PATCH 02/11] M6: i18n catalog test reads cargo metadata for the host only (#2413) craft_fig_src() ran `cargo metadata --offline` with no platform filter. Cargo then needs every target's packages in its cache, and a cache that holds only what a host build fetched lacks iOS-only crates such as accesskit_ios, so the nightly FreeBSD job failed. Ask the same cargo for its host triple (`cargo -vV`) and pass it as `--filter-platform`. --- crates/ui-egui/src/i18n/tests.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 5e3f1d059..572cd5de7 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -217,8 +217,13 @@ fn importer_notes() -> BTreeSet { /// The `src` directory of the craft-fig sources this build uses, as Cargo resolved them. fn craft_fig_src() -> std::path::PathBuf { let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()); - let out = std::process::Command::new(cargo) - .args(["metadata", "--format-version", "1", "--offline"]) + // Unfiltered, `cargo metadata` needs every target's packages (accesskit_ios, ...) in Cargo's + // cache, and `--offline` cannot fetch them; a build fetches only the host's. Filter to the host. + let version = std::process::Command::new(&cargo).arg("-vV").output().unwrap(); + let version = String::from_utf8(version.stdout).unwrap(); + let host = version.lines().find_map(|l| l.strip_prefix("host: ")).expect("cargo -vV names its host"); + let out = std::process::Command::new(&cargo) + .args(["metadata", "--format-version", "1", "--offline", "--filter-platform", host]) .current_dir(env!("CARGO_MANIFEST_DIR")) .output() .unwrap(); From 2451cc34e420e6b6df21353d80c7c941bd11f91c Mon Sep 17 00:00:00 2001 From: Faridul Date: Tue, 17 Nov 2026 08:15:34 +0600 Subject: [PATCH 03/11] M8: the desktop refines a zoom only once it pauses After a zoom step's preview the render thread only checked once, right away, for a newer request, then started the full render. That render can't be stopped, so on a heavy page every later step of a held zoom waited for it (110-520 ms per render on a 9,000-layer page with images and shadows). It now waits like the browser worker does: SETTLE_MS, or the last full render's time when that's shorter. Pans and edits have no preview and are refined straight away as before. --- crates/ui-egui/src/canvas/render_worker.rs | 23 ++++++++++----- .../ui-egui/src/canvas/zoom_preview_tests.rs | 28 +++++++++++++++++++ docs/gaps.md | 9 +++++- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index 44a478807..27c9cc32b 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -32,9 +32,9 @@ use web_time::Instant; pub const PREVIEW_FACTOR: f64 = 4.0; /// Full renders quicker than this (about a frame) show without a preview. pub const PREVIEW_AFTER_MS: f64 = 12.0; -/// The browser refines a zoom's preview only once no newer request came for this long (or for as -/// long as the last full render took, when shorter): a full render there blocks the page, and one -/// between every two wheel steps of a zoom held it up for seconds. +/// A zoom's preview is refined only once no newer request came for this long (or for as long as +/// the last full render took, when shorter): in the browser a full render blocks the page, and on +/// the desktop it can't be stopped, so one between every two wheel steps of a zoom held it up. pub const SETTLE_MS: u64 = 120; /// The browser draws a full render a band at a time ([`figcraft_render::Steps`]): at least one /// band a frame, and more while they fit in this long, so input is handled while it draws. A @@ -481,10 +481,19 @@ impl Worker { break; } ctx.request_repaint_of(viewport); - // A newer request makes refining this one moot: it gets its own preview. - if let Ok(newer) = jobs.try_recv() { - next = Some(newer); - continue; + // A newer request makes refining this one moot: it gets its own preview. Wait + // for one as the browser does ([`SETTLE_MS`], or the last full render's time + // when shorter): a full render can't be stopped, so one started between two + // steps of a zoom held every later step up for as long as it took. + let wait = std::time::Duration::try_from_secs_f64(renders.full_ms_so_far() / 1000.0) + .map_or(std::time::Duration::ZERO, |full| full.min(std::time::Duration::from_millis(SETTLE_MS))); + match jobs.recv_timeout(wait) { + Ok(newer) => { + next = Some(newer); + continue; + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, } } if renders.wants_late_preview(&job) { diff --git a/crates/ui-egui/src/canvas/zoom_preview_tests.rs b/crates/ui-egui/src/canvas/zoom_preview_tests.rs index bb36c0aae..bef17fe59 100644 --- a/crates/ui-egui/src/canvas/zoom_preview_tests.rs +++ b/crates/ui-egui/src/canvas/zoom_preview_tests.rs @@ -405,6 +405,34 @@ fn a_slow_first_render_gets_a_preview_beside_it_and_a_quick_one_none() { assert_eq!(drain(&mut w), [(1, false)], "done before the threshold: no preview"); } +#[test] +fn the_render_thread_refines_a_zoom_only_once_it_pauses() { + // A full render can't be stopped: a zoom step's started as soon as its preview was out held the + // next step up for as long as it took. The next step coming while the preview shows skips it. + let views: Vec = [1.0, 0.5, 0.25].into_iter().map(|s| view_at((300.0, 200.0), s, 1200, 1200)).collect(); + let s = slow_scene(&views, 4.0 * PREVIEW_AFTER_MS); + let ds = s.ds().unwrap(); + let at = |i: usize| job(&ds.doc, ds.page, ds.uid, views[i].clone()); + let mut w = Worker::new(egui::Context::default()); + w.submit(at(0)); + drain(&mut w); + // A zoom out: its preview, then the next step while that preview is on screen. + w.submit(at(1)); + let start = std::time::Instant::now(); + let preview = loop { + assert!(start.elapsed() < Duration::from_secs(60), "no preview came"); + if let Some(d) = w.poll() { + break d; + } + std::thread::sleep(Duration::from_millis(1)); + }; + assert_eq!((preview.seq, preview.coarse), (2, true)); + w.submit(at(2)); + let got = drain(&mut w); + assert!(!got.contains(&(2, false)), "the step zoomed past is never refined: {got:?}"); + assert_eq!(got.last(), Some(&(3, false)), "the last step is: {got:?}"); +} + #[test] fn a_preview_replaces_a_refined_image_of_the_same_zoom_elsewhere_on_the_page() { // 800 × 600: A at 100% from the page origin, B at 800% about its top-left, A' back at 100% diff --git a/docs/gaps.md b/docs/gaps.md index 66ac5bb9f..30d4e2304 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -306,6 +306,12 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe write lock, went from about 45 µs to 0.2 µs (the lookup logic timed alone). The faces drawn are those drawn before, except where two are equally near the run's style (the one read already is kept) and for Hiragino's W3-style names (read as their weight). +- **Landed (2026-11-17):** the desktop's render thread waits the same way after a zoom's preview + (`SETTLE_MS`, or the last full render's time when shorter) before refining it. A full render + there can't be stopped, so one started between two steps of a held zoom made every later step + wait for it: on a 29,000 × 12,600 page of 9,000 layers with images and shadows (M1 Pro, 2x + display) full renders took 110–520 ms, and the preview stood in for that long. Pans and edits are + refined at once, as before. - **Landed (2026-10-28):** the browser refines a zoom's preview only once no newer request has come for 120 ms (`SETTLE_MS`), or for as long as its last full render took when that is shorter: its full renders run on the UI thread, and one between every two wheel steps held the page up @@ -595,6 +601,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Gap 7: the desktop refines a zoom's preview only once the zoom has paused, as the browser does, so a full render that can't be stopped no longer holds up the next steps of a held zoom. Numbers unchanged. Test: `zoom_preview_tests::the_render_thread_refines_a_zoom_only_once_it_pauses` | | 2026-11-12 | minor | Gap 1: the `.fig` export writes vector region paints (#2302); the 2026-10-26 "Landed" bullet no longer says the export drops them | | 2026-11-10 | minor | Gap 13: a boolean group's corner radius rounds every sharp corner of its result (#2222); the boolean clause leaves the 2026-10-12 "Left" list | | 2026-11-10 | minor | Gap 24: mind maps, first step (`board.mindMap`, `board.mindMapAdd`; the map lays itself out again after every edit, #2226); the toolbar entry, shortcuts, drag to re-parent and `.jam` import are what is missing of them. | From 87e43cccf0d059415b7c5e22842d29a3ae8001f1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:22:16 -0500 Subject: [PATCH 04/11] format: write Penpot containers through shared incremental writer --- Cargo.lock | 22 +++++++++++++++ Cargo.toml | 3 ++ crates/format/Cargo.toml | 1 + crates/format/src/penpot/export.rs | 35 +++++++++--------------- crates/format/src/penpot/export_tests.rs | 16 +++++++++++ 5 files changed, 55 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d6d010579..07e4fa1b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1131,6 +1131,17 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-penpot" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e#f7c87b3b3a90fffd44b4a414acee966e66cb006e" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e)", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-quit" version = "0.1.0" @@ -1265,6 +1276,16 @@ dependencies = [ "zip 9.1.1", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e#f7c87b3b3a90fffd44b4a414acee966e66cb006e" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -2017,6 +2038,7 @@ dependencies = [ "craft-fig", "craft-figcraft-format", "craft-figma-rest", + "craft-penpot", "figcraft-doc", "figcraft-layout", "figcraft-pathops", diff --git a/Cargo.toml b/Cargo.toml index 05aa2d393..75995debf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,9 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9ae # Where the settings live: the suite's folder rules, portable mode included (craft-libs). craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } +# Penpot export container only; JSON values cross this boundary, not shared model types. +craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "f7c87b3b3a90fffd44b4a414acee966e66cb006e" } + # The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of # a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share # types, so they stay on one rev; they share none with the crates above. diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 9424b95e0..46869824c 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -20,6 +20,7 @@ ruzstd = { workspace = true } sha1 = { workspace = true } sha2 = { workspace = true } image = { workspace = true } +craft-penpot = { workspace = true } craft-fig = { workspace = true } craft-figcraft-format = { workspace = true } craft-figma-rest = { workspace = true } diff --git a/crates/format/src/penpot/export.rs b/crates/format/src/penpot/export.rs index d0b9d3046..10811022a 100644 --- a/crates/format/src/penpot/export.rs +++ b/crates/format/src/penpot/export.rs @@ -1,5 +1,4 @@ use std::collections::{BTreeMap, BTreeSet}; -use std::io::{Cursor, Write}; use figcraft_doc::color::{BlendMode, Color, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind}; use figcraft_doc::geom::kurbo::PathEl; @@ -13,7 +12,7 @@ use figcraft_doc::{ use serde_json::{Map, Value, json}; use super::{ROOT_ID, fingerprint, layout_fingerprint, strokes_fingerprint, text_fingerprint, tokens_fingerprint, uuid}; -use crate::{FormatError, io_err, json_options}; +use crate::{FormatError, io_err}; const DEFAULT_FEATURES: &[&str] = &["fdata/path-data", "design-tokens/v1", "variants/v1", "layout/grid", "components/v2", "fdata/shape-data-type"]; @@ -565,27 +564,19 @@ impl<'a> Exporter<'a> { "files": [{"id": self.file_id, "name": name, "features": file.get("features").cloned().unwrap_or(Value::Null)}], "relations": [], }); - let mut buf = Cursor::new(Vec::new()); - { - let mut z = zip::ZipWriter::new(&mut buf); - let mut put = |path: &str, bytes: &[u8]| -> Result<(), FormatError> { - z.start_file(path, json_options()).map_err(io_err)?; - z.write_all(bytes).map_err(io_err) - }; - put("manifest.json", &serde_json::to_vec_pretty(&manifest).map_err(io_err)?)?; - put(&format!("{base}.json"), &serde_json::to_vec_pretty(&file).map_err(io_err)?)?; - if let Some(tokens) = tokens { - put(&format!("{base}/tokens.json"), tokens.as_bytes())?; - } - for (path, value) in &entries { - put(path, &serde_json::to_vec_pretty(value).map_err(io_err)?)?; - } - for (path, bytes) in &blobs { - put(path, bytes)?; - } - z.finish().map_err(io_err)?; + let mut writer = craft_penpot::Writer::new(); + writer.add("manifest.json", &serde_json::to_vec_pretty(&manifest).map_err(io_err)?).map_err(io_err)?; + writer.add(&format!("{base}.json"), &serde_json::to_vec_pretty(&file).map_err(io_err)?).map_err(io_err)?; + if let Some(tokens) = tokens { + writer.add(&format!("{base}/tokens.json"), tokens.as_bytes()).map_err(io_err)?; } - Ok((buf.into_inner(), self.warnings)) + for (path, value) in &entries { + writer.add(path, &serde_json::to_vec_pretty(value).map_err(io_err)?).map_err(io_err)?; + } + for (path, bytes) in &blobs { + writer.add(path, bytes).map_err(io_err)?; + } + Ok((writer.finish().map_err(io_err)?, self.warnings)) } fn page_json(&self, page: NodeId, page_id: &str, index: usize, background: Color) -> Value { diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index 1e9e95638..e3ad744ef 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -1027,3 +1027,19 @@ fn stored_variable_ids_keep_penpot_token_identity() { assert_eq!(width, &expected); } } + +#[test] +fn shared_writer_keeps_manifest_first_and_deflated_members() { + let doc = Document::new("Shared container"); + let (bytes, _) = export(&doc).unwrap(); + let mut zip = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + assert_eq!(zip.by_index(0).unwrap().name(), "manifest.json"); + for index in 0..zip.len() { + assert_eq!(zip.by_index(index).unwrap().compression(), zip::CompressionMethod::Deflated); + } + let archive = craft_penpot::Archive::open(&bytes).unwrap(); + assert_eq!(archive.files.len(), 1); + assert_eq!(archive.files[0].name.as_deref(), Some("Shared container")); + assert_eq!(archive.manifest["generatedBy"], format!("figcraft/{}", env!("CARGO_PKG_VERSION"))); + assert!(import(&bytes).is_ok()); +} From 26fa159c0c7771095df4e963736ec994bdda480c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:24:19 -0500 Subject: [PATCH 05/11] deps: pin documented Penpot writer error contract --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 07e4fa1b4..8adab0b43 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1134,9 +1134,9 @@ dependencies = [ [[package]] name = "craft-penpot" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e#f7c87b3b3a90fffd44b4a414acee966e66cb006e" +source = "git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3#8418f9a9e846d27bb4f5e854f370405fd013e9e3" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3)", "serde", "serde_json", "thiserror 2.0.21", @@ -1279,7 +1279,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e#f7c87b3b3a90fffd44b4a414acee966e66cb006e" +source = "git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3#8418f9a9e846d27bb4f5e854f370405fd013e9e3" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 75995debf..ac3aedee2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,7 +59,7 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9ae craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } # Penpot export container only; JSON values cross this boundary, not shared model types. -craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "f7c87b3b3a90fffd44b4a414acee966e66cb006e" } +craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "8418f9a9e846d27bb4f5e854f370405fd013e9e3" } # The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of # a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share From 931a1467b20eac928fae2f293c0413c606af55fa Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:50:31 -0500 Subject: [PATCH 06/11] fix(format): retain Cursor import for embedded Penpot PNG encoding --- crates/format/src/penpot/export.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/format/src/penpot/export.rs b/crates/format/src/penpot/export.rs index 10811022a..071809cab 100644 --- a/crates/format/src/penpot/export.rs +++ b/crates/format/src/penpot/export.rs @@ -1,4 +1,5 @@ use std::collections::{BTreeMap, BTreeSet}; +use std::io::Cursor; use figcraft_doc::color::{BlendMode, Color, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind}; use figcraft_doc::geom::kurbo::PathEl; From 6963e0d5ce7d08c1166f947cff750aebfd74ec24 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:58:13 -0500 Subject: [PATCH 07/11] Use shared Sketch container while retaining Fig document projection (#2418) --- Cargo.lock | 37 +++++- Cargo.toml | 1 + crates/format/Cargo.toml | 1 + crates/format/src/sketch.rs | 184 ++---------------------------- crates/format/src/sketch/tests.rs | 18 +++ 5 files changed, 67 insertions(+), 174 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d6d010579..083d59554 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1016,7 +1016,7 @@ name = "craft-fig" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" dependencies = [ - "craft-figma-rest", + "craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)", "craft-kiwi", "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)", "flate2", @@ -1048,6 +1048,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-figma-rest" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-font-catalog" version = "0.1.0" @@ -1153,6 +1163,18 @@ dependencies = [ "toml_edit", ] +[[package]] +name = "craft-sketch" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd" +dependencies = [ + "craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd)", + "kurbo", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -1265,6 +1287,16 @@ dependencies = [ "zip 9.1.1", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -2016,7 +2048,8 @@ version = "0.18.1" dependencies = [ "craft-fig", "craft-figcraft-format", - "craft-figma-rest", + "craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)", + "craft-sketch", "figcraft-doc", "figcraft-layout", "figcraft-pathops", diff --git a/Cargo.toml b/Cargo.toml index 05aa2d393..57cc46f7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,6 +61,7 @@ craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9 # The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of # a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share # types, so they stay on one rev; they share none with the crates above. +craft-sketch = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd" } craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "976eb51c59edb0a37f24105850f52d921c8518ee" } craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 9424b95e0..b5673119d 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -20,6 +20,7 @@ ruzstd = { workspace = true } sha1 = { workspace = true } sha2 = { workspace = true } image = { workspace = true } +craft-sketch = { workspace = true } craft-fig = { workspace = true } craft-figcraft-format = { workspace = true } craft-figma-rest = { workspace = true } diff --git a/crates/format/src/sketch.rs b/crates/format/src/sketch.rs index 182447015..2389813bb 100644 --- a/crates/format/src/sketch.rs +++ b/crates/format/src/sketch.rs @@ -43,48 +43,15 @@ mod tree_tests; use std::collections::BTreeSet; use figcraft_doc::Document; -use serde_json::{Value, json}; +use serde_json::Value; + +// Container parsing is shared; FigCraft document projection remains in this module. +pub(crate) use craft_sketch::Archive; use crate::FormatError; -/// The oldest Sketch whose files open: from 48 on, text is plain JSON too. -pub const MIN_SKETCH: u32 = 48; -/// The newest `meta.json` format version checked against real files (Sketch 83); newer files -/// open with a warning. -pub const NEWEST_TESTED_VERSION: u64 = 139; -/// What opening a file saved by an older Sketch says. -pub const TOO_OLD: &str = "saved by a Sketch older than 48; open it in a newer Sketch and save it again"; -/// Largest JSON member read (a real page of a few thousand layers takes 33 MB). -const MAX_JSON_MEMBER: u64 = 512 * 1024 * 1024; -/// Most bytes a member may unpack to, per compressed byte (real JSON packs 5–20 times and images -/// barely; a zero-filled member a thousand times), with a floor for small members. -const MAX_RATIO: u64 = 100; -const MIN_ALLOWANCE: u64 = 16 * 1024 * 1024; -/// Most JSON read from one file in all. -#[cfg(not(target_pointer_width = "32"))] -const MAX_JSON_TOTAL: u64 = 2 * 1024 * 1024 * 1024; -#[cfg(target_pointer_width = "32")] -const MAX_JSON_TOTAL: u64 = 512 * 1024 * 1024; -/// Largest image member read. -const MAX_IMAGE: u64 = figcraft_doc::ImageData::MAX_BYTES; -/// Most image bytes read from one file in all. -#[cfg(not(target_pointer_width = "32"))] -const MAX_IMAGE_TOTAL: u64 = 1024 * 1024 * 1024; -#[cfg(target_pointer_width = "32")] -const MAX_IMAGE_TOTAL: u64 = 256 * 1024 * 1024; -/// Most pages read from one file. -const MAX_PAGES: usize = 1000; - -/// Whether `bytes` look like a `.sketch` file: a zip holding `document.json` and `meta.json`, or -/// the SQLite database Sketch wrote before version 43 (so that it gets the "too old" message). -pub fn is_sketch(bytes: &[u8]) -> bool { - bytes.starts_with(b"SQLite format 3\0") - || (bytes.starts_with(b"PK") - && zip::ZipArchive::new(std::io::Cursor::new(bytes)).is_ok_and(|z| { - let names: BTreeSet<&str> = z.file_names().collect(); - names.contains("document.json") && names.contains("meta.json") - })) -} +pub use craft_sketch::{MIN_SKETCH, NEWEST_TESTED_VERSION, TOO_OLD, is_sketch}; +const MAX_JSON_MEMBER: u64 = craft_sketch::MAX_JSON_MEMBER; /// Finds the installed face a PostScript name belongs to: its family and style. pub type FontLookup = Box Option<(String, String)>>; @@ -133,7 +100,12 @@ fn import_parts( if bytes.starts_with(b"SQLite format 3\0") { return Err(FormatError::Io(TOO_OLD.into())); } - let archive = Archive::open(bytes, max_member)?; + let archive = + Archive::open_with(bytes, craft_sketch::Limits { max_page: max_member, max_image: figcraft_doc::ImageData::MAX_BYTES, ..Default::default() }) + .map_err(|error| match error { + craft_sketch::Error::TooOld => FormatError::Io(TOO_OLD.into()), + craft_sketch::Error::Corrupt(message) => FormatError::Corrupt(format!("Sketch file: {message}")), + })?; let map = tree::to_rest(&archive, name, max_nodes, fonts); if map.too_old { return Err(FormatError::Io(TOO_OLD.into())); @@ -172,135 +144,3 @@ fn embedded_fonts(document: &Value) -> Option { let list: Vec<&str> = families.iter().map(String::as_str).collect(); Some(format!("the file has embedded fonts FigCraft doesn't use ({}); install them to see the text as designed", list.join(", "))) } - -fn corrupt(msg: impl Into) -> FormatError { - FormatError::Corrupt(format!("Sketch file: {}", msg.into())) -} - -/// The parts of a `.sketch` archive: the document, the pages in document order and the images. -pub(crate) struct Archive<'b> { - pub document: Value, - /// `meta.json`'s format version (0 when missing). - pub version: u64, - /// `(id, page JSON)` in the document's order. - pub pages: Vec<(String, Value)>, - /// Problems met while reading (pages skipped). - pub warnings: Vec, - zip: zip::ZipArchive>, - /// Image bytes read so far. - image_total: std::cell::Cell, -} - -impl<'b> Archive<'b> { - fn open(bytes: &'b [u8], max_member: u64) -> Result { - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| corrupt(e.to_string()))?; - let mut total = 0u64; - let meta = json_member(&mut z, "meta.json", MAX_JSON_MEMBER, &mut total)?; - if !meta.is_object() { - return Err(corrupt("meta.json is not an object")); - } - if app_major(&meta).is_some_and(|v| v < MIN_SKETCH) { - return Err(FormatError::Io(TOO_OLD.into())); - } - let mut warnings = Vec::new(); - if meta.get("version").and_then(Value::as_u64).is_some_and(|v| v > NEWEST_TESTED_VERSION) { - warnings.push("the file was saved by a newer Sketch than the import was checked with; some layers may differ".to_string()); - } - // A document.json that can't be read (nested too deep, damaged) loses its shared styles and - // library copies, not the pages: they are then taken in archive order. - let document = match json_member(&mut z, "document.json", MAX_JSON_MEMBER, &mut total) { - Ok(d) if d.is_object() => d, - other => { - let why = other.err().map_or_else(|| "not an object".to_string(), |e| e.to_string()); - warnings.push(format!( - "the document's shared styles and library symbols were skipped: {}", - why.trim_start_matches("not a valid FigCraft file: ") - )); - let pages: Vec = z - .file_names() - .filter_map(|n| n.strip_prefix("pages/")?.strip_suffix(".json")) - .map(|id| json!({"_ref": format!("pages/{id}")})) - .collect(); - json!({"pages": pages}) - } - }; - let refs = document.get("pages").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); - let mut pages = Vec::new(); - let mut seen = std::collections::HashSet::new(); - for r in refs.iter().take(MAX_PAGES) { - let Some(id) = r.get("_ref").and_then(Value::as_str).and_then(|s| s.strip_prefix("pages/")).filter(|id| valid_id(id)) else { - warnings.push("pages the document lists without a valid reference were skipped".into()); - continue; - }; - // A page listed twice is read once: a repeated reference must not repeat the unpacking. - if !seen.insert(id) { - continue; - } - match json_member(&mut z, &format!("pages/{id}.json"), max_member, &mut total) { - Ok(page) if page.is_object() => pages.push((id.to_string(), page)), - Ok(_) => warnings.push("pages that aren't JSON objects were skipped".into()), - Err(e) => warnings.push(format!("a page was skipped: {}", e.to_string().trim_start_matches("not a valid FigCraft file: "))), - } - } - if refs.len() > MAX_PAGES { - warnings.push(format!("the file has more than {MAX_PAGES} pages; the rest were skipped")); - } - let version = meta.get("version").and_then(Value::as_u64).unwrap_or(0); - Ok(Archive { document, version, pages, warnings, zip: z, image_total: std::cell::Cell::new(0) }) - } - - /// The bytes of the image a layer references (`images/`). - pub(crate) fn image(&self, r: &str) -> Option> { - let name = r.strip_prefix("images/").unwrap_or(r); - if !valid_id(name.split('.').next().unwrap_or("")) || name.split('.').count() > 2 { - return None; - } - // A clone shares the parsed directory and the bytes; the resolver only has shared access. - let mut z = self.zip.clone(); - let mut total = self.image_total.get(); - let data = capped_member(&mut z, &format!("images/{name}"), MAX_IMAGE, &mut total, MAX_IMAGE_TOTAL).ok(); - self.image_total.set(total); - data - } -} - -/// Member `name`, refused before unpacking when it would be larger than `limit`, than -/// [`MAX_RATIO`] times what it takes in the archive (past a floor), or than what is left of -/// `max_total` (`total`: read so far, counted up). -fn capped_member( - z: &mut zip::ZipArchive>, - name: &str, - limit: u64, - total: &mut u64, - max_total: u64, -) -> Result, FormatError> { - let (size, packed) = { - let f = z.by_name(name).map_err(|e| corrupt(format!("{name}: {e}")))?; - (f.size(), f.compressed_size()) - }; - let allowed = limit.min(packed.saturating_mul(MAX_RATIO).max(MIN_ALLOWANCE)).min(max_total.saturating_sub(*total)); - if size > allowed { - return Err(corrupt(format!("{name} is too large"))); - } - let data = crate::read_member(z, name, allowed); - // A failed read (a bad checksum at the end, say) unpacked all the same: charged in full, so - // a page list naming the member again can't repeat it within the budget. - *total += data.as_ref().map_or(size, |d| d.len() as u64); - data -} - -/// JSON member `name`, read by [`capped_member`] within the file's [`MAX_JSON_TOTAL`]. -fn json_member(z: &mut zip::ZipArchive>, name: &str, limit: u64, total: &mut u64) -> Result { - let data = capped_member(z, name, limit, total, MAX_JSON_TOTAL)?; - serde_json::from_slice(&data).map_err(|e| corrupt(format!("{name}: {e}"))) -} - -/// The major version of the Sketch that saved the file (`meta.json` `appVersion`, "50.2" → 50). -fn app_major(meta: &Value) -> Option { - meta.get("appVersion").and_then(Value::as_str)?.split('.').next()?.trim().parse().ok() -} - -/// Ids name archive members: letters, digits, `-` and `_` only, never a path. -fn valid_id(id: &str) -> bool { - !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') -} diff --git a/crates/format/src/sketch/tests.rs b/crates/format/src/sketch/tests.rs index d8ace8be9..784c542bd 100644 --- a/crates/format/src/sketch/tests.rs +++ b/crates/format/src/sketch/tests.rs @@ -206,3 +206,21 @@ fn members_over_budget_are_skipped() { assert!(warnings.iter().any(|w| w.contains("too large")), "{warnings:?}"); assert!(!page_names(&doc).contains(&"Big".to_string())); } + +/// The shared container refuses ambiguous member names instead of selecting one silently. +#[test] +fn duplicate_archive_members_are_refused() { + let mut z = sketch_zip("50.2", 103, document(&["A", "B"]), &[page("A", "Alpha", vec![]), page("B", "Beta", vec![])], &[]); + let from = b"pages/B.json"; + let to = b"pages/A.json"; + let mut replaced = 0; + for i in 0..z.len().saturating_sub(from.len()).saturating_add(1) { + if z.get(i..i + from.len()) == Some(from.as_slice()) { + z[i..i + from.len()].copy_from_slice(to); + replaced += 1; + } + } + assert_eq!(replaced, 2, "local and central directory names changed"); + let error = import(&z, "ambiguous").unwrap_err().to_string(); + assert!(error.contains("two entries of the archive share a name"), "{error}"); +} From be44cb1ab6a35a61c3ef369489768d84b04fad65 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:58:17 -0500 Subject: [PATCH 08/11] docs: prefer craft-libs for reusable formats, codecs, protocols and UI (#2408) --- AGENTS.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index e63e92c7c..cc4ea91e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +59,7 @@ inspection. It runs natively on macOS, Windows, Linux and FreeBSD, and in the br Siblings: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop-class), `../designcraft` (InDesign-class) and the other Crafting Apps; same conventions. -Repos don't share code. +Share reusable code through craft-libs; do not depend on sibling application crates. ## Start every session here 1. Read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, estimates) and @@ -182,3 +182,7 @@ commit. Grade by behaviour against the incumbent, not by whether a menu item exi - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. - Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +## Shared Craft libraries + +Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage. From 954687fcf7c15fdb94d5343d72be95c5832e4710 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:58:22 -0500 Subject: [PATCH 09/11] ci: lock workflow actions through an actions.lock lockfile (#2300) --- .github/workflows/actions.lock | 29 ++++++++++++++++++++++++ .github/workflows/lockfile.yml | 34 ++++++++++++++++++++++++++++ .github/workflows/packaging-lint.yml | 4 ++-- sonar-project.properties | 10 +++++++- 4 files changed, 74 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/actions.lock create mode 100644 .github/workflows/lockfile.yml diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 000000000..6917bde73 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,29 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/ci.yml': [] + '.github/workflows/freebsd.yml': [] + '.github/workflows/house-rules.yml': [] + '.github/workflows/lockfile.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nix.yml': [] + '.github/workflows/packaging-lint.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/release.yml': [] + '.github/workflows/sonarcloud.yml': [] + '.github/workflows/windows-arm64.yml': [] +dependencies: + 'actions/checkout@v7.0.1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'step-security/harden-runner@v2.22.4': + ref: 'v2.22.4' + commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' + owner_id: 88700172 + repo_id: 422287306 diff --git a/.github/workflows/lockfile.yml b/.github/workflows/lockfile.yml new file mode 100644 index 000000000..e630c9a8f --- /dev/null +++ b/.github/workflows/lockfile.yml @@ -0,0 +1,34 @@ +name: Lockfile + +# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin +# no longer verifies upstream, so a moved tag cannot slip a different commit into a run. +# Docs: https://gh.io/actions-lockfile +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +env: + GH_TOKEN: ${{ github.token }} + +jobs: + lockfile: + name: Lockfile is in sync + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Install gh-actions-lock + run: gh extension install github/gh-actions-lock --pin v0.4.1 + - name: Verify the lockfile + run: gh actions-lock --verify diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 0a91cc050..f442059bb 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -30,10 +30,10 @@ jobs: runs-on: windows-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - name: Install the pinned packaging toolchain diff --git a/sonar-project.properties b/sonar-project.properties index 7bd9e8ce6..8c36accaf 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -6,6 +6,14 @@ sonar.exclusions=craft-fonts/** # S4790 (weak hash): a .fig file names each image by the SHA-1 of its bytes (20 bytes, the only # length readers accept). It is an identifier the format fixes, not a security choice. -sonar.issue.ignore.multicriteria=fig_image_sha1 +sonar.issue.ignore.multicriteria=fig_image_sha1,gha-lockfile sonar.issue.ignore.multicriteria.fig_image_sha1.ruleKey=rust:S4790 sonar.issue.ignore.multicriteria.fig_image_sha1.resourceKey=crates/format/src/fig/export.rs + +# githubactions:S7637 asks for every action to be pinned to a commit SHA. A workflow covered by +# .github/workflows/actions.lock runs the commit the lockfile records, so its tag refs are pinned +# and the lockfile covers the actions those actions use too. Sonar does not read lockfiles yet, so +# the rule flags the tag refs anyway: +# https://community.sonarsource.com/t/githubactions-s7637-false-positives-for-actions-pinned-through-native-actions-lock/190814 +sonar.issue.ignore.multicriteria.gha-lockfile.ruleKey=githubactions:S7637 +sonar.issue.ignore.multicriteria.gha-lockfile.resourceKey=.github/workflows/** From 5ee60ec708201fe93b44ea5dacbce49b96b3598e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:01:33 -0500 Subject: [PATCH 10/11] fix(format): keep legacy ZIP options only for remaining test fixture --- crates/format/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 167444c62..1c246bb89 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -47,6 +47,7 @@ pub use craft_figcraft_format::{ MAX_VERSION_INDEX, MAX_VERSION_NAME, MAX_VERSIONS, ReadBudget, VERSION, VersionEntry as NativeVersionEntry, VersionIndex as NativeVersionIndex, clip, document_limit, is_valid_version_id, }; +#[cfg(test)] const JSON_LEVEL: i64 = 3; /// The export warning for colour calculations that resolve to nothing (an operand missing, or more /// than 32 variables to read), shared by the Penpot and `.fig` exports. @@ -411,7 +412,8 @@ pub(crate) fn io_err(e: impl std::fmt::Display) -> FormatError { FormatError::Io(e.to_string()) } -/// JSON compression for Penpot and external ZIP exporters. +/// JSON compression for legacy Penpot test fixtures. +#[cfg(test)] pub(crate) fn json_options() -> zip::write::SimpleFileOptions { zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).compression_level(Some(JSON_LEVEL)) } From 4aae3f2733a3fb1e42c80ab5ba81730a4a55339e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:11:07 -0500 Subject: [PATCH 11/11] chore(penpot): pin merged writer and canonicalize lock order --- Cargo.lock | 24 ++++++++++++------------ Cargo.toml | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 77abcfa01..879856783 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1144,9 +1144,9 @@ dependencies = [ [[package]] name = "craft-penpot" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3#8418f9a9e846d27bb4f5e854f370405fd013e9e3" +source = "git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a#064afccce82b01cbf85da5e265bcf897553bea2a" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a)", "serde", "serde_json", "thiserror 2.0.21", @@ -1278,6 +1278,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a#064afccce82b01cbf85da5e265bcf897553bea2a" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -1298,16 +1308,6 @@ dependencies = [ "zip 9.1.1", ] -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3#8418f9a9e846d27bb4f5e854f370405fd013e9e3" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip 9.1.1", -] - [[package]] name = "craft-zip" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index dd33c406c..82831e556 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,7 +59,7 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9ae craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } # Penpot export container only; JSON values cross this boundary, not shared model types. -craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "8418f9a9e846d27bb4f5e854f370405fd013e9e3" } +craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "064afccce82b01cbf85da5e265bcf897553bea2a" } # The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of # a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share