From ee2482c66232c55f5c953c0b40139cb32490dc04 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 17:56:31 -0500 Subject: [PATCH 1/8] Merge pull request #15341 from storytold/cutover/shared-tysh-fallback psd: preserve lenient TySh recovery through craft-psd --- Cargo.lock | 12 ++++++++++++ crates/io/Cargo.toml | 1 + crates/io/src/blocks.rs | 13 +------------ crates/io/src/blocks/tests.rs | 26 ++++++++++++++++++++++++++ crates/io/src/psd_import/tests.rs | 31 +++++++++++++++++++++++++++++++ 5 files changed, 71 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cbff2d74c8..37a1a28f3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1629,6 +1629,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=20220807a4c33a35a72c7b4dfad90edd29205e34#20220807a4c33a35a72c7b4dfad90edd29205e34" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-psd" version = "0.1.0" @@ -5787,6 +5798,7 @@ dependencies = [ "craft-pdf", "craft-pdn", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=040b5202f9ca2ecaedcaea9351fc095c0d3dc5e8)", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=20220807a4c33a35a72c7b4dfad90edd29205e34)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2823525586851bf81ccfe9daf838c7a4cafb8ab9)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=589842f0da5c5a11e71f39b70092dcb918b92f39)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5e2bc54a48c9f03e7ce4eca42775ce5cc051f5d6)", diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 6d7332ca03..aa4b01c6fa 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -29,6 +29,7 @@ photocraft-doc = { workspace = true } photocraft-compose = { workspace = true } photocraft-algo = { workspace = true } craft-psd = { workspace = true } +craft-psd-tysh = { package = "craft-psd", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "20220807a4c33a35a72c7b4dfad90edd29205e34" } craft-psd-displace = { package = "craft-psd", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "2823525586851bf81ccfe9daf838c7a4cafb8ab9" } craft-psd-names = { package = "craft-psd", git = "https://github.com/storytold/craft-libs", rev = "040b5202f9ca2ecaedcaea9351fc095c0d3dc5e8", version = "0.1.0" } craft-psd-channels = { package = "craft-psd", git = "https://github.com/storytold/craft-libs", rev = "5e2bc54a48c9f03e7ce4eca42775ce5cc051f5d6", version = "0.1.0" } diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs index 2f69330b60..79aeb67ff2 100644 --- a/crates/io/src/blocks.rs +++ b/crates/io/src/blocks.rs @@ -713,18 +713,7 @@ pub(crate) fn quilt_knots(env: &Descriptor, key: &str, patches: usize) -> Option /// Text content and transform from a `TySh` block (best effort). pub fn parse_tysh(data: &[u8]) -> Option<(String, Affine)> { - let f = |at: usize| data.get(at..at + 8).map(|b| f64::from_be_bytes(b.try_into().unwrap_or([0; 8]))); - let mut m = [0.0; 6]; - for (i, v) in m.iter_mut().enumerate() { - *v = f(2 + i * 8)?; - } - // text version (2) at 50, descriptor version (4) at 52, descriptor at 56. - let rest = data.get(52..)?; - let text = parse_prefix_versioned(rest).and_then(|d| match d.get("Txt ") { - Some(Value::Text(t)) => Some(t.to_string_lossy()), - _ => None, - }); - Some((text.unwrap_or_default(), Affine { m })) + craft_psd_tysh::text::envelope::parse_tysh_text_prefix(data).map(|(text, m)| (text, Affine { m })) } /// Parses a version-16 descriptor at the start of `data` (trailing bytes allowed). diff --git a/crates/io/src/blocks/tests.rs b/crates/io/src/blocks/tests.rs index 45e9ec206b..e6281d4f2a 100644 --- a/crates/io/src/blocks/tests.rs +++ b/crates/io/src/blocks/tests.rs @@ -333,3 +333,29 @@ fn fills_roundtrip() { } } } + +#[test] +fn tysh_preservation_fallback_survives_missing_descriptor() { + let mut bytes = vec![0u8; 52]; + let expected = [1.0f64, 0.0, 0.0, 1.0, 25.0, 30.0]; + for (i, v) in expected.iter().enumerate() { + bytes[2 + i * 8..10 + i * 8].copy_from_slice(&v.to_be_bytes()); + } + let (text, transform) = super::parse_tysh(&bytes).unwrap(); + assert!(text.is_empty()); + assert_eq!(transform.m, expected); + assert!(super::parse_tysh(&bytes[..51]).is_none()); +} + +#[test] +fn oversized_tysh_preserves_fallback_geometry_without_decoding_text() { + let mut bytes = vec![0u8; craft_psd_tysh::text::envelope::MAX_BYTES + 1]; + let expected = [1.0f64, 0.0, 0.0, 1.0, 25.0, 30.0]; + for (i, v) in expected.iter().enumerate() { + bytes[2 + i * 8..10 + i * 8].copy_from_slice(&v.to_be_bytes()); + } + let (text, transform) = super::parse_tysh(&bytes).unwrap(); + assert!(text.is_empty()); + assert_eq!(transform.m, expected); + assert!(photocraft_text::psd::transform_is_safe(&transform)); +} diff --git a/crates/io/src/psd_import/tests.rs b/crates/io/src/psd_import/tests.rs index d15ef5fa28..7e689c4e63 100644 --- a/crates/io/src/psd_import/tests.rs +++ b/crates/io/src/psd_import/tests.rs @@ -640,3 +640,34 @@ fn unicode_names_preserve_empty_lossy_and_terminator_policy() { data.extend([0, 0, 0, 2, 0, 65]); assert_eq!(unicode_names(&data), ["", "\u{fffd}A", "๐Ÿ˜€", "A\0B"]); } + +#[test] +fn oversized_tysh_fallback_remains_type_and_roundtrips_raw_block() { + for extra in [1, 2] { + let mut file = testgen::small(Version::Psd, Compression::Raw); + let mut raw = vec![0u8; craft_psd_tysh::text::envelope::MAX_BYTES + extra]; + for (i, value) in [1.0f64, 0.0, 0.0, 1.0, 25.0, 30.0].iter().enumerate() { + raw[2 + i * 8..10 + i * 8].copy_from_slice(&value.to_be_bytes()); + } + file.layers_mut()[0].blocks.push(craft_psd::TaggedBlock::new(*b"TySh", raw.clone())); + let (doc, _, _) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + let text = doc + .layers + .iter() + .find_map(|layer| match &layer.content { + LayerContent::Text(text) => Some(text), + _ => None, + }) + .expect("oversized descriptor must retain a type layer rather than rasterizing"); + assert!(text.text.is_empty()); + assert_eq!(text.psd_raw.as_deref().unwrap().as_slice(), raw); + let saved = crate::psd_export::document_to_psd(&doc).unwrap(); + let block = saved.layers().iter().find_map(|layer| layer.block(b"TySh")).unwrap(); + // Layer blocks include a zero pad inside odd lengths for PSD reader compatibility (#200). + // No original byte may change; only that required pad may be appended. + if raw.len() % 2 == 1 { + raw.push(0); + } + assert_eq!(block.data, raw); + } +} From 957b10cccbb4bcd402394d250e52a9b9e1b63d74 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:12:23 +0100 Subject: [PATCH 2/8] test(ui-egui): hold the background redraw in tests that need it still running (#15359) `a_redraw_across_a_text_gamma_change_and_back_is_not_kept` stepped two frames and expected the 4096x3072 CPU redraw to still be running. Nothing holds the worker, so on the FreeBSD VM (software Vulkan, 4 cores) the redraw finished within those frames ("the redraw finished before the change back"; FreeBSD runs on eb3c99d65 and 02e9907f6). Start the redraw with the existing test hold (`hold_redraws` + `wait_for_held_redraw`, already used by `an_edit_during_a_redraw_is_not_overwritten_by_blocks_drawn_before_it`) in every test that needs the redraw running at a later frame: the gamma change and back, the gamma change, the hidden document's gamma change, Memory Usage dropping mid-redraw, and closing the document. The hold is released before `settle`, so each redraw still finishes and the kept-composite assertions still check what they guarded: without `forget_if_gamma_changed` the held redraw draws every block with the original gamma and is kept, failing the test. --- .../src/canvas/background_redraw/tests.rs | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas/background_redraw/tests.rs b/crates/ui-egui/src/canvas/background_redraw/tests.rs index 6176ea0e26..12e9655d96 100644 --- a/crates/ui-egui/src/canvas/background_redraw/tests.rs +++ b/crates/ui-egui/src/canvas/background_redraw/tests.rs @@ -178,6 +178,19 @@ fn settle(g: &mut Gpu) { } } +/// Run the frame that starts `doc`'s redraw with its worker held before the first batch, and wait +/// until that very worker reaches the hold: the redraw runs, every block still to draw, until the +/// returned guard drops. Without it a test that needs the redraw still running at its next frame +/// races the worker: a fast machine draws the document first, and so does a slow frame (a +/// software adapter's uploads) that keeps taking blocks as they land until the last one. +fn start_held_redraw(g: &mut Gpu, doc: DocId) -> HoldRedraws { + let held = hold_redraws(); + g.harness.step(); + let generation = g.harness.state().redraws.get(&doc).expect("the frame started a redraw").worker_generation; + assert!(wait_for_held_redraw(g.harness.state(), doc, generation, std::time::Duration::from_secs(10)), "the redraw worker never reached the pre-batch hold"); + held +} + /// The canvas texture of `doc` against the synchronous CPU refresh of the current document. fn assert_matches_synchronous(g: &mut Gpu, doc: DocId) { let app = g.harness.state_mut(); @@ -295,10 +308,10 @@ fn a_redraw_finishing_after_memory_usage_drops_keeps_nothing_over_it() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut g) = gpu_app() else { return }; let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - g.harness.step(); - assert!(g.harness.state().redraws.contains_key(&doc)); + let held = start_held_redraw(&mut g, doc); // Less than the document's own pixels: nothing is left for kept composites. g.harness.state_mut().session.edit_prefs(|p| p.performance.memory_usage_mb = 1); + drop(held); settle(&mut g); assert!(g.harness.state().kept.entries.is_empty(), "a composite was kept over the current cap"); } @@ -331,9 +344,9 @@ fn a_redraw_across_a_text_gamma_change_is_not_kept() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut g) = gpu_app() else { return }; let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - g.harness.step(); - assert!(g.harness.state().redraws.contains_key(&doc)); + let held = start_held_redraw(&mut g, doc); g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; + drop(held); settle(&mut g); assert!(g.harness.state().kept.entries.is_empty(), "a composite of two gammas was kept"); } @@ -345,11 +358,12 @@ fn a_redraw_across_a_text_gamma_change_and_back_is_not_kept() { let Some(mut g) = gpu_app() else { return }; let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); let gamma = g.harness.state().session.color.settings.blend_text_gamma; - g.harness.step(); + let held = start_held_redraw(&mut g, doc); g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; g.harness.step(); g.harness.state_mut().session.color.settings.blend_text_gamma = gamma; assert!(g.harness.state().redraws.contains_key(&doc), "the redraw finished before the change back"); + drop(held); settle(&mut g); assert!(g.harness.state().kept.entries.is_empty(), "a composite of two gammas was kept"); } @@ -362,7 +376,7 @@ fn a_hidden_documents_redraw_across_a_text_gamma_change_and_back_is_not_kept() { let Some(mut g) = gpu_app() else { return }; let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); let gamma = g.harness.state().session.color.settings.blend_text_gamma; - g.harness.step(); + let held = start_held_redraw(&mut g, doc); g.harness.state_mut().run("file.new", json!({"width": 64, "height": 64})).expect("another document"); g.harness.step(); g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; @@ -372,6 +386,7 @@ fn a_hidden_documents_redraw_across_a_text_gamma_change_and_back_is_not_kept() { assert!(g.harness.state().redraws.contains_key(&doc), "the hidden document's redraw stopped"); let i = g.harness.state().session.documents().iter().position(|st| st.doc.id == doc).expect("document"); g.harness.state_mut().session.set_active(i); + drop(held); settle(&mut g); assert!(g.harness.state().kept.entries.iter().all(|k| k.id != doc), "a composite of two gammas was kept"); } @@ -477,8 +492,8 @@ fn closing_the_document_stops_its_redraw() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut g) = gpu_app() else { return }; let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - g.harness.step(); - assert!(g.harness.state().redraws.contains_key(&doc)); + // Held: the close lands while the redraw runs, and a cancelled worker leaves the hold. + let _held = start_held_redraw(&mut g, doc); g.harness.state_mut().run("file.close", json!({"save": false})).expect("close"); g.harness.step(); assert!(g.harness.state().redraws.is_empty()); From ba9ee03d45f646af1cccc24ea4d635952a99cb92 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:59:22 -0500 Subject: [PATCH 3/8] docs: prefer shared craft-libs implementations (#15299) --- AGENTS.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 2beee5df23..8fe25bcd77 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -214,3 +214,7 @@ If the field has a PSD equivalent, map it in `crates/io` too, and keep unknown P - 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-library reuse + +Before implementing file formats, codecs, protocols or reusable UI components, check [storytold/craft-libs](https://github.com/storytold/craft-libs) and relevant open PRs; reuse or extend shared APIs instead of duplicating app-local implementations. Keep app-specific policy and adapters local, preserve behavior and format fidelity, security and resource limits, repository layering and regression tests, and document any shared-API gap rather than silently reducing functionality. From 3ef7d5cf7a381e8e3cb73e43ee66e23cdeaf177b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:59:26 -0500 Subject: [PATCH 4/8] oracle_diff example: skip directory symlinks, refuse an oversized dump (#13362) --- crates/io/examples/oracle_diff.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs index 1da97fefa1..7f06839308 100644 --- a/crates/io/examples/oracle_diff.rs +++ b/crates/io/examples/oracle_diff.rs @@ -49,6 +49,14 @@ fn compare_modes(doc: &photocraft_doc::Document, ours: &[[f32; 4]], merged: &[[f // prefix_ours.f32, prefix_ps.f32, prefix_L.f32 (each top-level layer's own pixels, // masks not applied) and prefix.txt (width, height, layer names). let out = std::env::args().nth(4).expect("prefix"); + // Every layer is expanded to a full-canvas RGBA f32 plane (16 bytes per pixel). + const MAX_DUMP_BYTES: u128 = 16 << 30; + let planes = doc.layers.len() as u128 + 2; + let total = planes * doc.size.width as u128 * doc.size.height as u128 * 16; + if total > MAX_DUMP_BYTES { + eprintln!("dump would write {total} bytes (limit {MAX_DUMP_BYTES}); refusing"); + return; + } let wr = |name: String, px: &[[f32; 4]]| { let bytes: Vec = px.iter().flat_map(|p| p.iter().flat_map(|v| v.to_le_bytes())).collect(); std::fs::write(name, bytes).unwrap(); @@ -466,7 +474,9 @@ fn corpus_summary(root: &std::path::Path) { let Ok(rd) = std::fs::read_dir(dir) else { return }; for e in rd.flatten() { let p = e.path(); - if p.is_dir() { + // file_type() does not follow symlinks: a directory alias would repeat its subtree. + let Ok(ft) = e.file_type() else { continue }; + if ft.is_dir() { collect(&p, out); } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("psd") || e.eq_ignore_ascii_case("psb")) { out.push(p); From 43c2d1bd4540bbb21268461993a64023b8e5957d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:59:31 -0500 Subject: [PATCH 5/8] Camera Raw sidecar read: one nonblocking open judged by the opened handle (#13359) --- .../ui-egui/src/dialogs/camera_raw_ui/sidecar.rs | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs index 31b6d551d6..350a34671d 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs @@ -108,19 +108,13 @@ pub(super) fn existing_sidecar_is_ours(sidecar: &str) -> Option { /// The bytes of the regular file at `path` when it holds at most /// [`photocraft_io::camera_raw_xmp::MAX_XMP_BYTES`]; `None` for anything else (missing, a folder, -/// a pipe or device that might never end, larger). Never reads more than the cap plus one byte. +/// a pipe or device that might never end, larger). Never reads more than the cap plus one byte, and +/// never blocks opening a pipe. #[cfg(not(target_arch = "wasm32"))] pub(super) fn read_bounded(path: &str) -> Option> { - use std::io::Read; - let cap = photocraft_io::camera_raw_xmp::MAX_XMP_BYTES; - // Checked before opening: opening a pipe for reading waits for a writer. - if !std::fs::metadata(path).ok()?.is_file() { - return None; - } - let file = std::fs::File::open(path).ok()?; - let mut bytes = Vec::new(); - file.take(cap as u64 + 1).read_to_end(&mut bytes).ok()?; - (bytes.len() <= cap).then_some(bytes) + // One nonblocking open judged by the opened handle (regular file, at most the cap): a name + // checked and then opened again could be swapped for a pipe in between. + photocraft_format::read_file_limited(std::path::Path::new(path), photocraft_io::camera_raw_xmp::MAX_XMP_BYTES as u64).ok() } #[cfg(target_arch = "wasm32")] From d71e9fd1bf34b137338a4b9db4e128c5115bb3ef Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:59:36 -0500 Subject: [PATCH 6/8] text: bound copies of preserved style data and font names (#11046) --- crates/io/src/psd_export/document.rs | 10 +- crates/io/tests/it/text_corpus.rs | 4 +- crates/text/src/psd.rs | 2 +- crates/text/src/psd/build.rs | 178 ++++++++++++++++++++++++--- crates/text/src/psd/edit.rs | 127 ++++++++++++++++++- crates/text/src/psd/import.rs | 10 +- 6 files changed, 299 insertions(+), 32 deletions(-) diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index c28f44d1e6..f8f69b7f4e 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -204,8 +204,14 @@ fn export_supported_document( // as Photopea reject it (#3514). Keep the block when the file had one (round-trip its pen // positions/extras), a layer is Optical (#1348), or a layer carries stylistic sets / other // Txt2-only features (#10308). - let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)) - .then(|| photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi)); + // A restyle that would lose a style's fill colour is refused: the file's own block stays as it + // was, and the export says so. + let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)).then(|| { + photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi).unwrap_or_else(|e| { + ex.warnings.push(format!("type styles were not updated in the file's text block: {e}")); + previous.clone().unwrap_or_default() + }) + }); for (sig, key, data) in preserved { // With no type layers left the opened file's `Txt2` describes text that is gone (fonts and // layout caches, often most of the file): Photoshop drops it, and so does the save (#9563). diff --git a/crates/io/tests/it/text_corpus.rs b/crates/io/tests/it/text_corpus.rs index 8edf8a670c..e97b6f988f 100644 --- a/crates/io/tests/it/text_corpus.rs +++ b/crates/io/tests/it/text_corpus.rs @@ -347,7 +347,7 @@ fn corpus_text_psd_legacy_objects_are_edited_in_place() { let items = |value: &E| if let E::Dict(items) = value { items.clone() } else { Vec::new() }; // Unedited: the legacy object and the font list are as the file has them. - let unedited = photocraft_text::psd::parse_txt2(&photocraft_text::psd::build_txt2_at(&[(0, &layer)], Some(&txt2), doc.resolution_dpi)).unwrap(); + let unedited = photocraft_text::psd::parse_txt2(&photocraft_text::psd::build_txt2_at(&[(0, &layer)], Some(&txt2), doc.resolution_dpi).unwrap()).unwrap(); assert!(legacy(&unedited) == legacy(&before), "an unedited layer leaves the legacy text object alone"); assert!(unedited.path(&["DocumentResources", "FontSet"]) == before.path(&["DocumentResources", "FontSet"]), "and the font list it indexes"); @@ -356,7 +356,7 @@ fn corpus_text_psd_legacy_objects_are_edited_in_place() { for run in &mut bigger.runs { run.style.size_pt += 7.0; } - let edited = photocraft_text::psd::parse_txt2(&photocraft_text::psd::build_txt2_at(&[(0, &bigger)], Some(&txt2), doc.resolution_dpi)).unwrap(); + let edited = photocraft_text::psd::parse_txt2(&photocraft_text::psd::build_txt2_at(&[(0, &bigger)], Some(&txt2), doc.resolution_dpi).unwrap()).unwrap(); let (was, now) = (features(&legacy(&before)).expect("features"), features(&legacy(&edited)).expect("features")); let size = |f: &E| f.get("FontSize").and_then(E::as_f64).expect("FontSize"); assert!((size(&now) - size(&was) - 7.0).abs() < 1e-6, "the legacy size follows the edit: {} -> {}", size(&was), size(&now)); diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index bd06d79acd..908bebe0ab 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -27,7 +27,7 @@ mod import; #[cfg(test)] pub(crate) use build::font_entry; -pub use build::{MAX_TEXT_INDEX, build_engine_data, build_txt2, build_txt2_at, build_tysh, needs_txt2}; +pub use build::{MAX_TEXT_INDEX, Txt2Error, build_engine_data, build_txt2, build_txt2_at, build_tysh, needs_txt2}; pub(crate) use build::{font_set, paragraph_properties, style_sheet_data}; pub use edit::{set_text_index, text_index, txt2_object_count}; #[cfg(test)] diff --git a/crates/text/src/psd/build.rs b/crates/text/src/psd/build.rs index 5ba5bc2fa2..72ec9dcdd8 100644 --- a/crates/text/src/psd/build.rs +++ b/crates/text/src/psd/build.rs @@ -1,4 +1,6 @@ -use super::edit::{TEMPLATE_NODES, edited_object, fits, is_stub, names_one_frame, new_object, pad_frames, td_edited_object, with_modes}; +use super::edit::{ + TEMPLATE_NODES, compact, copies_fit_plus, edited_object, fits, is_stub, names_one_frame, new_object, pad_frames, td_edited_object, with_modes, +}; use super::import::{OPENTYPE_KEYS, TXT2_FEATURES, TXT2_STYLISTIC_SETS, kern_units, manual, object_frame, pair_runs, parse_txt2, postscript_for, real}; use super::{ AntiAlias, Caps, CharStyle, Color, ColorMode, D, Descriptor, E, FontBaseline, Id, Kerning, Orientation, ParagraphStyle, TextAlign, TextLayer, TextShape, @@ -206,13 +208,34 @@ fn char_spans(layer: &TextLayer) -> Vec<(usize, i64)> { /// (`/11`). Photoshop reads the character style from here rather than from EngineData, and quit /// on a run holding only the auto-kern mode. `None` when `base` has no style dictionary or is /// larger than a template may be (it is copied once per run). -fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec, dpi: f32, seed_empty: bool) -> Option> { +fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec, dpi: f32, seed_empty: bool) -> Result>, Txt2Error> { if !matches!(base.path(&["0", "0", "6"]), Some(E::Dict(_))) || !fits(base, &mut { TEMPLATE_NODES }) { - return None; + return Ok(None); } let k = if dpi.is_finite() && dpi > 0.0 { dpi / 72.0 } else { 1.0 }; let runs = layer.char_runs(); let spans = char_spans(layer); + // A template too large to copy once per run is compacted rather than given up on: falling + // back would keep the file's old style runs, so the edit would not reach the saved file. + let compacted; + // Each run can gain up to TXT2_ADDED_KEYS keys the template may lack (size, leading, features...). + const TXT2_ADDED_KEYS: usize = 18; + const TXT2_ADDED_KEY_BYTES: usize = 32; + let base = if copies_fit_plus(base, spans.len(), TXT2_ADDED_KEYS, TXT2_ADDED_KEY_BYTES) { + base + } else { + let Some(c) = compact(base, &["0", "0", "6"]).filter(|c| copies_fit_plus(c, spans.len(), TXT2_ADDED_KEYS, TXT2_ADDED_KEY_BYTES)) else { + return Ok(None); + }; + // The fill colour is written into the style's paint dictionary (`/53`): compacting must not + // drop it, or the saved run would have no colour at all. + let paint = ["0", "0", "6", "53"]; + if base.path(&paint).is_some() && c.path(&paint).is_none() { + return Err(Txt2Error::FillColourDropped); + } + compacted = c; + &compacted + }; let default = CharStyle::default(); let mut out = Vec::with_capacity(spans.len()); let mut looked_up = std::collections::HashMap::new(); @@ -220,7 +243,7 @@ fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec, dpi: f32, se let s = runs.get(ri).map_or(&default, |r| &r.style); let font = *looked_up.entry(postscript_for(s)).or_insert_with_key(|name| txt2_font(fonts, name, seed_empty)); let mut run = base.clone(); - let style = run.get_mut("0")?.get_mut("0")?.get_mut("6")?; + let Some(style) = run.get_mut("0").and_then(|r| r.get_mut("0")).and_then(|r| r.get_mut("6")) else { return Ok(None) }; if let Some(font) = font { style.set("0", E::Int(font)); } @@ -247,9 +270,27 @@ fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec, dpi: f32, se run.set("1", E::Int(n)); out.push(run); } - Some(out) + Ok(Some(out)) } +/// Why [`build_txt2_at`] refused to write a block. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Txt2Error { + /// A text style's fill-colour dictionary is too large to copy into each style run; writing the + /// runs without it would lose the requested colour. + FillColourDropped, +} + +impl std::fmt::Display for Txt2Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::FillColourDropped => f.write_str("a text style's fill colour is too large to rewrite, so its style cannot be restyled"), + } + } +} + +impl std::error::Error for Txt2Error {} + /// Whether the style runs of a `Txt2` text model (`/6 /0`) agree with `layer`'s character runs /// on every key [`txt2_style_runs`] writes, the auto-kern mode aside ([`with_modes`] refits that /// on its own): font (by name, through `fonts`, the block's font list), size, faux bold and @@ -473,9 +514,29 @@ fn td_restyled(entry: &E, layer: &TextLayer, fonts: &mut Vec, dpi: f32) -> Op } let k = if dpi.is_finite() && dpi > 0.0 { dpi / 72.0 } else { 1.0 }; let runs = layer.char_runs(); + let spans = char_spans(layer); + // As in `txt2_style_runs`: compact a template too large to copy per run, so the edit still + // reaches this copy instead of the entry keeping its old style. + let compacted; + // Each run can gain the `Features` keys set below (17 + 7 option flags + the style-set mask), the run + // `Length`, and the paint `Type`/`Values`; a bound on their nodes and key bytes (longest key 21 bytes). + const TD_ADDED_KEYS: usize = 40; + const TD_ADDED_KEY_BYTES: usize = 1024; + let base = if copies_fit_plus(base, spans.len(), TD_ADDED_KEYS, TD_ADDED_KEY_BYTES) { + base + } else { + compacted = compact(base, &["RunData", "StyleSheet", "Features"]).filter(|c| copies_fit_plus(c, spans.len(), TD_ADDED_KEYS, TD_ADDED_KEY_BYTES))?; + // As for the Txt2 runs: a restyle that would drop the fill colour dictionary is not made, so + // the entry keeps the colour the file has rather than none. + let paint = ["RunData", "StyleSheet", "Features", "FillColor"]; + if base.path(&paint).is_some() && compacted.path(&paint).is_none() { + return None; + } + &compacted + }; let default = CharStyle::default(); let mut out = Vec::new(); - for (ri, n) in char_spans(layer) { + for (ri, n) in spans { let s = runs.get(ri).map_or(&default, |r| &r.style); let mut run = base.clone(); let features = run.get_mut("RunData")?.get_mut("StyleSheet")?.get_mut("Features")?; @@ -655,12 +716,14 @@ fn fresh_point_text_object(frame: usize, text: &str) -> E { /// is kept, and a block whose content comes out unchanged is returned byte for byte (#2374: /// Photoshop refused files whose `Txt2` an unedited save had stripped). pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec { - build_txt2_at(objects, previous, 72.0) + // A refused restyle keeps the file's block as it was. + build_txt2_at(objects, previous, 72.0).unwrap_or_else(|_| previous.map(<[u8]>::to_vec).unwrap_or_default()) } /// [`build_txt2`] for a document of `dpi` (the style runs of new and edited objects carry sizes -/// in the document's points, as EngineData does). -pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi: f32) -> Vec { +/// in the document's points, as EngineData does). An error when a restyle would lose a style's +/// fill colour ([`Txt2Error`]); nothing is written then. +pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi: f32) -> Result, Txt2Error> { let prev = previous.and_then(parse_txt2); let prev_objects: &[E] = prev.as_ref().and_then(|p| p.path(&["1", "1"]).and_then(E::as_array)).unwrap_or(&[]); let mut slots: Vec = prev_objects.to_vec(); @@ -791,14 +854,32 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi // from these runs, so the template's (or the old text's) would show, and come back on // reopen. They are built on one of the object's own runs, every key Photoshop wrote kept; // without a template run, a minimal base is filled the same way (#10308). - let styled = (!unchanged) - .then(|| { - let file_base = (!is_stub(&object)).then(|| model.path(&["6", "0"]).and_then(E::as_array).and_then(<[E]>::first).cloned()).flatten(); - let base = file_base.or_else(|| native.then(minimal_txt2_style_run))?; - txt2_style_runs(layer, &base, &mut fonts, dpi, seed_empty) - }) - .flatten(); - let file_runs = reuse.then(|| model.path(&["6", "0"]).and_then(E::as_array)).flatten().and_then(|runs| with_modes(runs, &modes)); + let styled = if unchanged { + None + } else { + let file_base = (!is_stub(&object)).then(|| model.path(&["6", "0"]).and_then(E::as_array).and_then(<[E]>::first).cloned()).flatten(); + match file_base.or_else(|| native.then(minimal_txt2_style_run)) { + Some(base) => txt2_style_runs(layer, &base, &mut fonts, dpi, seed_empty)?, + None => None, + } + }; + // The file's own runs, moved out of the model (it gets the runs written below), so keeping + // them copies nothing. + let file_runs = if reuse && styled.is_none() { + model + .get_mut("6") + .and_then(|r| r.get_mut("0")) + .and_then(|r| match std::mem::replace(r, E::Array(Vec::new())) { + E::Array(runs) => Some(runs), + other => { + *r = other; + None + } + }) + .and_then(|runs| with_modes(runs, &modes)) + } else { + None + }; let runs = styled.or(file_runs).unwrap_or_else(|| { modes .iter() @@ -888,13 +969,13 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi if let (Some(bytes), Some(p)) = (previous, &prev) && *p == outer { - return bytes.to_vec(); + return Ok(bytes.to_vec()); } - match outer { + Ok(match outer { E::Dict(items) => ed::write_bare(&items), // Unreachable: `parse_txt2` and the fallback above both yield a dictionary. _ => ed::write_bare(&[]), - } + }) } /// Updates (or creates) an EngineData tree for `layer`. @@ -1156,3 +1237,60 @@ pub fn build_tysh(layer: &TextLayer, dpi: f32, ink: Option<[f32; 4]>) -> Option< let bounds = if warped { [l, t, r, b] } else { [0.0; 4] }; write_tysh(&TySh { transform: layer.transform, text, warp, bounds }) } + +#[cfg(test)] +mod copy_budget_tests { + use super::{CharStyle, E, TextLayer, td_restyled, txt2_style_runs}; + use photocraft_doc::text::TextRun; + + /// A style edit on a layer whose template holds an oversized value still writes the layer's + /// style (from the compacted template), rather than giving up and keeping the old runs. + #[test] + fn an_oversized_template_still_takes_the_new_style() { + let style = E::Dict(vec![("1".into(), E::Real(12.0)), ("99".into(), E::String("x".repeat(1 << 20)))]); + let base = E::Dict(vec![("0".into(), E::Dict(vec![("0".into(), E::Dict(vec![("6".into(), style)]))])), ("1".into(), E::Int(1))]); + // 100 single-letter runs alternating sizes: 100 copies of 1 MiB are past the budget. + let text = "ab".repeat(50); + let runs = (0..100).map(|i| TextRun { len: 1, style: CharStyle { size_pt: if i % 2 == 0 { 30.0 } else { 40.0 }, ..Default::default() } }).collect(); + let layer = TextLayer { text, runs, ..Default::default() }; + let out = txt2_style_runs(&layer, &base, &mut Vec::new(), 72.0, false).unwrap().expect("styled runs"); + assert!(out.len() >= 100); + assert!(out.iter().all(|r| r.path(&["0", "0", "6", "99"]).is_none())); + let size = |r: &E| { + r.path(&["0", "0", "6", "1"]).and_then(|v| match v { + E::Real(f) => Some(*f), + E::Int(i) => Some(*i as f64), + _ => None, + }) + }; + assert_eq!(size(&out[0]), Some(30.0)); + assert_eq!(size(&out[1]), Some(40.0)); + } + + /// A template whose fill-colour dictionary is past the copy budget cannot be restyled without + /// losing the colour: refused, not written colourless. + #[test] + fn an_oversized_fill_colour_refuses_the_restyle() { + let paint = E::Dict(vec![("0".into(), E::Dict(vec![("99".into(), E::String("x".repeat(1 << 20)))]))]); + let style = E::Dict(vec![("1".into(), E::Real(12.0)), ("53".into(), paint)]); + let base = E::Dict(vec![("0".into(), E::Dict(vec![("0".into(), E::Dict(vec![("6".into(), style)]))])), ("1".into(), E::Int(1))]); + let text = "ab".repeat(50); + let runs = (0..100).map(|i| TextRun { len: 1, style: CharStyle { size_pt: if i % 2 == 0 { 30.0 } else { 40.0 }, ..Default::default() } }).collect(); + let layer = TextLayer { text, runs, ..Default::default() }; + assert_eq!(txt2_style_runs(&layer, &base, &mut Vec::new(), 72.0, false), Err(super::Txt2Error::FillColourDropped)); + } + + /// The legacy `TextObjects` copy: an oversized fill-colour dictionary is not compacted away, so + /// the entry is left with the colour the file has instead of a colourless restyle. + #[test] + fn an_oversized_legacy_fill_colour_keeps_the_entry() { + let colour = E::Dict(vec![("Color".into(), E::Dict(vec![("Pad".into(), E::String("x".repeat(1 << 20)))]))]); + let features = E::Dict(vec![("FillColor".into(), colour)]); + let run = E::Dict(vec![("RunData".into(), E::Dict(vec![("StyleSheet".into(), E::Dict(vec![("Features".into(), features)]))]))]); + let entry = E::Dict(vec![("Model".into(), E::Dict(vec![("StyleRun".into(), E::Dict(vec![("RunArray".into(), E::Array(vec![run]))]))]))]); + let text = "ab".repeat(50); + let runs = (0..100).map(|i| TextRun { len: 1, style: CharStyle { size_pt: if i % 2 == 0 { 30.0 } else { 40.0 }, ..Default::default() } }).collect(); + let layer = TextLayer { text, runs, ..Default::default() }; + assert_eq!(td_restyled(&entry, &layer, &mut Vec::new(), 72.0), None); + } +} diff --git a/crates/text/src/psd/edit.rs b/crates/text/src/psd/edit.rs index dd2c80bb45..79eea4654e 100644 --- a/crates/text/src/psd/edit.rs +++ b/crates/text/src/psd/edit.rs @@ -13,6 +13,48 @@ const MAX_REFIT_RUN_NODES: usize = 16_384; const MAX_REFIT_RUN_BYTES: usize = 1 << 20; +/// Cumulative node and string-byte budgets for the style runs copied from one preserved run while +/// restyling (`txt2_style_runs`, `td_restyled`, [`with_modes`]): a template within +/// [`TEMPLATE_NODES`] can still hold long strings, copied once per output run. +const MAX_COPIED_NODES: usize = 1 << 22; +const MAX_COPIED_BYTES: usize = 64 << 20; + +/// Whether `copies` copies of `v` fit [`MAX_COPIED_NODES`] and [`MAX_COPIED_BYTES`]. +#[cfg(test)] +pub(super) fn copies_fit(v: &E, copies: usize) -> bool { + copies_fit_plus(v, copies, 0, 0) +} + +/// [`copies_fit`] where each copy also gains up to `extra_nodes` nodes and `extra_bytes` key bytes +/// (keys the caller adds after copying). +pub(super) fn copies_fit_plus(v: &E, copies: usize, extra_nodes: usize, extra_bytes: usize) -> bool { + let (mut nodes, mut bytes) = (MAX_COPIED_NODES, MAX_COPIED_BYTES); + if !fits_budget(v, &mut nodes, &mut bytes) { + return false; + } + let (n, b) = (MAX_COPIED_NODES - nodes, MAX_COPIED_BYTES - bytes); + n.saturating_add(extra_nodes).checked_mul(copies).is_some_and(|t| t <= MAX_COPIED_NODES) + && b.saturating_add(extra_bytes).checked_mul(copies).is_some_and(|t| t <= MAX_COPIED_BYTES) +} + +/// Values at most this large survive [`compact`]: far above any style value Photoshop writes. +const SMALL_NODES: usize = 256; +const SMALL_BYTES: usize = 4096; + +/// `v` without its oversized values, for a style run template that fails [`copies_fit`]: along +/// `path` each dictionary keeps its small entries and the next step of the path, so every +/// ordinary key is still copied into the new runs and only data no real file holds at that size +/// is left out. `None` when `v` is not a dictionary. +pub(super) fn compact(v: &E, path: &[&str]) -> Option { + let E::Dict(items) = v else { return None }; + let small = |k: &str, x: &E| k.len() <= SMALL_BYTES && fits_budget(x, &mut { SMALL_NODES }, &mut { SMALL_BYTES }); + let kept = items.iter().filter_map(|(k, x)| match path.split_first() { + Some((head, rest)) if k == head => compact(x, rest).map(|c| (k.clone(), c)), + _ => small(k, x).then(|| (k.clone(), x.clone())), + }); + Some(E::Dict(kept.collect())) +} + /// Whether `v` holds at most `budget` values, counting down `budget` (stops at the first one over). pub(super) fn fits(v: &E, budget: &mut usize) -> bool { let Some(left) = budget.checked_sub(1) else { return false }; @@ -243,21 +285,25 @@ fn runs_to_length(runs: &[E], total: usize, len_key: &str, nodes: &mut usize, by /// The file's own `Txt2` style runs `runs` with the auto-kern modes `modes` (`(mode, UTF-16 /// length)`, see [`txt2_mode_runs`]) set at `/0 /0 /6 /11`, keeping every other style key. A /// run a mode change falls inside is split there. `None` when the runs don't cover the text or -/// lack a style dictionary: the caller writes its own runs instead. -pub(super) fn with_modes(runs: &[E], modes: &[(i64, usize)]) -> Option> { +/// lack a style dictionary: the caller writes its own runs instead. Runs are moved, not copied; +/// only the extra pieces a split makes are copies, charged to the copy budget, so an unchanged +/// object keeps its runs whatever their size. +pub(super) fn with_modes(runs: Vec, modes: &[(i64, usize)]) -> Option> { let lens: Vec = runs.iter().map(|r| r.get("1").and_then(E::as_i64).and_then(|l| usize::try_from(l).ok())).collect::>()?; let total = modes.iter().try_fold(0usize, |a, m| a.checked_add(m.1))?; if lens.iter().try_fold(0usize, |a, l| a.checked_add(*l))? != total { return None; } let mut out = Vec::with_capacity(runs.len()); + let (mut nodes, mut bytes) = (MAX_COPIED_NODES, MAX_COPIED_BYTES); let (mut mi, mut mode_end) = (0usize, modes.first()?.1); let mut at = 0usize; - for (run, len) in runs.iter().zip(lens) { + for (run, len) in runs.into_iter().zip(lens) { if len == 0 { - out.push(run.clone()); + out.push(run); continue; } + let mut run = Some(run); let end = at + len; while at < end { while at >= mode_end && mi + 1 < modes.len() { @@ -268,7 +314,16 @@ pub(super) fn with_modes(runs: &[E], modes: &[(i64, usize)]) -> Option> { if piece_end <= at { return None; } - let mut piece = run.clone(); + // The last piece takes the run itself; every earlier one (a mode boundary inside the + // run) is a copy. + let mut piece = if piece_end == end { + run.take()? + } else { + if !fits_budget(run.as_ref()?, &mut nodes, &mut bytes) { + return None; + } + run.clone()? + }; if piece_end - at != len { piece.set("1", E::Int(i64::try_from(piece_end - at).ok()?)); } @@ -318,3 +373,65 @@ pub fn set_text_index(tysh: &[u8], index: i32) -> Option> { } write_tysh(&t) } + +#[cfg(test)] +mod copy_budget_tests { + use super::{E, MAX_COPIED_BYTES, MAX_COPIED_NODES, compact, copies_fit, copies_fit_plus, with_modes}; + + /// `<< /0 << /0 << /6 << /11 1 /99 (filler) >> >> >> /1 len >>`, a Txt2 style run. + fn run(len: i64, filler: usize) -> E { + let style = E::Dict(vec![("11".into(), E::Int(1)), ("99".into(), E::String("x".repeat(filler)))]); + let inner = E::Dict(vec![("6".into(), style)]); + E::Dict(vec![("0".into(), E::Dict(vec![("0".into(), inner)])), ("1".into(), E::Int(len))]) + } + + #[test] + fn copies_of_a_large_preserved_run_are_refused() { + assert!(copies_fit(&run(1, 16), 1000)); + let big = run(1, 1 << 20); + assert!(copies_fit(&big, 63)); + assert!(!copies_fit(&big, MAX_COPIED_BYTES >> 20), "64 copies of 1 MiB pass the byte budget"); + assert!(!copies_fit(&big, usize::MAX)); + } + + #[test] + fn keys_added_per_copy_count_against_the_node_budget() { + let small = run(1, 16); + let copies = MAX_COPIED_NODES / 8; + assert!(copies_fit(&small, copies), "the template alone passes"); + assert!(!copies_fit_plus(&small, copies, 18, 0), "the keys each copy gains do not"); + } + + #[test] + fn key_bytes_added_per_copy_count_against_the_byte_budget() { + let small = run(1, 16); + let copies = 100_000; + assert!(copies_fit_plus(&small, copies, 0, 0), "the template alone passes"); + assert!(!copies_fit_plus(&small, copies, 0, 700), "the key bytes each copy gains do not"); + } + + #[test] + fn compacting_drops_only_oversized_values() { + let big = run(5, 1 << 20); + let small = compact(&big, &["0", "0", "6"]).unwrap(); + // The 1 MiB string goes; the mode key, the path and the length stay. + assert_eq!(small.path(&["0", "0", "6", "11"]).and_then(E::as_i64), Some(1)); + assert!(small.path(&["0", "0", "6", "99"]).is_none()); + assert_eq!(small.get("1").and_then(E::as_i64), Some(5)); + assert!(copies_fit(&small, 100_000)); + // An ordinary run comes back whole. + assert_eq!(compact(&run(5, 16), &["0", "0", "6"]), Some(run(5, 16))); + } + + #[test] + fn mode_splits_stop_at_the_copy_budget() { + // One run, 1 MiB of preserved text, split at every one of 200 mode boundaries. + let modes: Vec<(i64, usize)> = (0..200).map(|i| (i % 2, 1)).collect(); + assert!(with_modes(vec![run(200, 1 << 20)], &modes).is_none()); + assert_eq!(with_modes(vec![run(200, 16)], &modes).map(|v| v.len()), Some(200)); + // Unsplit runs are moved, not copied: an unchanged object keeps them whatever their size. + let kept = vec![run(100, 1 << 20), run(100, 1 << 20)]; + let modes = [(1, 100), (1, 100)]; + assert_eq!(with_modes(kept.clone(), &modes), Some(kept)); + } +} diff --git a/crates/text/src/psd/import.rs b/crates/text/src/psd/import.rs index f17de4c90c..983e5fbb90 100644 --- a/crates/text/src/psd/import.rs +++ b/crates/text/src/psd/import.rs @@ -390,6 +390,10 @@ fn descriptor_rect(text: &Descriptor, key: &str) -> Option<[f64; 4]> { pub(super) const MAX_ENGINE_RUNS: usize = 65_536; +/// The longest `FontSet` name kept. PostScript names are at most 63 characters; family names in +/// the files seen are shorter than this. +const MAX_FONT_NAME: usize = 1024; + pub(crate) fn arr_f(v: Option<&E>) -> Vec { v.and_then(E::as_array).map(|a| a.iter().take(MAX_ENGINE_RUNS).filter_map(E::as_f64).collect()).unwrap_or_default() } @@ -435,7 +439,9 @@ fn apply_engine_data(layer: &mut TextLayer, e: &E, txt: Option<&str>, k: f32) { let fonts: Vec = res .and_then(|r| r.get("FontSet")) .and_then(E::as_array) - .map(|a| a.iter().map(|f| f.get("Name").and_then(E::as_str).unwrap_or("").to_string()).collect()) + // Every character run naming a font copies its name (family and PostScript name): a name + // past any real one's length is dropped, so one huge entry can't be multiplied by the runs. + .map(|a| a.iter().map(|f| f.get("Name").and_then(E::as_str).filter(|n| n.len() <= MAX_FONT_NAME).unwrap_or("").to_string()).collect()) .unwrap_or_default(); // Style resolution (#3795). A run's own `StyleSheetData` / `Properties` hold only what it // overrides; the rest comes from its sheets, as in Photoshop: @@ -563,7 +569,7 @@ pub(crate) fn char_style(base: &[Option<&E>], d: &E, fonts: &[String], k: f32) - let numk = |key: &str, k: f32| num(key).map(|v| v as f32 * k).filter(|v| v.is_finite()); let flag = |key: &str| g(key).and_then(E::as_bool); let mut s = CharStyle::default(); - if let Some(ps) = g("Font").and_then(E::as_i64).and_then(|i| usize::try_from(i).ok()).and_then(|i| fonts.get(i)) { + if let Some(ps) = g("Font").and_then(E::as_i64).and_then(|i| usize::try_from(i).ok()).and_then(|i| fonts.get(i)).filter(|ps| !ps.is_empty()) { let r = guess_from_postscript(ps); s.font_family = r.family; s.weight = r.weight; From 2163bd45afc0c963749e84e55d1a078665b7cb31 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:59:41 -0500 Subject: [PATCH 7/8] security(doc): resolve slice visibility in one sweep, cap resolved slice count (#10959) --- crates/doc/src/slices.rs | 277 ++++++++++++++++----- crates/engine/src/cmd/slice_cmds.rs | 3 +- crates/engine/src/cmd/web_cmds/save_web.rs | 5 +- crates/engine/src/cmd/web_cmds/tests.rs | 14 ++ crates/ui-egui/src/dialogs/file_ui/web.rs | 8 + 5 files changed, 244 insertions(+), 63 deletions(-) diff --git a/crates/doc/src/slices.rs b/crates/doc/src/slices.rs index 9e66752833..6bfb9b1577 100644 --- a/crates/doc/src/slices.rs +++ b/crates/doc/src/slices.rs @@ -167,34 +167,44 @@ pub struct ResolvedSlice { pub kind: SliceKind, } -/// The visible part of every stored slice (later slices cover earlier ones, as in Photoshop), -/// clipped to the canvas: a covered slice is cut into the rectangles that stay visible, each -/// paired with the slice's index in the list. -fn visible(doc: &Document) -> Vec<(usize, Rect)> { - let canvas = doc.bounds(); - let rects: Vec = doc.slices.list.iter().map(|s| s.rect.intersect(&canvas)).collect(); - let mut out = Vec::new(); - for (i, r) in rects.iter().enumerate() { - let above = rects.get(i + 1..).unwrap_or_default(); - out.extend(auto_slices(*r, above).into_iter().map(|p| (i, p))); - } - out +/// The most stored slices [`resolve`] considers; later ones in the list are left out. A Divide +/// Slice makes at most 10 000 parts, and Photoshop documents hold a few hundred at most, but a +/// file's slice resource is only bounded by its size. The partition below is quadratic in the +/// slice count for nested rectangles, so this keeps a hostile list to well under a second of work. +pub const MAX_RESOLVED_SLICES: usize = 10_000; + +/// A warning naming how many stored slices [`resolve`] leaves out (`None` when it considers all). +pub fn overflow_warning(doc: &Document) -> Option { + let n = doc.slices.list.len().checked_sub(MAX_RESOLVED_SLICES).filter(|n| *n > 0)?; + Some(format!("{n} stored slices past the first {MAX_RESOLVED_SLICES} were ignored")) } /// Rectangles that tile `canvas` minus `taken`. The canvas is cut into a grid along every slice /// edge; free cells merge into horizontal runs per row band, then runs with identical columns /// merge down, which yields the few large auto slices Photoshop shows. pub fn auto_slices(canvas: Rect, taken: &[Rect]) -> Vec { + partition(canvas, taken, false).1 +} + +/// Splits `canvas` by `rects` (later rects on top) in one sweep: for each rect, the pieces of it +/// that no later rect covers, and the pieces that no rect covers. +/// +/// The canvas is cut into a grid along every rect edge. Each row band is painted from the topmost +/// rect down, skipping cells already painted (a next-free-cell index), so every cell is written +/// once per band. Consecutive cells with the same owner make a horizontal run, and runs with the +/// same owner and columns merge down. Resolving each rect against the rects above it separately +/// rebuilt that grid once per rect and re-marked shared overlaps every time, which was quartic in +/// the slice count for nested rectangles and let a crafted document stall canvas drawing. +fn partition(canvas: Rect, rects: &[Rect], want_owned: bool) -> (Vec>, Vec) { + let mut owned_runs: Vec> = vec![Vec::new(); rects.len()]; + let mut free_runs: Vec = Vec::new(); if canvas.is_empty() { - return Vec::new(); + return (owned_runs, free_runs); } + let clipped: Vec = rects.iter().map(|r| r.intersect(&canvas)).collect(); let mut xs = vec![canvas.x0, canvas.x1]; let mut ys = vec![canvas.y0, canvas.y1]; - for r in taken { - let r = r.intersect(&canvas); - if r.is_empty() { - continue; - } + for r in clipped.iter().filter(|r| !r.is_empty()) { xs.extend([r.x0, r.x1]); ys.extend([r.y0, r.y1]); } @@ -202,47 +212,94 @@ pub fn auto_slices(canvas: Rect, taken: &[Rect]) -> Vec { xs.dedup(); ys.sort_unstable(); ys.dedup(); - // Clip the taken rectangles to the canvas once, so band coverage only considers rects that - // can actually cover a cell. - let clipped: Vec = taken.iter().map(|r| r.intersect(&canvas)).filter(|r| !r.is_empty()).collect(); - // Map an x edge to its cell index in `xs` (xs is sorted/deduped). - let x_cell = |x: i32| xs.partition_point(|&e| e <= x).saturating_sub(1); - // Horizontal runs per row band. For each band, mark covered x-cells in a single pass over - // the rects intersecting that band, instead of scanning every rect for every cell (which - // was cubic in the slice count and let a crafted document stall canvas drawing). + // Every clipped edge is in `xs`/`ys`, so these are exact grid indices. + let x_edge = |x: i32| xs.partition_point(|&e| e < x); + let y_edge = |y: i32| ys.partition_point(|&e| e < y); + let nbands = ys.len().saturating_sub(1); let ncells = xs.len().saturating_sub(1); - let mut runs: Vec = Vec::new(); - for yw in ys.windows(2) { - let (band_y0, band_y1) = (yw[0], yw[1]); - let mut covered_cell = vec![false; ncells]; - for r in &clipped { - if r.y0 <= band_y0 && band_y1 <= r.y1 { - // Rect spans this whole band vertically; mark the x-cells it covers. - let (c0, c1) = (x_cell(r.x0), x_cell(r.x1)); - for c in covered_cell.iter_mut().take(c1).skip(c0) { - *c = true; - } - } - } - let mut start: Option = None; - for (ci, xw) in xs.windows(2).enumerate() { - let free = !covered_cell.get(ci).copied().unwrap_or(false); - match (free, start) { - (true, None) => start = Some(xw[0]), - (false, Some(s)) => { - runs.push(Rect::new(s, band_y0, xw[0], band_y1)); - start = None; - } - _ => {} - } - } - if let Some(s) = start { - runs.push(Rect::new(s, band_y0, *xs.last().unwrap_or(&canvas.x1), band_y1)); + // Rects entering and leaving the sweep at each band edge. + let mut enter: Vec> = vec![Vec::new(); ys.len()]; + let mut leave: Vec> = vec![Vec::new(); ys.len()]; + let mut cols: Vec<(usize, usize)> = vec![(0, 0); rects.len()]; + for (i, r) in clipped.iter().enumerate().filter(|(_, r)| !r.is_empty()) { + if let (Some(e), Some(l), Some(c)) = (enter.get_mut(y_edge(r.y0)), leave.get_mut(y_edge(r.y1)), cols.get_mut(i)) { + e.push(i); + l.push(i); + *c = (x_edge(r.x0), x_edge(r.x1)); } } - // Merge vertically adjacent runs with the same columns. - // `open` finds the slice a run continues by its columns and bottom edge: searching the output - // for each run is quadratic in the runs, and bars crossing in a grid leave a million of them. + let mut active: std::collections::BTreeSet = std::collections::BTreeSet::new(); + let mut owner: Vec = vec![usize::MAX; ncells]; + // next[c]: the first unpainted cell at or after c (ncells when none). + let mut next: Vec = (0..=ncells).collect(); + for b in 0..nbands { + for i in leave.get(b).into_iter().flatten() { + active.remove(i); + } + active.extend(enter.get(b).into_iter().flatten().copied()); + let (Some(&band_y0), Some(&band_y1)) = (ys.get(b), ys.get(b + 1)) else { break }; + owner.fill(usize::MAX); + for (c, n) in next.iter_mut().enumerate() { + *n = c; + } + for &i in active.iter().rev() { + let (c0, c1) = cols.get(i).copied().unwrap_or((0, 0)); + let mut c = find_free(&mut next, c0); + while c < c1 { + if let Some(o) = owner.get_mut(c) { + *o = i; + } + if let Some(n) = next.get_mut(c) { + *n = c + 1; + } + c = find_free(&mut next, c + 1); + } + } + let mut c = 0; + while c < ncells { + let who = owner.get(c).copied().unwrap_or(usize::MAX); + let mut end = c + 1; + while end < ncells && owner.get(end).copied() == Some(who) { + end += 1; + } + if let (Some(&x0), Some(&x1)) = (xs.get(c), xs.get(end)) { + let run = Rect::new(x0, band_y0, x1, band_y1); + match owned_runs.get_mut(who) { + Some(runs) => { + if want_owned { + runs.push(run); + } + } + None => free_runs.push(run), + } + } + c = end; + } + } + (owned_runs.into_iter().map(merge_down).collect(), merge_down(free_runs)) +} + +/// The first unpainted cell at or after `c`, compressing the path it walks. +fn find_free(next: &mut [usize], c: usize) -> usize { + let mut root = c; + while let Some(&n) = next.get(root) { + if n == root { + break; + } + root = n; + } + let mut c = c; + while c != root { + let Some(slot) = next.get_mut(c) else { break }; + c = std::mem::replace(slot, root); + } + root +} + +/// Merges vertically adjacent runs (given band by band, top to bottom) with the same columns. +/// `open` finds the slice a run continues by its columns and bottom edge: searching the output +/// for each run is quadratic in the runs, and bars crossing in a grid leave a million of them. +fn merge_down(runs: Vec) -> Vec { let mut out: Vec = Vec::new(); let mut open: std::collections::HashMap<(i32, i32, i32), usize> = std::collections::HashMap::new(); for r in runs { @@ -268,10 +325,10 @@ pub fn auto_slices(canvas: Rect, taken: &[Rect]) -> Vec { /// appears once per visible piece: the first piece keeps its name, the others are `-NN`. pub fn resolve(doc: &Document) -> Vec { let base = base_name(doc); - let stored = visible(doc); - let rects: Vec = stored.iter().map(|(_, r)| *r).collect(); - let mut all: Vec<(Option, Rect)> = stored.iter().map(|(i, r)| (Some(*i), *r)).collect(); - all.extend(auto_slices(doc.bounds(), &rects).into_iter().map(|r| (None, r))); + let rects: Vec = doc.slices.list.iter().take(MAX_RESOLVED_SLICES).map(|s| s.rect).collect(); + let (owned, free) = partition(doc.bounds(), &rects, true); + let mut all: Vec<(Option, Rect)> = owned.into_iter().enumerate().flat_map(|(i, pieces)| pieces.into_iter().map(move |p| (Some(i), p))).collect(); + all.extend(free.into_iter().map(|r| (None, r))); all.sort_by_key(|(_, r)| (r.y0, r.x0)); let single = all.len() == 1; let mut named = vec![false; doc.slices.list.len()]; @@ -414,6 +471,106 @@ mod tests { assert_eq!(names, ["o82_01", "o82_03"]); } + /// The earlier resolver: each stored slice cut against the slices above it on its own grid, + /// then the auto slices cut against the visible pieces. + fn reference_resolve(canvas: Rect, rects: &[Rect]) -> (Vec<(usize, Rect)>, Vec) { + fn cut(canvas: Rect, taken: &[Rect]) -> Vec { + if canvas.is_empty() { + return Vec::new(); + } + let clipped: Vec = taken.iter().map(|r| r.intersect(&canvas)).filter(|r| !r.is_empty()).collect(); + let mut xs = vec![canvas.x0, canvas.x1]; + let mut ys = vec![canvas.y0, canvas.y1]; + for r in &clipped { + xs.extend([r.x0, r.x1]); + ys.extend([r.y0, r.y1]); + } + xs.sort_unstable(); + xs.dedup(); + ys.sort_unstable(); + ys.dedup(); + let mut runs = Vec::new(); + for yw in ys.windows(2) { + let mut start = None; + for xw in xs.windows(2) { + let free = !clipped.iter().any(|r| r.x0 <= xw[0] && xw[1] <= r.x1 && r.y0 <= yw[0] && yw[1] <= r.y1); + match (free, start) { + (true, None) => start = Some(xw[0]), + (false, Some(s)) => { + runs.push(Rect::new(s, yw[0], xw[0], yw[1])); + start = None; + } + _ => {} + } + } + if let Some(s) = start { + runs.push(Rect::new(s, yw[0], canvas.x1, yw[1])); + } + } + merge_down(runs) + } + let clipped: Vec = rects.iter().map(|r| r.intersect(&canvas)).collect(); + let mut stored = Vec::new(); + for (i, r) in clipped.iter().enumerate() { + stored.extend(cut(*r, &clipped[i + 1..]).into_iter().map(|p| (i, p))); + } + let pieces: Vec = stored.iter().map(|(_, r)| *r).collect(); + let free = cut(canvas, &pieces); + (stored, free) + } + + #[test] + fn sweep_partition_matches_per_slice_resolution() { + // A small deterministic generator: overlapping, nested, touching and off-canvas rects. + let mut seed = 0x2545_f491_u32; + let mut next = |m: i32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + (seed % (m as u32)) as i32 + }; + let canvas = Rect::new(0, 0, 120, 90); + for round in 0..200 { + let n = 1 + round % 9; + let rects: Vec = (0..n) + .map(|_| { + let (x, y) = (next(140) - 10, next(110) - 10); + Rect::new(x, y, x + next(70), y + next(60)) + }) + .collect(); + let (owned, free) = partition(canvas, &rects, true); + let got: Vec<(usize, Rect)> = owned.into_iter().enumerate().flat_map(|(i, ps)| ps.into_iter().map(move |p| (i, p))).collect(); + let (want, want_free) = reference_resolve(canvas, &rects); + assert_eq!(got, want, "pieces for {rects:?}"); + assert_eq!(free, want_free, "auto slices for {rects:?}"); + } + } + + #[test] + fn nested_slices_resolve_in_bounded_work() { + // Nested rectangles were the quartic case: every slice re-marked every later overlap on + // its own grid. Each ring here stays visible as four bars around the next slice in. + let n = 2_000; + let mut d = Document::new("nest.psd", Size::new(10_000, 10_000), ColorMode::Rgb, SampleType::U8); + d.slices.list = (0..n).map(|i| Slice { id: i as u32 + 1, rect: Rect::new(i, i, 10_000 - i, 10_000 - i), ..Default::default() }).collect(); + let r = resolve(&d); + let stored = r.iter().filter(|s| s.id.is_some()).count(); + assert_eq!(stored, 4 * (n as usize - 1) + 1); + assert_eq!(r.iter().map(|s| i64::from(s.rect.width()) * i64::from(s.rect.height())).sum::(), 10_000 * 10_000); + } + + #[test] + fn slices_past_the_limit_are_left_out() { + let mut d = Document::new("many.psd", Size::new(100, 100), ColorMode::Rgb, SampleType::U8); + d.slices.list = (0..MAX_RESOLVED_SLICES + 5).map(|i| Slice { id: i as u32 + 1, rect: Rect::new(0, 0, 10, 10), ..Default::default() }).collect(); + let r = resolve(&d); + let ids: Vec = r.iter().filter_map(|s| s.id).collect(); + assert_eq!(ids, [MAX_RESOLVED_SLICES as u32], "the topmost considered slice covers the others"); + assert!(overflow_warning(&d).unwrap().starts_with("5 stored slices")); + d.slices.list.truncate(MAX_RESOLVED_SLICES); + assert_eq!(overflow_warning(&d), None); + } + #[test] fn exhausted_slice_id_survives_serialization() { let slices = Slices { list: vec![Slice { id: u32::MAX, ..Default::default() }], ..Default::default() }; diff --git a/crates/engine/src/cmd/slice_cmds.rs b/crates/engine/src/cmd/slice_cmds.rs index 0cdb4a95e3..3e8eee6951 100644 --- a/crates/engine/src/cmd/slice_cmds.rs +++ b/crates/engine/src/cmd/slice_cmds.rs @@ -485,7 +485,8 @@ fn list(s: &mut Session) -> Result { for sl in d.doc.slices.list.iter().filter(|sl| !listed.contains(&sl.id) && !sl.rect.intersect(&canvas).is_empty()) { all.extend(stored_json(&d.doc, sl.id, &resolved)); } - Ok(json!({"slices": all, "locked": s.file_menu.slices_locked})) + let warnings: Vec = slices::overflow_warning(&d.doc).into_iter().collect(); + Ok(json!({"slices": all, "locked": s.file_menu.slices_locked, "warnings": warnings})) } fn layer_based(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/web_cmds/save_web.rs b/crates/engine/src/cmd/web_cmds/save_web.rs index 66c278c497..a6478b76ea 100644 --- a/crates/engine/src/cmd/web_cmds/save_web.rs +++ b/crates/engine/src/cmd/web_cmds/save_web.rs @@ -242,7 +242,8 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u let xmp = web_xmp(&doc, st.metadata); let exif = web_exif(&doc, st.metadata); let dpi = wdoc.resolution_dpi; - let warnings = web_warnings(&st, exif, dpi); + let mut warnings = web_warnings(&st, exif, dpi); + warnings.extend(slices::overflow_warning(&doc)); let all = slices::resolve(&doc); let picked = |r: &ResolvedSlice| match &pick { SlicePick::Numbers(n) => n.contains(&(r.number as u64)), @@ -266,7 +267,7 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u if single.is_none() && dir.is_none() && folder.is_none() { let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; return Ok( - json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "colorTable": o.color_table.iter().map(|c| rgb_hex(*c)).collect::>(), "transparentIndex": o.transparent_index}), + json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "colorTable": o.color_table.iter().map(|c| rgb_hex(*c)).collect::>(), "transparentIndex": o.transparent_index, "warnings": warnings}), ); } if let Some(folder) = folder { diff --git a/crates/engine/src/cmd/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs index a372274584..bc1d154e07 100644 --- a/crates/engine/src/cmd/web_cmds/tests.rs +++ b/crates/engine/src/cmd/web_cmds/tests.rs @@ -49,6 +49,20 @@ fn estimates_preserve_last_successful_export_settings() { /// The next launch's dialog seeds from the preferences: `file_menu` is not saved, so a complete /// export remembers its settings in `prefs.dialogs` too, as Fill and the filter dialogs do. +/// Stored slices past the resolve limit are reported by the estimate as well as by the export. +#[test] +fn the_estimate_reports_ignored_slices() { + let mut s = session(8); + s.edit("slices", |doc, _| { + let n = photocraft_doc::slices::MAX_RESOLVED_SLICES + 2; + doc.slices.list = (0..n).map(|i| photocraft_doc::Slice { id: i as u32 + 1, rect: Rect::new(0, 0, 8, 8), ..Default::default() }).collect(); + Ok(()) + }) + .unwrap(); + let estimate = s.execute("file.export.saveForWebLegacy", json!({"format": "png24"})).unwrap(); + assert!(estimate["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("2 stored slices"))), "{estimate}"); +} + #[test] fn a_complete_export_remembers_its_settings_in_the_preferences() { let dir = tmp("remember_settings"); diff --git a/crates/ui-egui/src/dialogs/file_ui/web.rs b/crates/ui-egui/src/dialogs/file_ui/web.rs index 450ac006b9..1ca658143a 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web.rs @@ -177,6 +177,10 @@ fn web_pane(app: &PhotocraftApp, ui: &mut egui::Ui, size: egui::Vec2, p: Option< let l1 = if ratio > 1.001 { format!("{l1} ยท Proxy preview") } else { l1 }; ui.add(egui::Label::new(egui::RichText::new(l1).color(t.text).size(11.5)).truncate()); ui.add(egui::Label::new(egui::RichText::new(l2).color(t.text_dim).size(11.0)).truncate()); + // Before anything is written: slices past the resolve limit are left out of the export. + if let Some(w) = photocraft_doc::slices::overflow_warning(&doc) { + ui.add(egui::Label::new(egui::RichText::new(w).color(t.warning).size(11.0)).truncate()); + } }); } @@ -643,6 +647,10 @@ fn save_for_web(app: &mut PhotocraftApp, p: Value) -> Result { app.sync_views(); app.ui.status = crate::i18n::trn(crate::i18n::current(), r["files"].as_array().map_or(0, Vec::len) as u64, "Saved for Web: {n} file", "Saved for Web: {n} files"); + // Warnings (such as ignored slices) go in the status line: the dialog closes on success. + if let Some(w) = r["warnings"].as_array().filter(|w| !w.is_empty()) { + app.ui.status = format!("{} ({})", app.ui.status, w.iter().filter_map(Value::as_str).collect::>().join("; ")); + } app.ui.status_error = false; Ok(r) } From 01b79958a7b73c3d840b76492069e9635f9f7394 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:28:19 +0100 Subject: [PATCH 8/8] ci(freebsd): build every target with the test profile so ui-egui's tests fit the VM (#15360) * ci(freebsd): build with two cargo jobs so the aarch64 cross build fits the VM The nightly aarch64 leg (a cold cross build of every target in the shared workflow's 12 GB FreeBSD guest, CARGO_BUILD_JOBS=4) was killed with exit 137 twenty minutes into ui-egui's targets, while photocraft-web compiled alongside them (run 43936108201). The same cold build passed on 15 Nov, so it is at the edge of the guest's memory. Pass `--jobs 2` through the existing cargo-build-extra-args input. It applies to the build step of both legs; the x86_64 test commands keep the shared four jobs. * ci(freebsd): build with the test profile, not two jobs Two jobs didn't fix it: the x86_64 leg of the dispatched run was SIGKILLed the same way at --jobs 2 (run 43963415772). The killed rustc was ui-egui's lib test target at -C opt-level=1: `cargo build --all-targets` builds test targets with the dev profile, so Cargo.toml's `[profile.test.package.photocraft-ui-egui] opt-level = 0` never applied to the build step. That one optimised rustc over about 390k lines and 7700 tests ran the 12 GB guest out of memory, and `cargo test` then rebuilt the same target at opt-level 0 (1m47s on x86_64) anyway. Pass `--profile test` instead, so the build compiles every target as the tests do: ui-egui at opt-level 0, debuginfo still off through CARGO_PROFILE_DEV_DEBUG=0 (test inherits dev), and the test commands reuse the build's artifacts. * ci(freebsd): test ui-egui with the build's package selection `cargo test -p photocraft-ui-egui` resolves dependency features without the other workspace members, so egui, epaint and everything above them got new hashes. The test step then rebuilt ui-egui's lib tests instead of reusing the build step's, and that rustc was SIGKILLed in the 12 GB guest. Run ui-egui's lib, doc and integration tests through `--workspace --features heif --exclude photocraft-gpu`, which resolves the same units as the build (checked with cargo's unit graph: 0 units missing from the build, against 146 for `-p photocraft-ui-egui --lib`). The integration tests share one command, so all of them run one at a time. --- .github/workflows/freebsd.yml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index 2b98d8c11d..cfa3fe8876 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -33,8 +33,20 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 - cargo-build-extra-args: "--features heif" + # Build every target with the profile the tests use. Plain `cargo build --all-targets` builds + # test targets with the dev profile, so ui-egui's lib tests (about 390k lines, 7700 tests) + # were compiled at opt-level 1 rather than Cargo.toml's test-profile opt-level 0, and that + # rustc ran the 12 GB guest out of memory (SIGKILL, nightly and dispatched runs on both + # legs). + cargo-build-extra-args: "--features heif --profile test" + # The test commands reuse that build only if they resolve the same features. `-p + # photocraft-ui-egui` (or `--exclude photocraft-ui-egui`) leaves out the other members' + # feature requests, so egui, epaint and the crates above them got new hashes and the test + # step rebuilt ui-egui's lib tests, where that rustc was SIGKILLed again. So ui-egui is + # tested with the build's selection, `--workspace --features heif`. Excluding + # photocraft-gpu leaves the resolution unchanged; its own command rebuilds only its graph. # The VM's software Vulkan driver crashes (SIGSEGV) when several tests set up a device at - # once, so photocraft-gpu's tests run one at a time, like ui-egui's integration tests. - custom-test-command: "CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked --features heif --exclude photocraft-ui-egui --exclude photocraft-gpu && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-gpu --locked -- --test-threads=1 && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --lib && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --doc && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --test '*' -- --test-threads=1" + # once, so photocraft-gpu's tests and the integration tests (ui-egui's among them; one + # command runs them all) run one at a time. + custom-test-command: "CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked --features heif --exclude photocraft-gpu --lib --bins && CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked --features heif --exclude photocraft-gpu --doc && CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked --features heif --exclude photocraft-gpu --test '*' -- --test-threads=1 && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-gpu --locked -- --test-threads=1" run-package-check: true