From 204c76ce36ab5e7ddf6d406074f099d3759fd8ff Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Sat, 17 Oct 2026 20:03:18 -0400 Subject: [PATCH 1/8] fix(psd): an edited type layer keeps its Txt2 object instead of a bare stub (#6968) When a type layer's text changed, build_txt2 replaced the layer's object in Photoshop's own Txt2 block with a bare `<< /0 << /0 text /6 runs >> >>`: no paragraph runs (/5), no view (/1, which names the object's frame) and none of the style keys. Photoshop 27.10 quits while opening such a file (layer_effects.psd after type.edit), as it refused stripped objects in #2374. An edited object now starts from the file's object at its slot: the text is replaced, the paragraph runs are remade one per paragraph of the new text, and every other run array of the model (style runs, ...) is cut or extended to the new length before the auto-kern modes are applied. The view and other keys are kept; only the old text's glyph pen positions (/21) are dropped. An object whose run arrays aren't shaped as Photoshop writes them still falls back to a fresh one. Test: text edited_text_keeps_the_files_txt2_object. Co-Authored-By: Claude Opus 5.5 --- crates/text/src/psd.rs | 87 ++++++++++++++++++++++++++++++++++++++-- crates/text/src/tests.rs | 50 +++++++++++++++++++++++ 2 files changed, 133 insertions(+), 4 deletions(-) diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 8c502c75af..41d65ff887 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]>) -> Vec let 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 { + 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 = 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> { + 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> { + 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 or diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 894ecf4e4f..d2aaa78a45 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 = 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 { + 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] From 198fa59c7d46dc6bef2c3b2544ab62a1b9aed92f Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:52:12 +0200 Subject: [PATCH 2/8] fix(psd): a new type layer gets a full Txt2 object and its own frame (#7698) A type layer the file's Txt2 has no object for (one added in PhotoCraft) was written as a bare stub with no view, no paragraph runs and no frame in /0 /8 /0. Photopea and Photoshop refused the file once the objects outnumbered the frames. build_txt2 now gives such a layer an object shaped like one of the file's own (refitted with edited_object from #7220), with its view naming its own frame, and pads the frame list to one per object. A stub written by an earlier save is replaced the same way, so re-saving an affected file repairs it. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/text/src/psd.rs | 77 ++++++++++++++++++++++++++++++++++++++-- crates/text/src/tests.rs | 60 +++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+), 2 deletions(-) diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 41d65ff887..5ffbebd94d 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -975,6 +975,11 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec 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(); + // Looked up once per save, not per layer: a crafted block with many objects must not cost + // a pass over all of them for every type layer. + let all_stubs = prev_objects.iter().all(is_stub); + // A template is copied once per new layer, so a large one is skipped (the stub is written). + let template = prev_objects.iter().rev().find(|o| names_one_frame(o) && fits(o, &mut { TEMPLATE_NODES }) && edited_object(o, "\r").is_some()); for (index, layer) in objects { if !(0..=MAX_TEXT_INDEX).contains(index) { continue; @@ -988,8 +993,15 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec // 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); + // A new object (#7698): a layer the file's block has no object for (a type layer added + // here) takes the shape of one of the file's own objects, refitted the same way, with its + // view naming its own frame. A bare stub beside Photoshop's objects, its slot without a + // frame in `/0 /8 /0`, made Photoshop and Photopea refuse the file. A stub an earlier save + // wrote is replaced the same way, so re-saving such a file repairs it. + let kept = kept.filter(|o| !is_stub(o) || all_stubs); + let fresh = (kept.is_none() && edited.is_none()).then(|| template.and_then(|t| new_object(t, at, &text))).flatten(); + let reuse = kept.is_some() || edited.is_some() || fresh.is_some(); + let mut object = kept.cloned().or(edited).or(fresh).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 = 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(|| { @@ -1019,6 +1031,7 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec // The outer dictionary keeps whatever the block held (`/98` version, block extras, …), and // `/1` whatever it holds beside the text objects. let mut outer = prev.clone().unwrap_or_else(|| E::Dict(vec![("98".into(), E::Dict(vec![("0".into(), E::Int(14))])), ("0".into(), E::dict())])); + pad_frames(&mut outer, slots.len()); match outer.get_mut("1") { Some(objs @ E::Dict(_)) => objs.set("1", E::Array(slots)), _ => outer.set("1", E::Dict(vec![("1".into(), E::Array(slots))])), @@ -1036,6 +1049,66 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec } } +/// The most values a `Txt2` object may hold to serve as the template for new objects. Photoshop's +/// own objects hold a few hundred (611 at most in the file from #7698). +const TEMPLATE_NODES: usize = 4096; + +/// Whether `v` holds at most `budget` values, counting down `budget` (stops at the first one over). +fn fits(v: &E, budget: &mut usize) -> bool { + let Some(left) = budget.checked_sub(1) else { return false }; + *budget = left; + match v { + E::Dict(items) => items.iter().all(|(_, x)| fits(x, budget)), + E::Array(items) => items.iter().all(|x| fits(x, budget)), + _ => true, + } +} + +/// Whether the text object `object` has a view naming one frame (`/1 /0 [ << /0 n >> ]`), as +/// Photoshop writes it. +fn names_one_frame(object: &E) -> bool { + object.path(&["1", "0"]).and_then(E::as_array).is_some_and(|f| f.len() == 1 && f.first().and_then(|x| x.get("0")).is_some()) +} + +/// A text object for the slot `at`, which the file's block has none for: the file's object +/// `template` refitted to `text` by [`edited_object`], its view now naming frame `at` and its view +/// runs (`/1 /1 /0`, one per paragraph) remade for the new paragraphs. `None` when the template +/// can't be refitted. +fn new_object(template: &E, at: usize, text: &str) -> Option { + let paragraphs: Vec = text.split_inclusive('\r').map(|p| p.encode_utf16().count()).collect(); + let mut object = edited_object(template, text)?; + let view = object.get_mut("1")?; + view.set("0", E::Array(vec![E::Dict(vec![("0".into(), E::Int(i64::try_from(at).ok()?))])])); + if let Some(runs) = view.path(&["1", "0"]).and_then(E::as_array) { + let fitted = runs_per(runs, ¶graphs)?; + view.get_mut("1")?.set("0", E::Array(fitted)); + } + Some(object) +} + +/// Whether `object` is the bare `<< /0 << /0 text /6 runs >> >>` object [`build_txt2`] writes +/// when it has nothing to take a shape from: no view, no paragraph runs. +fn is_stub(object: &E) -> bool { + let only = |v: &E, keys: &[&str]| matches!(v, E::Dict(items) if items.iter().all(|(k, _)| keys.contains(&k.as_str()))); + only(object, &["0"]) && object.get("0").is_some_and(|m| only(m, &["0", "6"])) +} + +/// Gives the block `outer` a frame (`/0 /8 /0`) for each of its `count` text objects: Photoshop +/// writes one per object, and a reader indexes them by object number. Missing frames are the +/// small point-text frame Photoshop writes (`<< /0 << /2 << /6 [ -1.0 -1.0 ] /11 << /4 -1 /7 +/// false >> >> >> >>`), never copies of a file's frame: the slot count reaches +/// [`MAX_TEXT_INDEX`], and a large frame copied that often would blow up the save. A block +/// without a frame list is left as it is. +fn pad_frames(outer: &mut E, count: usize) { + let Some(E::Array(frames)) = outer.get_mut("0").and_then(|v| v.get_mut("8")).and_then(|v| v.get_mut("0")) else { return }; + if frames.len() < count { + let kind = E::Dict(vec![("4".into(), E::Int(-1)), ("7".into(), E::Bool(false))]); + let data = E::Dict(vec![("6".into(), E::Array(vec![E::Real(-1.0), E::Real(-1.0)])), ("11".into(), kind)]); + let frame = E::Dict(vec![("0".into(), E::Dict(vec![("2".into(), data)]))]); + frames.resize(count, frame); + } +} + /// 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 diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index d2aaa78a45..4f6aad9c86 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1147,6 +1147,66 @@ fn edited_text_keeps_the_files_txt2_object() { } } +/// A type layer the file's `Txt2` has no object for (one added before the save, #7698) gets an +/// object shaped like the file's own, with a view naming its own frame and a frame in `/0 /8 /0`, +/// instead of a bare stub: Photoshop and Photopea refused the file when the frames ran out. +#[test] +fn new_text_layer_gets_a_txt2_object_and_frame() { + use crate::engine_data::Value as E; + let run = |len: usize| format!("<< /0 << /0 << /0 (\u{fe}\u{ff}) /5 << /7 1.2 >> /6 << /0 0 /1 12.0 >> >> >> /1 {len} >> "); + 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 [ {}] >> >> /1 << /0 [ << /0 0 >> ] /1 << /0 [ << /0 << /1 1 >> /1 3 >> << /0 << /1 1 >> /1 3 >> ] >> /2 [ << /99 /PC >> ] >> /21 << /1 [ 1.0 ] >> >> ] /2 << /0 7 >> >>", + run(3), + run(3), + run(6) + ); + // The same block after an earlier save wrote a bare stub for "v1.0" (the file in #7698). + let stub = "<< /0 << /0 (\u{fe}\u{ff}\0v\x001\0.\x000\0\r) /6 << /0 [ << /0 << /0 << /0 () /6 << /0 0 /11 1 >> >> >> /1 5 >> ] >> >> >> "; + let broken = prev.replace(" >> ] /2 << /0 7 >>", &format!(" >> {stub}] /2 << /0 7 >>")); + let broken: Vec = broken.chars().map(|c| c as u32 as u8).collect(); + let prev: Vec = prev.chars().map(|c| c as u32 as u8).collect(); + let before = crate::psd::parse_txt2(&prev).unwrap(); + let old = runs_of("AB\nCD", &[(5, CharStyle::default())]); + let new = runs_of("v1.0", &[(4, CharStyle::default())]); + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &old), (1, &new)], Some(&prev))).unwrap(); + let objects = out.path(&["1", "1"]).and_then(E::as_array).unwrap(); + assert_eq!(objects.len(), 2); + let kept = &before.path(&["1", "1"]).and_then(E::as_array).unwrap()[0]; + assert_eq!(objects[0].get("1"), kept.get("1"), "the file's object keeps its view"); + assert_eq!(objects[0].path(&["0", "5"]), kept.path(&["0", "5"]), "the file's object keeps its paragraphs"); + let frames = out.path(&["0", "8", "0"]).and_then(E::as_array).unwrap(); + assert_eq!(frames.len(), 2, "one frame per object"); + let object = &objects[1]; + assert_eq!(object.path(&["0", "0"]).and_then(E::as_str), Some("v1.0\r")); + assert_eq!(object.path(&["1", "0"]), Some(&E::Array(vec![E::Dict(vec![("0".into(), E::Int(1))])])), "the view names its own frame"); + assert!(object.get("21").is_none()); + let lens = + |path: &[&str]| -> Vec { object.path(path).and_then(E::as_array).unwrap().iter().map(|r| r.get("1").and_then(E::as_i64).unwrap()).collect() }; + assert_eq!(lens(&["0", "5", "0"]), vec![5]); + assert_eq!(lens(&["0", "6", "0"]), vec![5]); + assert_eq!(lens(&["1", "1", "0"]), vec![5], "view runs follow the new paragraphs"); + + // Re-saving the file with the stub repairs it: the stub is replaced like a missing object. + assert_eq!(crate::psd::parse_txt2(&broken).unwrap().path(&["1", "1"]).and_then(E::as_array).unwrap().len(), 2); + let repaired = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &old), (1, &new)], Some(&broken))).unwrap(); + assert_eq!(repaired, out, "a stub from an earlier save is replaced"); + + // No object to take the shape from: the fresh object as before, with the frames still padded. + let bare = b"\n\n/98 << /0 7 >> /0 << /8 << /0 [ << /0 1 >> ] >> >> /1 << /1 [ << >> ] >> "; + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(1, &new)], Some(bare))).unwrap(); + assert_eq!(out.path(&["1", "1"]).and_then(E::as_array).unwrap().len(), 2); + assert_eq!(out.path(&["0", "8", "0"]).and_then(E::as_array).unwrap().len(), 2); + + // An oversized object is never the template (it would be copied once per new layer). + let filler = "0 ".repeat(5000); + let big = prev.iter().map(|&b| b as char).collect::().replace("/2 [ << /99 /PC >> ]", &format!("/2 [ << /99 /PC >> ] /9 [ {filler}]")); + let big: Vec = big.chars().map(|c| c as u32 as u8).collect(); + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &old), (1, &new)], Some(&big))).unwrap(); + let object = &out.path(&["1", "1"]).and_then(E::as_array).unwrap()[1]; + assert!(object.get("1").is_none(), "no copy of an oversized template"); + assert_eq!(out.path(&["0", "8", "0"]).and_then(E::as_array).unwrap().len(), 2); +} + /// 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] From 604007490bfba2f0df84b8e0b87f8b6648229214 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:33:05 +0200 Subject: [PATCH 3/8] fix(psd): replace an earlier save's Txt2 stub also when its text is edited The stub filter applied only to the kept object, so an edited layer whose slot held a stub from an earlier save went through edited_object and kept the bare stub. The slot is now filtered before both lookups. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/text/src/psd.rs | 12 +++++++----- crates/text/src/tests.rs | 6 ++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 5ffbebd94d..2caddb0c6e 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -987,18 +987,20 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec let text = format!("{}\r", layer.text.replace('\n', "\r")); let 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())); + // A stub an earlier save wrote beside Photoshop's objects counts as no object at all, so + // it is replaced like a missing one (below) and re-saving such a file repairs it, whether + // or not the layer's text changed. + let slot = prev_objects.get(at).filter(|o| !is_stub(o) || all_stubs); + let kept = slot.filter(|o| o.get("0").and_then(|m| m.get("0")).and_then(E::as_str) == Some(text.as_str())); // 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 edited = kept.is_none().then(|| slot.and_then(|o| edited_object(o, &text))).flatten(); // A new object (#7698): a layer the file's block has no object for (a type layer added // here) takes the shape of one of the file's own objects, refitted the same way, with its // view naming its own frame. A bare stub beside Photoshop's objects, its slot without a - // frame in `/0 /8 /0`, made Photoshop and Photopea refuse the file. A stub an earlier save - // wrote is replaced the same way, so re-saving such a file repairs it. - let kept = kept.filter(|o| !is_stub(o) || all_stubs); + // frame in `/0 /8 /0`, made Photoshop and Photopea refuse the file. let fresh = (kept.is_none() && edited.is_none()).then(|| template.and_then(|t| new_object(t, at, &text))).flatten(); let reuse = kept.is_some() || edited.is_some() || fresh.is_some(); let mut object = kept.cloned().or(edited).or(fresh).unwrap_or_else(E::dict); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 4f6aad9c86..1015107843 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1190,6 +1190,12 @@ fn new_text_layer_gets_a_txt2_object_and_frame() { assert_eq!(crate::psd::parse_txt2(&broken).unwrap().path(&["1", "1"]).and_then(E::as_array).unwrap().len(), 2); let repaired = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &old), (1, &new)], Some(&broken))).unwrap(); assert_eq!(repaired, out, "a stub from an earlier save is replaced"); + // Also when the stub's layer is edited before the re-save. + let edited = runs_of("v2.0", &[(4, CharStyle::default())]); + let repaired = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &old), (1, &edited)], Some(&broken))).unwrap(); + let object = &repaired.path(&["1", "1"]).and_then(E::as_array).unwrap()[1]; + assert_eq!(object.path(&["0", "0"]).and_then(E::as_str), Some("v2.0\r")); + assert_eq!(object.path(&["1", "0"]), Some(&E::Array(vec![E::Dict(vec![("0".into(), E::Int(1))])])), "an edited stub is replaced too"); // No object to take the shape from: the fresh object as before, with the frames still padded. let bare = b"\n\n/98 << /0 7 >> /0 << /8 << /0 [ << /0 1 >> ] >> >> /1 << /1 [ << >> ] >> "; From 78cc36f24a2c78564ac2ec0a2e5f8fa9049b6fd4 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 20 Oct 2026 10:51:26 +0200 Subject: [PATCH 4/8] fix(psd): keep preserved TextIndex values when a type layer is added below them Text indices were assigned in one bottom-up pass, so a new layer took the next free number before the layers above it claimed the numbers their TySh keeps. Each of those was then renumbered onto its neighbour's Txt2 object and took its style (70 of 74 layers on the #7698 file after adding a layer at index 5). Kept numbers are now claimed first and new layers get numbers past them. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/psd_export.rs | 33 ++++++++++++++++++++------------- crates/io/tests/psd_kerning.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 13 deletions(-) diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 64a5e7073a..dd6446148a 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1582,26 +1582,33 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c ex.used_ids = used; // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — - // and new layers get the next free number. + // and new layers get numbers past every kept one. Kept numbers are claimed first: a layer + // added below others must not take a number a layer above it keeps, or each of those + // would be renumbered onto its neighbour's object and take its style (#7773). let mut used_txt = std::collections::HashSet::new(); - let mut next_txt = 0i32; ex.text_index = Default::default(); + let mut fresh = Vec::new(); for (_, _, l) in &walk { let LayerContent::Text(t) = &l.content else { continue; }; - let kept = t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)); - let index = match kept { - Some(i) if used_txt.insert(i) => i, - _ => { - while used_txt.contains(&next_txt) { - next_txt += 1; - } - used_txt.insert(next_txt); - next_txt + match t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)) { + Some(i) if used_txt.insert(i) => { + ex.text_index.insert(l.id, i); } - }; - ex.text_index.insert(l.id, index); + _ => fresh.push(l.id), + } + } + let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1); + if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { + next_txt = 0; + } + for id in fresh { + while used_txt.contains(&next_txt) { + next_txt += 1; + } + used_txt.insert(next_txt); + ex.text_index.insert(id, next_txt); } } // Progress: one unit per layer record, then the merged composite (#3389). diff --git a/crates/io/tests/psd_kerning.rs b/crates/io/tests/psd_kerning.rs index b75a6542ae..99b8535f4c 100644 --- a/crates/io/tests/psd_kerning.rs +++ b/crates/io/tests/psd_kerning.rs @@ -144,6 +144,35 @@ fn duplicate_preserved_text_indices_get_distinct_txt2_objects() { } } +/// A type layer added below preserved ones takes a number past theirs: claiming the next free +/// number on the way up renumbered every layer above it onto its neighbour's `Txt2` object +/// (#7773, 70 of 74 layers on the #7698 file). +#[test] +fn new_text_layer_below_keeps_the_preserved_text_indices() { + let mut doc = Document::new("k", photocraft_geom::Size::new(64, 32), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + for (i, text) in ["AV", "BC"].into_iter().enumerate() { + let mut t = layer(text, &[(2, Kerning::Optical, 0.0)]); + photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format()); + let raw = photocraft_text::psd::build_tysh(&t, doc.resolution_dpi, None); + t.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::set_text_index(&raw, i as i32).unwrap())); + doc.layers.push(Layer::new(text, LayerContent::Text(t))); + } + let mut t = layer("new", &[(3, Kerning::Metrics, 0.0)]); + photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format()); + doc.layers.insert(0, Layer::new("new", LayerContent::Text(t))); + let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; + let back = photocraft_io::import("k.psd", &bytes).unwrap().document; + let indices: Vec<_> = back + .layers + .iter() + .map(|l| { + let LayerContent::Text(t) = &l.content else { panic!("not text") }; + (l.name.as_str(), t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d))) + }) + .collect(); + assert_eq!(indices, [("new", Some(2)), ("AV", Some(0)), ("BC", Some(1))]); +} + /// A file-controlled `TextIndex` must not size the save: `i32::MAX` is ignored (the regenerated /// `Txt2` is sized by real text objects, never by a file's numbers) and the document still saves /// and reopens with its text. From 304f055021f3f41cbf00c71343b5a1453e877e8a Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:04:33 +0200 Subject: [PATCH 5/8] fix(psd): point a new Txt2 object's frame strike at its own frame new_object copied the template's rendered strikes, whose frame strike (/99 /F) still named the template's frame in /10. It now names the new object's frame, like the view's /0. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/text/src/psd.rs | 13 ++++++++++++- crates/text/src/tests.rs | 9 +++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 2caddb0c6e..3221f9c80d 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -1078,9 +1078,20 @@ fn names_one_frame(object: &E) -> bool { /// can't be refitted. fn new_object(template: &E, at: usize, text: &str) -> Option { let paragraphs: Vec = text.split_inclusive('\r').map(|p| p.encode_utf16().count()).collect(); + let frame = template.path(&["1", "0"]).and_then(E::as_array).and_then(|f| f.first()).and_then(|f| f.get("0")).cloned(); + let at = i64::try_from(at).ok()?; let mut object = edited_object(template, text)?; let view = object.get_mut("1")?; - view.set("0", E::Array(vec![E::Dict(vec![("0".into(), E::Int(i64::try_from(at).ok()?))])])); + view.set("0", E::Array(vec![E::Dict(vec![("0".into(), E::Int(at))])])); + // The rendered strikes' frame strike (`/F`) names the template's frame too. + if let Some(E::Array(strikes)) = view.get_mut("2") { + for s in strikes.iter_mut() { + let Some(E::Array(parts)) = s.get_mut("6") else { continue }; + for p in parts.iter_mut().filter(|p| p.get("99").and_then(E::as_str) == Some("F") && p.get("10") == frame.as_ref()) { + p.set("10", E::Int(at)); + } + } + } if let Some(runs) = view.path(&["1", "0"]).and_then(E::as_array) { let fitted = runs_per(runs, ¶graphs)?; view.get_mut("1")?.set("0", E::Array(fitted)); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 1015107843..95d8902e0b 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1155,7 +1155,7 @@ fn new_text_layer_gets_a_txt2_object_and_frame() { use crate::engine_data::Value as E; let run = |len: usize| format!("<< /0 << /0 << /0 (\u{fe}\u{ff}) /5 << /7 1.2 >> /6 << /0 0 /1 12.0 >> >> >> /1 {len} >> "); 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 [ {}] >> >> /1 << /0 [ << /0 0 >> ] /1 << /0 [ << /0 << /1 1 >> /1 3 >> << /0 << /1 1 >> /1 3 >> ] >> /2 [ << /99 /PC >> ] >> /21 << /1 [ 1.0 ] >> >> ] /2 << /0 7 >> >>", + "\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 [ {}] >> >> /1 << /0 [ << /0 0 >> ] /1 << /0 [ << /0 << /1 1 >> /1 3 >> << /0 << /1 1 >> /1 3 >> ] >> /2 [ << /99 /PC /6 [ << /99 /F /10 0 >> ] >> ] >> /21 << /1 [ 1.0 ] >> >> ] /2 << /0 7 >> >>", run(3), run(3), run(6) @@ -1180,6 +1180,11 @@ fn new_text_layer_gets_a_txt2_object_and_frame() { assert_eq!(object.path(&["0", "0"]).and_then(E::as_str), Some("v1.0\r")); assert_eq!(object.path(&["1", "0"]), Some(&E::Array(vec![E::Dict(vec![("0".into(), E::Int(1))])])), "the view names its own frame"); assert!(object.get("21").is_none()); + assert_eq!( + object.path(&["1", "2"]).and_then(E::as_array).and_then(|s| s[0].get("6")).and_then(E::as_array).and_then(|f| f[0].get("10")), + Some(&E::Int(1)), + "the frame strike names its own frame" + ); let lens = |path: &[&str]| -> Vec { object.path(path).and_then(E::as_array).unwrap().iter().map(|r| r.get("1").and_then(E::as_i64).unwrap()).collect() }; assert_eq!(lens(&["0", "5", "0"]), vec![5]); @@ -1205,7 +1210,7 @@ fn new_text_layer_gets_a_txt2_object_and_frame() { // An oversized object is never the template (it would be copied once per new layer). let filler = "0 ".repeat(5000); - let big = prev.iter().map(|&b| b as char).collect::().replace("/2 [ << /99 /PC >> ]", &format!("/2 [ << /99 /PC >> ] /9 [ {filler}]")); + let big = prev.iter().map(|&b| b as char).collect::().replace("/2 [ << /99 /PC", &format!("/9 [ {filler}] /2 [ << /99 /PC")); let big: Vec = big.chars().map(|c| c as u32 as u8).collect(); let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &old), (1, &new)], Some(&big))).unwrap(); let object = &out.path(&["1", "1"]).and_then(E::as_array).unwrap()[1]; From 760109e23cd4f996aed591e60c88fffd639668bb Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:57:10 +0200 Subject: [PATCH 6/8] fix(psd): give a new Txt2 object its own style and a number past the file's objects A new object kept the template's style runs, and PhotoCraft's reader takes font features from Txt2, so a new type layer came back with the template layer's features (salt, ss01). Its style runs are now generated like the stub's; only the template's structure is copied. New type layers were numbered past the kept TextIndex values only, so after deleting the layer with the highest index a new layer landed on its object and took its style. They are now numbered past the file's Txt2 objects too. txt2_extras_survive_a_resave_of_unchanged_text now gives its layer the TySh index a file's layer has; without one the layer is new and no longer lands on object 0. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/psd_export.rs | 11 ++++--- crates/io/tests/psd_kerning.rs | 58 ++++++++++++++++++++++++++++++++++ crates/text/src/psd.rs | 10 +++++- 3 files changed, 74 insertions(+), 5 deletions(-) diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index dd6446148a..4350ffd06a 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1582,9 +1582,10 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c ex.used_ids = used; // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — - // and new layers get numbers past every kept one. Kept numbers are claimed first: a layer - // added below others must not take a number a layer above it keeps, or each of those - // would be renumbered onto its neighbour's object and take its style (#7773). + // and new layers get numbers past every kept one and every object in the file's `Txt2`. + // Kept numbers are claimed first: a layer added below others must not take a number a + // layer above it keeps, or each of those would be renumbered onto its neighbour's object + // and take its style (#7773); nor may it land on a deleted layer's object. let mut used_txt = std::collections::HashSet::new(); ex.text_index = Default::default(); let mut fresh = Vec::new(); @@ -1599,7 +1600,9 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c _ => fresh.push(l.id), } } - let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1); + let objects = + doc.metadata.psd_global_blocks.iter().find(|(_, key, _)| key == b"Txt2").map_or(0, |(_, _, d)| photocraft_text::psd::txt2_object_count(d)); + let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1).max(i32::try_from(objects).unwrap_or(i32::MAX)); if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { next_txt = 0; } diff --git a/crates/io/tests/psd_kerning.rs b/crates/io/tests/psd_kerning.rs index 99b8535f4c..9c5e3dd8cd 100644 --- a/crates/io/tests/psd_kerning.rs +++ b/crates/io/tests/psd_kerning.rs @@ -173,6 +173,61 @@ fn new_text_layer_below_keeps_the_preserved_text_indices() { assert_eq!(indices, [("new", Some(2)), ("AV", Some(0)), ("BC", Some(1))]); } +/// A Photoshop-shaped `Txt2` block: one object per `(text, style keys)` pair, each with its view +/// naming its own frame. +fn photoshop_txt2(objects: &[(&str, &str)]) -> Vec { + let bom = "\u{fe}\u{ff}"; + let frame = "<< /0 << /2 << /2 [ 1.0 0.0 0.0 1.0 5.0 6.0 ] >> >> >> "; + let mut frames = String::new(); + let mut body = String::new(); + for (i, (text, style)) in objects.iter().enumerate() { + let utf16: String = format!("{text}\r").chars().flat_map(|c| ['\0', c]).collect(); + let len = text.len() + 1; + frames.push_str(frame); + body.push_str(&format!( + "<< /0 << /0 ({bom}{utf16}) /5 << /0 [ << /0 << /0 << /0 ({bom}) /5 << /7 1.2 >> >> >> /1 {len} >> ] >> /6 << /0 [ << /0 << /0 << /0 ({bom}) /6 << /0 0 /11 1 {style} >> >> >> /1 {len} >> ] >> >> /1 << /0 [ << /0 {i} >> ] /1 << /0 [ << /0 << /1 1 >> /1 {len} >> ] >> /2 [ << /99 /PC /6 [ << /99 /F /10 {i} >> ] >> ] >> >> " + )); + } + format!("\n\n/98 << /0 7 >> /0 << /8 << /0 [ {frames}] >> >> /1 << /0 << /0 1 >> /1 [ {body}] /2 << /0 7 >> >>").chars().map(|c| c as u32 as u8).collect() +} + +/// The preserved type layers "AV" (`TextIndex` 0) and "BC" (1) of a Photoshop file whose `Txt2` +/// holds `objects`, plus a new type layer "Hi" on top, saved and reopened: "Hi"'s index and the +/// font features it comes back with. +fn add_layer_beside(objects: &[(&str, &str)]) -> (Option, Vec) { + let mut doc = Document::new("k", photocraft_geom::Size::new(64, 32), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + for (i, text) in ["AV", "BC"].into_iter().enumerate() { + let mut t = layer(text, &[(2, Kerning::Metrics, 0.0)]); + photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format()); + let raw = photocraft_text::psd::build_tysh(&t, doc.resolution_dpi, None); + t.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::set_text_index(&raw, i as i32).unwrap())); + doc.layers.push(Layer::new(text, LayerContent::Text(t))); + } + doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Txt2", std::sync::Arc::new(photoshop_txt2(objects)))]; + let mut t = layer("Hi", &[(2, Kerning::Metrics, 0.0)]); + photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format()); + doc.layers.push(Layer::new("Hi", LayerContent::Text(t))); + let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; + let back = photocraft_io::import("k.psd", &bytes).unwrap().document; + let LayerContent::Text(t) = &back.layers[2].content else { panic!("not text") }; + let features = t.char_runs().iter().flat_map(|r| r.style.features.iter().map(|f| f.tag.clone())).collect(); + (t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)), features) +} + +/// A new type layer takes the structure of one of the file's objects but not its style: the +/// template's style runs carried its font features (here `salt` and `ss01`) into the new layer. +#[test] +fn new_text_layer_takes_no_style_from_the_txt2_template() { + assert_eq!(add_layer_beside(&[("AV", ""), ("BC", "/28 true /85 1")]), (Some(2), vec![])); +} + +/// A new type layer is numbered past the file's `Txt2` objects, not only past the kept indices: +/// the object of a deleted type layer ("Gone", index 2) is not reused with its style. +#[test] +fn new_text_layer_skips_a_deleted_layers_txt2_object() { + assert_eq!(add_layer_beside(&[("AV", ""), ("BC", ""), ("Gone", "/28 true")]), (Some(3), vec![])); +} + /// A file-controlled `TextIndex` must not size the save: `i32::MAX` is ignored (the regenerated /// `Txt2` is sized by real text objects, never by a file's numbers) and the document still saves /// and reopens with its text. @@ -215,6 +270,9 @@ fn txt2_extras_survive_a_resave_of_unchanged_text() { let mut doc = Document::new("k", photocraft_geom::Size::new(64, 32), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); let mut r = t.clone(); photocraft_text::TextEngine::new().render_layer(&mut r, doc.resolution_dpi, doc.pixel_format()); + // The file's layer: its `TySh` names object 0. + let raw = photocraft_text::psd::build_tysh(&r, doc.resolution_dpi, None); + r.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::set_text_index(&raw, 0).unwrap())); doc.layers.push(Layer::new("kept", LayerContent::Text(r))); doc.metadata.psd_global_blocks.push((*b"8BIM", *b"Txt2", std::sync::Arc::new(prev.clone()))); let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 3221f9c80d..828a50a0a2 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -1002,7 +1002,8 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec // view naming its own frame. A bare stub beside Photoshop's objects, its slot without a // frame in `/0 /8 /0`, made Photoshop and Photopea refuse the file. let fresh = (kept.is_none() && edited.is_none()).then(|| template.and_then(|t| new_object(t, at, &text))).flatten(); - let reuse = kept.is_some() || edited.is_some() || fresh.is_some(); + // A new object keeps the template's structure, not its style: its style runs are generated. + let reuse = kept.is_some() || edited.is_some(); let mut object = kept.cloned().or(edited).or(fresh).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 = reuse.then(|| model.path(&["6", "0"]).and_then(E::as_array)).flatten().and_then(|runs| with_modes(runs, &modes)); @@ -1250,6 +1251,13 @@ pub fn text_index(tysh: &[u8]) -> Option { } } +/// How many text objects the document `Txt2` block `data` holds (`/1 /1`), named by a layer or +/// not; 0 when it doesn't parse. PSD export numbers new type layers past them, so a new layer +/// never lands on a deleted layer's object. +pub fn txt2_object_count(data: &[u8]) -> usize { + parse_txt2(data).and_then(|t| t.path(&["1", "1"]).and_then(E::as_array).map(<[E]>::len)).unwrap_or(0) +} + /// Rewrites a `TySh`'s `TextIndex`: the layer's text-object number in the document's `Txt2` /// block ([`build_txt2`] writes them in this order). `None` when `tysh` doesn't parse. pub fn set_text_index(tysh: &[u8], index: i32) -> Option> { From 20c9103148e3b7a6a2dd67ef4529655cce0c7e64 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 20 Oct 2026 19:48:40 +0200 Subject: [PATCH 7/8] fix(psd): write complete Txt2 style runs from the layer, number only file indices as kept Photoshop reads the character style from Txt2 and quit on the bare run (`/0 0 /11 mode`) that new objects got. New and edited objects now get one style run per character run, built on one of the object's own runs with every key kept, and font, size, faux styles, leading, scales, tracking, fill colour, OpenType keys and auto-kern mode set from the layer. A font the block's font list lacks is appended to it. Edited objects therefore no longer keep the old text's features by position. build_tysh no longer writes TextIndex 0 for a layer without one: the export took it as a kept number, so a Type tool layer landed on object 0 (a deleted layer's, or the one of a layer above it). set_text_index puts a missing TextIndex right before EngineData, where Photoshop writes it. pad_frames pads to at most MAX_TEXT_INDEX + 1 frames. edited_text_keeps_the_files_txt2_object (#7220) now expects style runs that follow the layer's runs and size. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/psd_export.rs | 4 +- crates/io/tests/psd_kerning.rs | 95 ++++++++++++++++++---- crates/text/src/psd.rs | 140 ++++++++++++++++++++++++++++----- crates/text/src/tests.rs | 20 ++++- 4 files changed, 220 insertions(+), 39 deletions(-) diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 4350ffd06a..419f9156f7 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1740,8 +1740,8 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c // writes its empty `<< /0 << >> >>` stub — readers such as Photopea reject it (#3514). Keep the // block when the file had one (round-trip its pen positions/extras) or a layer is Optical (the // one mode EngineData can't carry; #1348). - let txt2 = - (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)).then(|| photocraft_text::psd::build_txt2(&text_layers, previous.as_deref())); + 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)); for (sig, key, data) in preserved { if txt2.is_some() && key == *b"Txt2" { continue; diff --git a/crates/io/tests/psd_kerning.rs b/crates/io/tests/psd_kerning.rs index 9c5e3dd8cd..6eeebc43b4 100644 --- a/crates/io/tests/psd_kerning.rs +++ b/crates/io/tests/psd_kerning.rs @@ -185,47 +185,108 @@ fn photoshop_txt2(objects: &[(&str, &str)]) -> Vec { let len = text.len() + 1; frames.push_str(frame); body.push_str(&format!( - "<< /0 << /0 ({bom}{utf16}) /5 << /0 [ << /0 << /0 << /0 ({bom}) /5 << /7 1.2 >> >> >> /1 {len} >> ] >> /6 << /0 [ << /0 << /0 << /0 ({bom}) /6 << /0 0 /11 1 {style} >> >> >> /1 {len} >> ] >> >> /1 << /0 [ << /0 {i} >> ] /1 << /0 [ << /0 << /1 1 >> /1 {len} >> ] >> /2 [ << /99 /PC /6 [ << /99 /F /10 {i} >> ] >> ] >> >> " + "<< /0 << /0 ({bom}{utf16}) /5 << /0 [ << /0 << /0 << /0 ({bom}) /5 << /7 1.2 >> >> >> /1 {len} >> ] >> /6 << /0 [ << /0 << /0 << /0 ({bom}) /6 << /0 0 /1 12.0 /11 1 /53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 0.0 ] >> >> {style} >> >> >> /1 {len} >> ] >> >> /1 << /0 [ << /0 {i} >> ] /1 << /0 [ << /0 << /1 1 >> /1 {len} >> ] >> /2 [ << /99 /PC /6 [ << /99 /F /10 {i} >> ] >> ] >> >> " )); } - format!("\n\n/98 << /0 7 >> /0 << /8 << /0 [ {frames}] >> >> /1 << /0 << /0 1 >> /1 [ {body}] /2 << /0 7 >> >>").chars().map(|c| c as u32 as u8).collect() + let font: String = "MyriadPro-Regular".chars().flat_map(|c| ['\0', c]).collect(); + format!("\n\n/98 << /0 7 >> /0 << /1 << /0 [ << /0 << /99 /CoolTypeFont /0 << /0 ({bom}{font}) /2 1 >> >> >> ] >> /8 << /0 [ {frames}] >> >> /1 << /0 << /0 1 >> /1 [ {body}] /2 << /0 7 >> >>").chars().map(|c| c as u32 as u8).collect() } -/// The preserved type layers "AV" (`TextIndex` 0) and "BC" (1) of a Photoshop file whose `Txt2` -/// holds `objects`, plus a new type layer "Hi" on top, saved and reopened: "Hi"'s index and the -/// font features it comes back with. -fn add_layer_beside(objects: &[(&str, &str)]) -> (Option, Vec) { +/// A Photoshop file whose `Txt2` holds `objects` and whose type layers are `kept` (text and +/// `TextIndex`, bottom first), with a type layer "Hi" made the way the Type tool makes one +/// (`build_tysh`, no index of its own) inserted at `at`, saved and reopened: each layer's +/// index and font features (but `calt`, on by default and written on as Photoshop does), and +/// "Hi"'s style run in the saved `Txt2`. +fn add_type_layer(objects: &[(&str, &str)], kept: &[(&str, i32)], at: usize) -> (Vec<(String, Option, Vec)>, E) { let mut doc = Document::new("k", photocraft_geom::Size::new(64, 32), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); - for (i, text) in ["AV", "BC"].into_iter().enumerate() { - let mut t = layer(text, &[(2, Kerning::Metrics, 0.0)]); + for (text, index) in kept { + let mut t = layer(text, &[(text.len(), Kerning::Metrics, 0.0)]); photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format()); let raw = photocraft_text::psd::build_tysh(&t, doc.resolution_dpi, None); - t.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::set_text_index(&raw, i as i32).unwrap())); - doc.layers.push(Layer::new(text, LayerContent::Text(t))); + t.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::set_text_index(&raw, *index).unwrap())); + doc.layers.push(Layer::new(*text, LayerContent::Text(t))); } doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Txt2", std::sync::Arc::new(photoshop_txt2(objects)))]; let mut t = layer("Hi", &[(2, Kerning::Metrics, 0.0)]); + t.runs[0].style.size_pt = 30.0; photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format()); - doc.layers.push(Layer::new("Hi", LayerContent::Text(t))); + t.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::build_tysh(&t, doc.resolution_dpi, None))); + doc.layers.insert(at, Layer::new("Hi", LayerContent::Text(t))); let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; + let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)).unwrap(); let back = photocraft_io::import("k.psd", &bytes).unwrap().document; - let LayerContent::Text(t) = &back.layers[2].content else { panic!("not text") }; - let features = t.char_runs().iter().flat_map(|r| r.style.features.iter().map(|f| f.tag.clone())).collect(); - (t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)), features) + let layers: Vec<_> = back + .layers + .iter() + .map(|l| { + let LayerContent::Text(t) = &l.content else { panic!("not text") }; + let index = t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)); + (l.name.clone(), index, t.char_runs().iter().flat_map(|r| r.style.features.iter().filter(|f| f.tag != "calt").map(|f| f.tag.clone())).collect()) + }) + .collect(); + let hi = layers.iter().find(|l| l.0 == "Hi").and_then(|l| l.1).unwrap() as usize; + let run = txt2.path(&["1", "1"]).and_then(E::as_array).unwrap()[hi].path(&["0", "6", "0"]).and_then(E::as_array).unwrap()[0].clone(); + (layers, run) +} + +/// The layer `name` in `add_type_layer`'s result. +fn named<'a>(layers: &'a [(String, Option, Vec)], name: &str) -> &'a (String, Option, Vec) { + layers.iter().find(|l| l.0 == name).unwrap() } /// A new type layer takes the structure of one of the file's objects but not its style: the /// template's style runs carried its font features (here `salt` and `ss01`) into the new layer. +/// Its style run is the template's complete one (Photoshop quit on a run holding only the +/// auto-kern mode, and reads the character style from it) with the layer's own size. #[test] fn new_text_layer_takes_no_style_from_the_txt2_template() { - assert_eq!(add_layer_beside(&[("AV", ""), ("BC", "/28 true /85 1")]), (Some(2), vec![])); + let (layers, run) = add_type_layer(&[("AV", ""), ("BC", "/28 true /85 1")], &[("AV", 0), ("BC", 1)], 2); + assert_eq!(named(&layers, "Hi").1..=named(&layers, "Hi").1, Some(2)..=Some(2)); + assert!(named(&layers, "Hi").2.is_empty(), "{layers:?}"); + let style = run.path(&["0", "0", "6"]).unwrap(); + assert_eq!(style.get("1").and_then(E::as_f64), Some(30.0), "the layer's own size"); + assert_eq!(style.get("28"), Some(&E::Bool(false))); + assert_eq!(style.path(&["53", "0", "0"]), Some(&E::Int(1)), "the layer's fill colour, RGB"); + assert_eq!(style.get("11"), Some(&E::Int(1))); } /// A new type layer is numbered past the file's `Txt2` objects, not only past the kept indices: -/// the object of a deleted type layer ("Gone", index 2) is not reused with its style. +/// a deleted type layer's object ("Gone") is not reused with its style, whether it held the +/// highest index or index 0 (the Type tool's layer used to bring a `TextIndex` 0 of its own). #[test] fn new_text_layer_skips_a_deleted_layers_txt2_object() { - assert_eq!(add_layer_beside(&[("AV", ""), ("BC", ""), ("Gone", "/28 true")]), (Some(3), vec![])); + let (layers, _) = add_type_layer(&[("AV", ""), ("BC", ""), ("Gone", "/28 true")], &[("AV", 0), ("BC", 1)], 2); + assert_eq!((named(&layers, "Hi").1, named(&layers, "Hi").2.is_empty()), (Some(3), true)); + let (layers, _) = add_type_layer(&[("Gone", "/28 true"), ("AV", ""), ("BC", "")], &[("AV", 1), ("BC", 2)], 2); + assert_eq!((named(&layers, "Hi").1, named(&layers, "Hi").2.is_empty()), (Some(3), true)); +} + +/// A type layer added below the one holding index 0 neither takes that index nor its style. +#[test] +fn new_text_layer_at_the_bottom_keeps_index_0_where_it_was() { + let (layers, _) = add_type_layer(&[("AV", "/28 true"), ("BC", "")], &[("AV", 0), ("BC", 1)], 0); + assert_eq!(named(&layers, "AV").1, Some(0)); + assert_eq!(named(&layers, "AV").2, ["salt"]); + assert_eq!((named(&layers, "Hi").1, named(&layers, "Hi").2.is_empty()), (Some(2), true)); +} + +/// An edited object takes the layer's style, not the old text's: "Hello world" with Stylistic +/// Alternates on "Hello " edited to "world" without them comes back without `salt`. +#[test] +fn edited_text_layer_takes_its_own_style_runs() { + let mut doc = Document::new("k", photocraft_geom::Size::new(64, 32), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + let mut t = layer("world", &[(5, Kerning::Metrics, 0.0)]); + photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format()); + let raw = photocraft_text::psd::build_tysh(&t, doc.resolution_dpi, None); + t.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::set_text_index(&raw, 0).unwrap())); + doc.layers.push(Layer::new("edited", LayerContent::Text(t))); + doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Txt2", std::sync::Arc::new(photoshop_txt2(&[("Hello world", "/28 true")])))]; + let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; + let back = photocraft_io::import("k.psd", &bytes).unwrap().document; + let LayerContent::Text(t) = &back.layers[0].content else { panic!("not text") }; + assert_eq!(t.text, "world"); + assert!(t.char_runs().iter().all(|r| r.style.features.iter().all(|f| f.tag == "calt")), "the old text's salt came back"); } /// A file-controlled `TextIndex` must not size the save: `i32::MAX` is ignored (the regenerated diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 828a50a0a2..6d8fd8f454 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -820,21 +820,21 @@ pub const OPENTYPE_KEYS: [(&str, &str); 8] = [ ("Fractions", "frac"), ]; -pub(crate) fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E { - let c = &s.color; - let values = match c.mode { - ColorMode::Cmyk => vec![real(c.alpha), real(c.c[0]), real(c.c[1]), real(c.c[2]), real(c.c[3])], - ColorMode::Grayscale => vec![real(c.alpha), real(c.c[0])], +/// A fill colour as EngineData and `Txt2` store it: the colour type (0 gray, 1 RGB, 2 CMYK) and +/// its values, alpha first. +fn fill_color(c: &Color) -> (i64, Vec) { + match c.mode { + ColorMode::Cmyk => (2, vec![real(c.alpha), real(c.c[0]), real(c.c[1]), real(c.c[2]), real(c.c[3])]), + ColorMode::Grayscale => (0, vec![real(c.alpha), real(c.c[0])]), _ => { let [r, g, b] = c.to_rgb(); - vec![real(c.alpha), real(r), real(g), real(b)] + (1, vec![real(c.alpha), real(r), real(g), real(b)]) } - }; - let color_type = match c.mode { - ColorMode::Cmyk => 2, - ColorMode::Grayscale => 0, - _ => 1, - }; + } +} + +pub(crate) fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E { + let (color_type, values) = fill_color(&s.color); let mut opentype: Vec<(String, E)> = OPENTYPE_KEYS .iter() .filter(|(_, tag)| s.features.iter().any(|f| f.tag == *tag && f.value > 0)) @@ -938,6 +938,88 @@ fn txt2_mode_runs(layer: &TextLayer) -> Vec<(i64, usize)> { out } +/// `Txt2` style runs for `layer`, one per character run: `base` (one of the file's style runs, +/// `<< /0 << /0 << /6 style >> >> /1 length >>`, every key Photoshop wrote) with its style set +/// from the run's own: font (`/0`, an index into `fonts`, the block's `/0 /1 /0` font list, which +/// a missing font is appended to), size (`/1`), faux bold and italic, leading, scales and tracking +/// (`/2`–`/8`, EngineData's order), fill colour (`/53`), the OpenType keys and the auto-kern mode +/// (`/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. +fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec, dpi: f32) -> Option> { + if !matches!(base.path(&["0", "0", "6"]), Some(E::Dict(_))) { + return None; + } + let k = if dpi.is_finite() && dpi > 0.0 { dpi / 72.0 } else { 1.0 }; + let runs = layer.char_runs(); + let ed_text = format!("{}\r", layer.text.replace('\n', "\r")); + let mut spans: Vec<(usize, i64)> = Vec::new(); + let (mut ri, mut run_end) = (0usize, runs.first().map_or(0, |r| r.len)); + for (b, ch) in ed_text.char_indices() { + while b >= run_end && ri + 1 < runs.len() { + ri += 1; + run_end = run_end.saturating_add(runs.get(ri).map_or(0, |r| r.len)); + } + let n = ch.len_utf16() as i64; + match spans.last_mut() { + Some(last) if last.0 == ri => last.1 += n, + _ => spans.push((ri, n)), + } + } + let default = CharStyle::default(); + let mut out = Vec::with_capacity(spans.len()); + for (ri, n) in spans { + let s = runs.get(ri).map_or(&default, |r| &r.style); + let font = txt2_font(fonts, &postscript_for(s)); + let mut run = base.clone(); + let style = run.get_mut("0")?.get_mut("0")?.get_mut("6")?; + if let Some(font) = font { + style.set("0", E::Int(font)); + } + style.set("1", real(s.size_pt * k)); + style.set("2", E::Bool(s.faux_bold)); + style.set("3", E::Bool(s.faux_italic)); + style.set("4", E::Bool(s.leading_pt.is_none())); + style.set("5", real(s.leading_pt.unwrap_or(0.0) * k)); + style.set("6", real(s.horizontal_scale)); + style.set("7", real(s.vertical_scale)); + style.set("8", E::Int(s.tracking.round() as i64)); + if let Some(paint @ E::Dict(_)) = style.get_mut("53").and_then(|p| p.get_mut("0")) { + let (kind, values) = fill_color(&s.color); + paint.set("0", E::Int(kind)); + paint.set("1", E::Array(values)); + } + let feature = |tag: &str| s.features.iter().find(|f| f.tag == tag).map(|f| f.value > 0); + for (key, tag) in TXT2_FEATURES { + style.set(key, E::Bool(feature(tag).unwrap_or(tag == "calt"))); + } + let sets = (0..20).filter(|n| feature(&format!("ss{:02}", n + 1)) == Some(true)).fold(0i64, |m, n| m | 1 << n); + style.set(TXT2_STYLISTIC_SETS, E::Int(sets)); + style.set("11", E::Int(txt2_mode(s))); + run.set("1", E::Int(n)); + out.push(run); + } + Some(out) +} + +/// The index of the PostScript font `name` in a `Txt2` font list (`<< /0 << /99 /CoolTypeFont +/// /0 << /0 name /2 type >> >> >>` entries), appending it (shaped like the list's first entry) +/// when missing. `None` for an empty list: there is no entry to shape a new one on. +fn txt2_font(fonts: &mut Vec, name: &str) -> Option { + let named = |f: &E| f.path(&["0", "0", "0"]).and_then(E::as_str) == Some(name); + if let Some(i) = fonts.iter().position(named) { + return i64::try_from(i).ok(); + } + let mut entry = fonts.first()?.clone(); + let font = entry.get_mut("0")?.get_mut("0")?; + let kind = font.get("2").cloned(); + *font = E::Dict(vec![("0".into(), E::String(name.to_string()))]); + if let Some(kind) = kind { + font.set("2", kind); + } + fonts.push(entry); + i64::try_from(fonts.len() - 1).ok() +} + /// The highest text-object number honoured here (`TextIndex`, and the slot array [`build_txt2`] /// sizes). PSD text objects are numbered densely from 0; a crafted file can name object /// `i32::MAX`, and sizing the array by it would make every save allocate gigabytes. @@ -972,9 +1054,17 @@ pub fn needs_txt2(objects: &[(i32, &TextLayer)]) -> bool { /// 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) +} + +/// [`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 { 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(); + let mut fonts: Vec = prev.as_ref().and_then(|p| p.path(&["0", "1", "0"]).and_then(E::as_array)).map(<[E]>::to_vec).unwrap_or_default(); + let fonts_before = fonts.len(); // Looked up once per save, not per layer: a crafted block with many objects must not cost // a pass over all of them for every type layer. let all_stubs = prev_objects.iter().all(is_stub); @@ -1002,12 +1092,19 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec // view naming its own frame. A bare stub beside Photoshop's objects, its slot without a // frame in `/0 /8 /0`, made Photoshop and Photopea refuse the file. let fresh = (kept.is_none() && edited.is_none()).then(|| template.and_then(|t| new_object(t, at, &text))).flatten(); - // A new object keeps the template's structure, not its style: its style runs are generated. let reuse = kept.is_some() || edited.is_some(); + let unchanged = kept.is_some(); let mut object = kept.cloned().or(edited).or(fresh).unwrap_or_else(E::dict); let mut model = object.get("0").cloned().filter(|m| matches!(m, E::Dict(_))).unwrap_or_else(E::dict); + // A new or edited object takes the layer's own style: Photoshop reads the character style + // 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. + let styled = (!unchanged && !is_stub(&object)) + .then(|| model.path(&["6", "0"]).and_then(E::as_array).and_then(<[E]>::first).cloned()) + .flatten() + .and_then(|base| txt2_style_runs(layer, &base, &mut fonts, dpi)); 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(|| { + let runs = styled.or(file_runs).unwrap_or_else(|| { modes .iter() .map(|&(mode, len)| { @@ -1035,6 +1132,11 @@ pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec // `/1` whatever it holds beside the text objects. let mut outer = prev.clone().unwrap_or_else(|| E::Dict(vec![("98".into(), E::Dict(vec![("0".into(), E::Int(14))])), ("0".into(), E::dict())])); pad_frames(&mut outer, slots.len()); + if fonts.len() != fonts_before + && let Some(list @ E::Dict(_)) = outer.get_mut("0").and_then(|v| v.get_mut("1")) + { + list.set("0", E::Array(fonts)); + } match outer.get_mut("1") { Some(objs @ E::Dict(_)) => objs.set("1", E::Array(slots)), _ => outer.set("1", E::Dict(vec![("1".into(), E::Array(slots))])), @@ -1115,6 +1217,7 @@ fn is_stub(object: &E) -> bool { /// without a frame list is left as it is. fn pad_frames(outer: &mut E, count: usize) { let Some(E::Array(frames)) = outer.get_mut("0").and_then(|v| v.get_mut("8")).and_then(|v| v.get_mut("0")) else { return }; + let count = count.min(MAX_TEXT_INDEX as usize + 1); if frames.len() < count { let kind = E::Dict(vec![("4".into(), E::Int(-1)), ("7".into(), E::Bool(false))]); let data = E::Dict(vec![("6".into(), E::Array(vec![E::Real(-1.0), E::Real(-1.0)])), ("11".into(), kind)]); @@ -1264,7 +1367,11 @@ pub fn set_text_index(tysh: &[u8], index: i32) -> Option> { let mut t = parse_tysh(tysh)?; match t.text.items.iter_mut().find(|(k, _)| k.is("TextIndex")) { Some(e) => e.1 = D::Integer(index), - None => t.text.items.push((Id::new("TextIndex"), D::Integer(index))), + // Where Photoshop writes it: right before `EngineData`. + None => { + let at = t.text.items.iter().position(|(k, _)| k.is("EngineData")).unwrap_or(t.text.items.len()); + t.text.items.insert(at, (Id::new("TextIndex"), D::Integer(index))); + } } Some(write_tysh(&t)) } @@ -1495,9 +1602,6 @@ pub fn build_tysh(layer: &TextLayer, dpi: f32, ink: Option<[f32; 4]>) -> Vec }; set(&mut text, "bounds", rect("bounds")); set(&mut text, "boundingBox", rect("boundingBox")); - if text.get("TextIndex").is_none() { - set(&mut text, "TextIndex", D::Integer(0)); - } set(&mut text, "EngineData", D::RawData(ed::write(&e))); let warp = match (&layer.warp, old.as_ref().and_then(|o| o.warp.clone())) { (Some(w), _) => Some( diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 95d8902e0b..5c18460b03 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1122,7 +1122,7 @@ fn edited_text_keeps_the_files_txt2_object() { 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])] + [("Bevex\nCD", vec![6, 3], vec![9]), ("AB\nCD\nEFG", vec![3, 3, 4], vec![10]), ("X", vec![2], vec![2]), ("AB\nCZ", vec![3, 3], vec![6])] { let t = runs_of(text, &[(text.len(), CharStyle::default())]); let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap(); @@ -1136,13 +1136,16 @@ fn edited_text_keeps_the_files_txt2_object() { 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"); + // Photoshop reads the character style from these runs: they follow the layer's own runs + // (one here), built on the file's first run. 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"); + assert_eq!(r.path(&["0", "0", "6", "1"]).and_then(E::as_f64), Some(f64::from(CharStyle::default().size_pt)), "{text:?}: the layer's font size"); + assert_eq!(r.path(&["0", "0", "5", "7"]).and_then(E::as_f64), Some(1.2), "{text:?}: the file's run keeps its other keys"); } } } @@ -1218,6 +1221,19 @@ fn new_text_layer_gets_a_txt2_object_and_frame() { assert_eq!(out.path(&["0", "8", "0"]).and_then(E::as_array).unwrap().len(), 2); } +/// The frame padding is bounded like the slots a layer can name: a crafted block of many empty +/// objects and no frames must not make the save write a frame for each of them. +#[test] +fn txt2_frame_padding_is_bounded() { + use crate::engine_data::Value as E; + let objects = "<< >> ".repeat(70_000); + let prev = format!("\n\n/98 << /0 7 >> /0 << /8 << /0 [ ] >> >> /1 << /1 [ {objects}] >> "); + let t = runs_of("AV", &[(2, CharStyle::default())]); + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(prev.as_bytes()))).unwrap(); + let frames = out.path(&["0", "8", "0"]).and_then(E::as_array).unwrap().len(); + assert_eq!(frames, crate::psd::MAX_TEXT_INDEX as usize + 1); +} + /// 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] From e86e6910ae58d828cdc7b50dbb64dcb02662d50c Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 20 Oct 2026 20:07:39 +0200 Subject: [PATCH 8/8] fix(psd): bound the base style run a save copies per run The base run comes from the file and is cloned once per character run, so it now has to fit the template node budget, and each font is looked up once per name. Also names the reopened-layer tuple in psd_kerning for clippy::type_complexity. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/tests/psd_kerning.rs | 7 +++++-- crates/text/src/psd.rs | 8 +++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/io/tests/psd_kerning.rs b/crates/io/tests/psd_kerning.rs index 6eeebc43b4..ad492fce25 100644 --- a/crates/io/tests/psd_kerning.rs +++ b/crates/io/tests/psd_kerning.rs @@ -192,12 +192,15 @@ fn photoshop_txt2(objects: &[(&str, &str)]) -> Vec { format!("\n\n/98 << /0 7 >> /0 << /1 << /0 [ << /0 << /99 /CoolTypeFont /0 << /0 ({bom}{font}) /2 1 >> >> >> ] >> /8 << /0 [ {frames}] >> >> /1 << /0 << /0 1 >> /1 [ {body}] /2 << /0 7 >> >>").chars().map(|c| c as u32 as u8).collect() } +/// A reopened type layer: its name, `TextIndex` and font features. +type Reopened = (String, Option, Vec); + /// A Photoshop file whose `Txt2` holds `objects` and whose type layers are `kept` (text and /// `TextIndex`, bottom first), with a type layer "Hi" made the way the Type tool makes one /// (`build_tysh`, no index of its own) inserted at `at`, saved and reopened: each layer's /// index and font features (but `calt`, on by default and written on as Photoshop does), and /// "Hi"'s style run in the saved `Txt2`. -fn add_type_layer(objects: &[(&str, &str)], kept: &[(&str, i32)], at: usize) -> (Vec<(String, Option, Vec)>, E) { +fn add_type_layer(objects: &[(&str, &str)], kept: &[(&str, i32)], at: usize) -> (Vec, E) { let mut doc = Document::new("k", photocraft_geom::Size::new(64, 32), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); for (text, index) in kept { let mut t = layer(text, &[(text.len(), Kerning::Metrics, 0.0)]); @@ -231,7 +234,7 @@ fn add_type_layer(objects: &[(&str, &str)], kept: &[(&str, i32)], at: usize) -> } /// The layer `name` in `add_type_layer`'s result. -fn named<'a>(layers: &'a [(String, Option, Vec)], name: &str) -> &'a (String, Option, Vec) { +fn named<'a>(layers: &'a [Reopened], name: &str) -> &'a Reopened { layers.iter().find(|l| l.0 == name).unwrap() } diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 6d8fd8f454..aaa901eb2d 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -944,9 +944,10 @@ fn txt2_mode_runs(layer: &TextLayer) -> Vec<(i64, usize)> { /// a missing font is appended to), size (`/1`), faux bold and italic, leading, scales and tracking /// (`/2`–`/8`, EngineData's order), fill colour (`/53`), the OpenType keys and the auto-kern mode /// (`/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. +/// 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) -> Option> { - if !matches!(base.path(&["0", "0", "6"]), Some(E::Dict(_))) { + if !matches!(base.path(&["0", "0", "6"]), Some(E::Dict(_))) || !fits(base, &mut { TEMPLATE_NODES }) { return None; } let k = if dpi.is_finite() && dpi > 0.0 { dpi / 72.0 } else { 1.0 }; @@ -967,9 +968,10 @@ fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec, dpi: f32) -> } let default = CharStyle::default(); let mut out = Vec::with_capacity(spans.len()); + let mut looked_up = std::collections::HashMap::new(); for (ri, n) in spans { let s = runs.get(ri).map_or(&default, |r| &r.style); - let font = txt2_font(fonts, &postscript_for(s)); + let font = *looked_up.entry(postscript_for(s)).or_insert_with_key(|name| txt2_font(fonts, name)); let mut run = base.clone(); let style = run.get_mut("0")?.get_mut("0")?.get_mut("6")?; if let Some(font) = font {