PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(psd): an edited type layer keeps its Txt2 object instead of a bare stub (#6968)
Higgs32584204c76ce36ab
diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rsindex 8c502c75a..41d65ff88 100644--- a/crates/text/src/psd.rs+++ b/crates/text/src/psd.rs@@ -964,8 +964,10 @@ pub fn needs_txt2(objects: &[(i32, &TextLayer)]) -> bool {/// unchanged — keeps everything the file held beyond the two regenerated keys (its model's text/// and style runs): Photoshop stores glyph pen positions under `/21 /1` there, and a save with/// no text edit must not drop them. Its own style runs keep every style key too: only their-/// auto-kern mode is set (split where a mode changes inside a run). A changed text invalidates-/// those extras along with the old runs, so they are dropped rather than left stale. Everything+/// auto-kern mode is set (split where a mode changes inside a run). An edited object — the+/// file's object at that slot, its text changed — keeps the object too, with its text replaced+/// and its run arrays refitted to the new text (#6968: a bare stub crashed Photoshop); only its+/// glyph pen positions, which belong to the old text, are dropped. Everything/// else the file's block held — the other keys beside the text objects, objects no layer names —/// 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).@@ -981,9 +983,15 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Veclet modes = txt2_mode_runs(layer);let at = *index as usize;let kept = prev_objects.get(at).filter(|o| o.get("0").and_then(|m| m.get("0")).and_then(E::as_str) == Some(text.as_str()));- let mut object = kept.cloned().unwrap_or_else(E::dict);+ // An edited object (#6968): the file's object at this slot with its text changed. It keeps+ // the file's structure — paragraph runs, the view naming its frame, the rest — with every+ // run array refitted to the new text. A bare `<< /0 << /0 text /6 runs >> >>` stub in+ // Photoshop's block (no paragraph runs, no view) made Photoshop quit while opening the file.+ let edited = kept.is_none().then(|| prev_objects.get(at).and_then(|o| edited_object(o, &text))).flatten();+ let reuse = kept.is_some() || edited.is_some();+ let mut object = kept.cloned().or(edited).unwrap_or_else(E::dict);let mut model = object.get("0").cloned().filter(|m| matches!(m, E::Dict(_))).unwrap_or_else(E::dict);- let file_runs = kept.and_then(|_| model.path(&["6", "0"]).and_then(E::as_array)).and_then(|runs| with_modes(runs, &modes));+ let file_runs = reuse.then(|| model.path(&["6", "0"]).and_then(E::as_array)).flatten().and_then(|runs| with_modes(runs, &modes));let runs = file_runs.unwrap_or_else(|| {modes.iter()@@ -1028,6 +1036,77 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec}}+/// The file's `Txt2` text object `object` (`<< /0 model /1 view … >>`) for the changed engine+/// text `text` (`\r` breaks, trailing `\r`): the model's text replaced, its paragraph runs (`/5`)+/// one per paragraph of the new text (each keeping the style of the file's paragraph at that+/// position, else its last), and every other run array of the model (style runs `/6`, …) cut or+/// extended at its end to the new length. The view and the other keys are kept, except the glyph+/// pen positions (`/21`), which belong to the old text. `None` when the object or one of its run+/// arrays isn't shaped as Photoshop writes it: the caller writes a fresh object instead.+fn edited_object(object: &E, text: &str) -> Option<E> {+ let mut object = object.clone();+ let E::Dict(items) = &mut object else { return None };+ items.retain(|(k, _)| k != "21");+ let model = object.get_mut("0").filter(|m| matches!(m, E::Dict(_)))?;+ let total = utf16_len(text) as usize;+ let paragraphs: Vec<usize> = text.split_inclusive('\r').map(|p| p.encode_utf16().count()).collect();+ let E::Dict(entries) = model else { return None };+ for (key, value) in entries.iter_mut() {+ if key.as_str() == "0" {+ *value = E::String(text.to_string());+ continue;+ }+ let Some(runs) = value.get("0").and_then(E::as_array).filter(|r| r.iter().all(|x| matches!(x, E::Dict(_)) && x.get("1").is_some())) else {+ continue;+ };+ let fitted = if key.as_str() == "5" { runs_per(runs, ¶graphs)? } else { runs_to_length(runs, total)? };+ value.set("0", E::Array(fitted));+ }+ Some(object)+}++/// `runs` (`<< … /1 length >>`) remade with the lengths `lens`: run i keeps the content of the+/// file's run i, else of its last one. `None` for an empty `runs`.+fn runs_per(runs: &[E], lens: &[usize]) -> Option<Vec<E>> {+ let last = runs.last()?;+ lens.iter()+ .enumerate()+ .map(|(i, &len)| {+ let mut r = runs.get(i).unwrap_or(last).clone();+ r.set("1", E::Int(i64::try_from(len).ok()?));+ Some(r)+ })+ .collect()+}++/// `runs` (`<< … /1 length >>`) covering `total` UTF-16 units: the leading runs as they were, cut+/// where `total` ends, the last kept run extended when `total` is longer. Empty runs are dropped.+/// `None` when `runs` is empty or a length isn't a count.+fn runs_to_length(runs: &[E], total: usize) -> Option<Vec<E>> {+ let mut out: Vec<(E, usize)> = Vec::new();+ let mut left = total;+ for r in runs {+ let len = r.get("1").and_then(E::as_i64).and_then(|l| usize::try_from(l).ok())?;+ let take = len.min(left);+ if take > 0 {+ out.push((r.clone(), take));+ left -= take;+ }+ }+ if left > 0 {+ match out.last_mut() {+ Some(last) => last.1 = last.1.checked_add(left)?,+ None => out.push((runs.last()?.clone(), left)),+ }+ }+ out.into_iter()+ .map(|(mut r, len)| {+ r.set("1", E::Int(i64::try_from(len).ok()?));+ Some(r)+ })+ .collect()+}+/// 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 ordiff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rsindex 894ecf4e4..d2aaa78a4 100644--- a/crates/text/src/tests.rs+++ b/crates/text/src/tests.rs@@ -1097,6 +1097,56 @@ fn edited_txt2_keeps_the_files_styles_and_objects() {assert_eq!(modes, vec![(1, Kerning::Optical), (2, Kerning::Metrics)]);}+/// #6968: editing the text of a Photoshop type layer keeps its `Txt2` object — paragraph runs,+/// the view naming its frame, the model's other run arrays and its style keys — refitted to the+/// new text. It was replaced by a bare `<< /0 << /0 text /6 runs >> >>` stub, and Photoshop quit+/// while opening the file.+#[test]+fn edited_text_keeps_the_files_txt2_object() {+ use crate::engine_data::Value as E;+ let run = |extra: &str, len: usize| format!("<< /0 << /0 << /0 (\u{fe}\u{ff}) /5 << /7 1.2 >> /6 << /0 0 /1 12.0 {extra} >> >> >> /1 {len} >> ");+ // "AB\rCD\r": two paragraphs, two style runs, a kern run, a view and pen positions.+ let prev = format!(+ "\n\n/98 << /0 7 >> /0 << /8 << /0 [ << /0 << /2 << /2 [ 1.0 0.0 0.0 1.0 5.0 6.0 ] >> >> >> ] >> >> /1 << /0 << /0 1 >> /1 [ << /0 << /0 (\u{fe}\u{ff}\0A\0B\0\r\0C\0D\0\r) /5 << /0 [ {}{}] >> /6 << /0 [ {}{}] >> /7 << /0 [ << /0 << >> /1 6 >> ] >> >> /1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC >> ] >> /21 << /1 [ 1.0 ] >> >> ] /2 << /0 7 >> >>",+ run("", 3),+ run("", 3),+ run("/11 1", 2),+ run("/11 1 /53 (red)", 4)+ );+ // Every character above is below U+0100: one raw byte each (the BOM `FE FF` included).+ let prev: Vec<u8> = prev.chars().map(|c| c as u32 as u8).collect();+ let before = crate::psd::parse_txt2(&prev).unwrap();+ let before_object = before.path(&["1", "1"]).and_then(E::as_array).unwrap()[0].clone();+ assert_eq!(before_object.path(&["0", "0"]).and_then(E::as_str), Some("AB\rCD\r"));+ let lens = |o: &E, key: &str| -> Vec<i64> {+ o.path(&["0", key, "0"]).and_then(E::as_array).unwrap().iter().map(|r| r.get("1").and_then(E::as_i64).unwrap()).collect()+ };+ for (text, paragraphs, styles) in+ [("Bevex\nCD", vec![6, 3], vec![2, 7]), ("AB\nCD\nEFG", vec![3, 3, 4], vec![2, 8]), ("X", vec![2], vec![2]), ("AB\nCZ", vec![3, 3], vec![2, 4])]+ {+ let t = runs_of(text, &[(text.len(), CharStyle::default())]);+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap();+ for key in [&["0"][..], &["98"], &["1", "0"], &["1", "2"]] {+ assert_eq!(out.path(key), before.path(key), "{text:?}: /{} survives", key.join(" /"));+ }+ let object = &out.path(&["1", "1"]).and_then(E::as_array).unwrap()[0];+ let engine = format!("{}\r", text.replace('\n', "\r"));+ let total = engine.encode_utf16().count() as i64;+ assert_eq!(object.path(&["0", "0"]).and_then(E::as_str), Some(engine.as_str()));+ assert_eq!(object.get("1"), before_object.get("1"), "{text:?}: the view (its frame) is kept");+ assert!(object.get("21").is_none(), "{text:?}: pen positions of the old text are dropped");+ assert_eq!(lens(object, "5"), paragraphs, "{text:?}: one paragraph run per paragraph");+ assert_eq!(lens(object, "6"), styles, "{text:?}: style runs cover the new text");+ assert_eq!(lens(object, "7"), vec![total], "{text:?}: other run arrays cover the new text");+ for r in object.path(&["0", "5", "0"]).and_then(E::as_array).unwrap() {+ assert_eq!(r.path(&["0", "0", "5", "7"]).and_then(E::as_f64), Some(1.2), "{text:?}: paragraph style survives");+ }+ for r in object.path(&["0", "6", "0"]).and_then(E::as_array).unwrap() {+ assert_eq!(r.path(&["0", "0", "6", "1"]).and_then(E::as_f64), Some(12.0), "{text:?}: the font size survives");+ }+ }+}+/// The file's style runs are only reused when they cover the text: runs of another length (or/// hostile lengths) fall back to generated runs, without panicking.#[test]