PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(psd): an edited type layer updates the Photoshop-era Txt2 objects too (#6971)
VishnuByrraju013863da9512
diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rsindex 99fb2ebf0..ae8613802 100644--- a/crates/text/src/psd.rs+++ b/crates/text/src/psd.rs@@ -1104,6 +1104,14 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpilet 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<E> = prev_objects.to_vec();+ // The older Photoshop's objects (#6971): named keys at `/DocumentObjects /TextObjects`+ // instead of the numbered `/1 /1`, one entry per layer by `TextIndex` position (the same+ // numbering the slots take), its text under `Model /Text` and its run lengths under `/Length`.+ // Photoshop re-renders a type layer from this copy when the file has one, so an edit that+ // left the old text here showed the old text back on reopen. The entries are only ever edited+ // in place, never grown: a layer the block has no entry for has no stale copy to fix.+ let mut td: Option<Vec<E>> = prev.as_ref().and_then(|p| p.path(&["DocumentObjects", "TextObjects"])).and_then(E::as_array).map(<[E]>::to_vec);+ let mut td_changed = false;let mut fonts: Vec<E> = 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@@ -1118,6 +1126,21 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpilet text = format!("{}\r", layer.text.replace('\n', "\r"));let modes = txt2_mode_runs(layer);let at = *index as usize;+ // The older Photoshop's copy of this object (#6971), refitted like the numbered one+ // below. The entry's own text is the check, so a file a previous save left with a stale+ // copy beside a current `/1 /1` object is repaired here too.+ if let Some(entries) = td.as_mut() {+ let fixed = match entries.get(at) {+ Some(entry) if entry.path(&["Model", "Text"]).and_then(E::as_str) != Some(text.as_str()) => td_edited_object(entry, &text),+ _ => None,+ };+ if let Some(fixed) = fixed+ && let Some(slot) = entries.get_mut(at)+ {+ *slot = fixed;+ td_changed = true;+ }+ }// 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.@@ -1182,6 +1205,14 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpiSome(objs @ E::Dict(_)) => objs.set("1", E::Array(slots)),_ => outer.set("1", E::Dict(vec![("1".into(), E::Array(slots))])),}+ // The older Photoshop's objects, whatever the loop fixed in them (an untouched list is left+ // exactly as the file has it, so the byte-for-byte return below still holds).+ if td_changed+ && let Some(entries) = td+ && let Some(objects @ E::Dict(_)) = outer.get_mut("DocumentObjects")+ {+ objects.set("TextObjects", E::Array(entries));+ }// Nothing changed: the file's own bytes (writing them back would re-encode strings and numbers).if let (Some(bytes), Some(p)) = (previous, &prev)&& *p == outer@@ -1237,7 +1268,7 @@ fn new_object(template: &E, at: usize, text: &str) -> Option<E> {}}if let Some(runs) = view.path(&["1", "0"]).and_then(E::as_array) {- let fitted = runs_per(runs, ¶graphs)?;+ let fitted = runs_per(runs, ¶graphs, "1")?;view.get_mut("1")?.set("0", E::Array(fitted));}Some(object)@@ -1290,34 +1321,82 @@ fn edited_object(object: &E, text: &str) -> Option<E> {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)? };+ let fitted = if key.as_str() == "5" { runs_per(runs, ¶graphs, "1")? } else { runs_to_length(runs, total, "1")? };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>> {+/// The older Photoshop's `Txt2` text object `object` (`<< /Model << /Text … /ParagraphRun … >>+/// /View … >>`) for the changed engine text `text` (`\r` breaks, trailing `\r`): the model's text+/// replaced and every run array of the model refitted the way [`edited_object`] refits the+/// numbered objects' — the paragraph runs (`/ParagraphRun`) one per paragraph of the new text, the+/// others (`/StyleRun`, `/KernRun`, …) cut or extended to the new total. The model's other keys,+/// the view and the rest are kept: these blocks (the objects at `/DocumentObjects /TextObjects`+/// that older Photoshop versions write and re-render from, #6971) name their keys and number+/// their runs with `/Length` in UTF-16 units instead of `/1`. `None` when the object or one of+/// its run arrays isn't shaped as Photoshop writes it: the caller then leaves the entry as the+/// file has it, rather than write text its runs don't cover (#6968).+fn td_edited_object(object: &E, text: &str) -> Option<E> {+ let mut object = object.clone();+ let model = object.get_mut("Model").filter(|m| matches!(m, E::Dict(_)))?;+ let E::Dict(entries) = model else { return None };+ // The text must be there to replace: refitted runs over a text the model doesn't hold would+ // be a half-edited object.+ if !entries.iter().any(|(k, v)| k == "Text" && matches!(v, E::String(_))) {+ return None;+ }+ let total = utf16_len(text) as usize;+ let paragraphs: Vec<usize> = text.split_inclusive('\r').map(|p| p.encode_utf16().count()).collect();+ for (key, value) in entries.iter_mut() {+ if key.as_str() == "Text" {+ *value = E::String(text.to_string());+ continue;+ }+ if !matches!(value, E::Dict(_)) {+ continue;+ }+ // A model dict without `RunArray` isn't a run array (the view's keys live elsewhere), so+ // it is skipped; a named `RunArray` is unambiguous — malformed, the whole entry is left to+ // the file rather than half-updated.+ let Some(runs) = value.get("RunArray") else { continue };+ let fitted = match runs {+ E::Array(runs) if runs.iter().all(|x| matches!(x, E::Dict(_)) && x.get("Length").is_some()) => {+ if key.as_str() == "ParagraphRun" {+ runs_per(runs, ¶graphs, "Length")?+ } else {+ runs_to_length(runs, total, "Length")?+ }+ }+ _ => return None,+ };+ value.set("RunArray", E::Array(fitted));+ }+ Some(object)+}++/// `runs` (`<< … /1 length >>`, the length key named `len_key`) 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], len_key: &str) -> 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()?));+ r.set(len_key, 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>> {+/// `runs` (`<< … /1 length >>`, the length key named `len_key`) 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, len_key: &str) -> 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 len = r.get(len_key).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));@@ -1332,7 +1411,7 @@ fn runs_to_length(runs: &[E], total: usize) -> Option<Vec<E>> {}out.into_iter().map(|(mut r, len)| {- r.set("1", E::Int(i64::try_from(len).ok()?));+ r.set(len_key, E::Int(i64::try_from(len).ok()?));Some(r)}).collect()diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rsindex 6aecea05a..d7d37a091 100644--- a/crates/text/src/tests.rs+++ b/crates/text/src/tests.rs@@ -1085,6 +1085,202 @@ fn txt2_keeps_a_kept_objects_extras_and_drops_them_with_its_text() {assert!(object.path(&["0", "keep"]).is_none(), "model extras of another text are dropped");}+/// The `DocumentObjects` value older Photoshop writes beside the numbered objects+/// (`/DocumentObjects /TextObjects`, named keys, run lengths under `/Length` in UTF-16 units,+/// #6971): one entry per layer, its `\r`-terminated text in `Model /Text`, one paragraph run per+/// paragraph, one style and kern run covering the whole text.+fn photoshop_era_objects(texts: &[&str]) -> crate::engine_data::Value {+ use crate::engine_data::Value as E;+ let run = |len: i64| E::Dict(vec![("RunData".into(), E::Dict(vec![("0".into(), E::String(String::new()))])), ("Length".into(), E::Int(len))]);+ let entries = texts+ .iter()+ .map(|t| {+ let text = format!("{t}\r");+ let paragraphs: Vec<i64> = text.split_inclusive('\r').map(|p| p.encode_utf16().count() as i64).collect();+ let total = text.encode_utf16().count() as i64;+ E::Dict(vec![+ (+ "Model".into(),+ E::Dict(vec![+ ("Text".into(), E::String(text)),+ ("ParagraphRun".into(), E::Dict(vec![("RunArray".into(), E::Array(paragraphs.iter().map(|&n| run(n)).collect()))])),+ ("StyleRun".into(), E::Dict(vec![("RunArray".into(), E::Array(vec![run(total)]))])),+ ("KernRun".into(), E::Dict(vec![("RunArray".into(), E::Array(vec![run(total)]))])),+ ]),+ ),+ ("View".into(), E::Dict(vec![("0".into(), E::Array(vec![E::Dict(vec![("0".into(), E::Int(0))])]))])),+ ])+ })+ .collect();+ E::Dict(vec![("TextObjects".into(), E::Array(entries))])+}++/// A whole `Txt2` block shaped like the older Photoshop's: document resources and the objects at+/// `/DocumentObjects /TextObjects`, no numbered `/1 /1` list at all.+fn photoshop_era_txt2(texts: &[&str]) -> Vec<u8> {+ use crate::engine_data::Value as E;+ crate::engine_data::write_bare(&[+ ("98".into(), E::Dict(vec![("0".into(), E::Int(14))])),+ ("0".into(), E::dict()),+ ("DocumentObjects".into(), photoshop_era_objects(texts)),+ ])+}++/// #6971: Photoshop re-renders a type layer from the objects older Photoshop keeps at+/// `/DocumentObjects /TextObjects` when the file has them, so an edit that left the old text+/// there showed the old text back on reopen. The save refits that copy the way it refits the+/// numbered ones — the new text, one paragraph run per paragraph of it, the other runs to its+/// total — and keeps the entries' view and the rest.+#[test]+fn edited_text_updates_the_photoshop_era_objects() {+ use crate::engine_data::Value as E;+ use photocraft_doc::text::Kerning;+ let prev = photoshop_era_txt2(&["Line 1\rLine 2"]);+ let before = crate::psd::parse_txt2(&prev).unwrap();+ let t = styled("Hi\nBye", CharStyle { kerning: Kerning::Optical, ..Default::default() });+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap();+ let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");+ assert_eq!(entries.len(), 1, "no entry is added");+ let entry = entries.first().expect("the entry");+ let model = entry.get("Model").expect("the model");+ assert_eq!(model.get("Text").and_then(E::as_str), Some("Hi\rBye\r"), "the stale text is replaced");+ let lens = |key: &str| -> Vec<i64> {+ model+ .path(&[key, "RunArray"])+ .and_then(E::as_array)+ .map(|rs| rs.iter().map(|r| r.get("Length").and_then(E::as_i64).unwrap_or(-1)).collect())+ .unwrap_or_default()+ };+ assert_eq!(lens("ParagraphRun"), vec![3, 4], "one paragraph run per paragraph of the new text");+ assert_eq!(lens("StyleRun"), vec![7], "the style runs cover the new text's UTF-16 units");+ assert_eq!(lens("KernRun"), vec![7]);+ assert_eq!(+ entry.get("View"),+ before.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).and_then(|e| e.first()).and_then(|e| e.get("View")),+ "the view is kept"+ );+ // The numbered list is written alongside, as it was before this fix.+ let slots = out.path(&["1", "1"]).and_then(E::as_array).expect("the numbered objects");+ assert_eq!(slots.len(), 1);+ assert_eq!(slots.first().and_then(|o| o.path(&["0", "0"])).and_then(E::as_str), Some("Hi\rBye\r"));+}++/// Only the entries of layers the save holds change: another layer's object — one no layer names+/// — is written back as the file has it.+#[test]+fn only_the_edited_photoshop_era_object_changes() {+ use crate::engine_data::Value as E;+ use photocraft_doc::text::Kerning;+ let prev = photoshop_era_txt2(&["One", "Two"]);+ let before = crate::psd::parse_txt2(&prev).unwrap();+ let style = |kerning: Kerning| CharStyle { kerning, ..Default::default() };+ let t0 = runs_of("One", &[(3, style(Kerning::Metrics))]);+ let t1 = runs_of("Changed", &[(7, style(Kerning::Optical))]);+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t0), (1, &t1)], Some(&prev))).unwrap();+ let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");+ let was = before.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects before");+ assert_eq!(entries.len(), 2, "no entry is added");+ assert_eq!(entries.first(), was.first(), "the unchanged entry is written back as it was");+ assert_eq!(entries.get(1).and_then(|e| e.path(&["Model", "Text"])).and_then(E::as_str), Some("Changed\r"), "the edited entry takes the new text");+}++/// Files saved by the old code have both lists: the numbered object current, the older copy still+/// holding the text of an earlier edit. Re-saving repairs the stale copy even when the numbered+/// object's text matches the layer (nothing else about the file changes).+#[test]+fn legacy_file_with_both_object_lists_repairs_the_stale_one() {+ use crate::engine_data::Value as E;+ use photocraft_doc::text::Kerning;+ let mut prev = photoshop_txt2(&[(4, 1)]);+ prev.extend_from_slice(&crate::engine_data::write_bare(&[("DocumentObjects".into(), photoshop_era_objects(&["Old stuff"]))]));+ let before = crate::psd::parse_txt2(&prev).unwrap();+ let t = styled("AVA", CharStyle { kerning: Kerning::Metrics, ..Default::default() });+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap();+ let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");+ assert_eq!(entries.len(), 1);+ let model = entries.first().expect("the entry").get("Model").expect("the model");+ assert_eq!(model.get("Text").and_then(E::as_str), Some("AVA\r"), "the stale copy is repaired");+ let lens = model+ .path(&["StyleRun", "RunArray"])+ .and_then(E::as_array)+ .map(|rs| rs.iter().map(|r| r.get("Length").and_then(E::as_i64).unwrap_or(-1)).collect::<Vec<_>>());+ assert_eq!(lens, Some(vec![4]), "its runs cover the layer's text");+ let slots = out.path(&["1", "1"]).and_then(E::as_array).expect("the numbered objects");+ assert_eq!(slots.first().and_then(|o| o.path(&["0", "0"])).and_then(E::as_str), Some("AVA\r"), "the numbered object is kept as it was");+ assert_eq!(before.path(&["1", "1"]).and_then(E::as_array).and_then(|s| s.first()), slots.first(), "the numbered object changes not at all");+}++/// When both lists hold the layer's text, the block is written back byte for byte — #2374 holds+/// for the older objects too: re-encoding them would only risk Photoshop refusing the file.+#[test]+fn unchanged_block_with_both_object_lists_is_byte_identical() {+ use photocraft_doc::text::Kerning;+ let mut prev = photoshop_txt2(&[(4, 1)]);+ prev.extend_from_slice(&crate::engine_data::write_bare(&[("DocumentObjects".into(), photoshop_era_objects(&["AVA"]))]));+ let t = styled("AVA", CharStyle { kerning: Kerning::Metrics, ..Default::default() });+ assert_eq!(crate::psd::build_txt2(&[(0, &t)], Some(&prev)), prev);+}++/// An entry shaped unlike Photoshop writes it — a run without its `/Length`, a `RunArray` that+/// isn't an array, an empty one, an object with no text to replace — is left exactly as the file+/// has it: a half-refitted object (new text over old runs) is what made Photoshop quit (#6968),+/// so the save never writes one.+#[test]+fn odd_photoshop_era_entries_are_left_as_the_file_has_them() {+ use crate::engine_data::Value as E;+ use photocraft_doc::text::Kerning;+ let run = |len: i64| E::Dict(vec![("RunData".into(), E::dict()), ("Length".into(), E::Int(len))]);+ let entry = |model: Vec<(&str, E)>| {+ E::Dict(vec![("Model".into(), E::Dict(model.into_iter().map(|(k, v)| (k.to_string(), v)).collect())), ("View".into(), E::dict())])+ };+ let with_text = |text: E, style: E| {+ entry(vec![+ ("Text", text),+ ("ParagraphRun", E::Dict(vec![("RunArray".into(), E::Array(vec![run(4)]))])),+ ("StyleRun", E::Dict(vec![("RunArray".into(), style)])),+ ])+ };+ let odd = [+ with_text(E::String("Old\r".into()), E::Array(vec![E::Dict(vec![("RunData".into(), E::dict())])])),+ with_text(E::String("Old\r".into()), E::Int(3)),+ with_text(E::String("Old\r".into()), E::Array(vec![])),+ E::Int(3),+ entry(vec![("ParagraphRun", E::Dict(vec![("RunArray".into(), E::Array(vec![run(4)]))]))]),+ with_text(E::Int(9), E::Array(vec![run(4)])),+ ];+ for (i, object) in odd.iter().enumerate() {+ let prev = crate::engine_data::write_bare(&[+ ("98".into(), E::Dict(vec![("0".into(), E::Int(14))])),+ ("0".into(), E::dict()),+ ("DocumentObjects".into(), E::Dict(vec![("TextObjects".into(), E::Array(vec![object.clone()]))])),+ ]);+ let was = crate::psd::parse_txt2(&prev).unwrap();+ let t = styled("New", CharStyle { kerning: Kerning::Optical, ..Default::default() });+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap();+ let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");+ assert_eq!(+ entries.first(),+ was.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).and_then(|e| e.first()),+ "entry {i} is left as the file has it"+ );+ }+}++/// A `TextIndex` past the entries the block holds has no stale copy to fix: nothing is grown to+/// the layer's number (the slot list grows as it always did), and the entries stay the file's.+#[test]+fn a_text_index_beyond_the_photoshop_era_entries_grows_nothing() {+ use crate::engine_data::Value as E;+ use photocraft_doc::text::Kerning;+ let prev = photoshop_era_txt2(&["Only one"]);+ let was = crate::psd::parse_txt2(&prev).unwrap();+ let t = styled("Whatever", CharStyle { kerning: Kerning::Optical, ..Default::default() });+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(crate::psd::MAX_TEXT_INDEX, &t)], Some(&prev))).unwrap();+ let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");+ assert_eq!(entries.len(), 1, "no entry is grown to the layer's number");+ assert_eq!(entries.first(), was.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).and_then(|e| e.first()));+}+/// A `Txt2` shaped like Photoshop's: document resources and settings beside the text objects/// (`/0`, `/1 /0`, `/1 /2`), style runs carrying a full style (font, size, leading) besides the/// auto-kern mode, a Latin-1 string without a byte-order mark, reals, and a second object no