PhotoCraft: An open-source, photo editor written by scratch in pure Rust
PSD: Optical kerning survives a round trip (#1517)
shmuelbiller1decc7715b956
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 45dd05df5..137a1a3ab 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -51,6 +51,10 @@ struct Ex {next_id: u32,/// PSD ids assigned to document layers (kept from `psd_id` when unique).layer_ids: std::collections::HashMap<photocraft_doc::LayerId, u32>,+ /// The generated `Txt2` object number of each type layer (a preserved `TySh` keeps its own+ /// `TextIndex`, others get the next free number; see `photocraft_text::psd::build_txt2`),+ /// written into the `TySh` data this export re-serializes.+ text_index: std::collections::HashMap<photocraft_doc::LayerId, i32>,canvas: photocraft_geom::Rect,records: Vec<LayerRecord>,warnings: Vec<String>,@@ -475,7 +479,16 @@ impl Ex {let src = t.psd_raw.as_ref().or(generated.as_ref());// Character/paragraph style sheets from the document's styles.let styled = src.and_then(|d| crate::text_styles_map::export_tysh(d, t, &self.text_styles, self.dpi)).map(std::sync::Arc::new);- set_principal(&mut raw, &[b"TySh"], styled.as_ref().or(src));+ // `TextIndex` names the layer's object in the document's `Txt2` (where the+ // auto-kern mode lives); left at 0, every type layer would claim object 0 (#1348).+ // Keep an unchanged preserved TySh byte-for-byte (corpus_tysh_lossless).+ // Duplicate or out-of-range file TextIndex values must be renumbered,+ // however, even when no style sheet needed rebuilding: otherwise two+ // layers may read the same Txt2 object and acquire the wrong kerning.+ let idx = self.text_index.get(&l.id).copied().unwrap_or(0);+ let rewrite = styled.as_ref().or(generated.as_ref()).or_else(|| src.filter(|d| photocraft_text::psd::text_index(d.as_slice()) != Some(idx)));+ let fresh = rewrite.and_then(|d| photocraft_text::psd::set_text_index(d.as_slice(), idx)).map(std::sync::Arc::new);+ set_principal(&mut raw, &[b"TySh"], fresh.as_ref().or(styled.as_ref().or(src)));if !raw.iter().any(|(k, _)| k == b"TySh") {self.warnings.push(format!("layer \"{}\": text layer written as pixels (no TySh data)", l.name));}@@ -1119,6 +1132,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32) -fmt,dpi: doc.resolution_dpi,text_styles: doc.text_styles.clone(),+ text_index: Default::default(),mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false),cc,cmyk: fmt.mode == ColorMode::Cmyk,@@ -1163,6 +1177,29 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32) -}}ex.next_id = used.iter().copied().max().unwrap_or(0);+ // 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.+ let mut used_txt = std::collections::HashSet::new();+ let mut next_txt = 0i32;+ ex.text_index = Default::default();+ 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+ }+ };+ ex.text_index.insert(l.id, index);+ }}ex.emit(&doc.layers);@@ -1281,15 +1318,40 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32) -resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned()));}let mut global_blocks = Vec::new();- for (sig, key, data) in &ex.smart.finish(crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc))) {- let mut tb = TaggedBlock::new(*key, data.to_vec());- tb.signature = *sig;+ let preserved = ex.smart.finish(crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc)));+ // The type layers' `Txt2` is regenerated (the auto-kern modes live there, and a preserved+ // block goes stale as text is edited): one object per `TextIndex`, at the slot each layer's+ // `TySh` names (unused slots stay empty; see `photocraft_text::psd::build_txt2`). The block+ // it replaces is handed over so a kept object keeps everything the file held beyond its text+ // and style runs (Photoshop's `/21 /1` glyph pen positions, …).+ let text_layers: Vec<(i32, &photocraft_doc::TextLayer)> = doc+ .walk()+ .into_iter()+ .filter_map(|(_, _, l)| match &l.content {+ LayerContent::Text(t) => Some((ex.text_index.get(&l.id).copied().unwrap_or(0), t)),+ _ => None,+ })+ .collect();+ let previous = (!text_layers.is_empty()).then(|| preserved.iter().find(|(_, key, _)| key == b"Txt2").map(|(_, _, data)| data.to_vec())).flatten();+ let txt2 = (!text_layers.is_empty()).then(|| photocraft_text::psd::build_txt2(&text_layers, previous.as_deref()));+ for (sig, key, data) in preserved {+ if txt2.is_some() && key == *b"Txt2" {+ continue;+ }+ let mut tb = TaggedBlock::new(key, data.to_vec());+ tb.signature = sig;// Photoshop pads document-level (global) blocks to a multiple of 4, and readers such as// psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes)// misaligned every block after it (#200).tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]);global_blocks.push(tb);}+ if let Some(txt2) = txt2 {+ let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone());+ tb.signature = *b"8BIM";+ tb.padding = Some(vec![0; (4 - txt2.len() % 4) % 4]);+ global_blocks.push(tb);+ }let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc));let (slices_resource, slices_warning) = crate::slices_map::export_resource(doc, &ex.layer_ids);if let Some(warning) = slices_warning {diff --git a/crates/io/tests/psd_kerning.rs b/crates/io/tests/psd_kerning.rsindex 73cec791b..c3c4a09f3 100644--- a/crates/io/tests/psd_kerning.rs+++ b/crates/io/tests/psd_kerning.rs@@ -79,6 +79,108 @@ fn manual_and_off_kerning_round_trip_through_psd() {assert!(f.iter().enumerate().filter(|(j, _)| ![1, 4, 8, 9, 10].contains(j)).all(|(_, x)| *x == (true, 0)), "{f:?}");}+/// #1348: the automatic mode (Metrics/Optical) lives in the document `Txt2` block, one model+/// object per `TextIndex`. A PhotoCraft-authored PSD must carry it or a reopened layer falls+/// back to Metrics — Optical used to be silently lost.+#[test]+fn optical_kerning_round_trips_through_psd() {+ use Kerning::{Metrics as M, Optical as P};+ let t1 = layer("AVATAR", &[(4, P, 0.0), (2, M, 0.0)]);+ let t2 = layer("Wave", &[(2, M, 0.0), (2, P, 0.0)]);+ let mut doc = Document::new("k", photocraft_geom::Size::new(64, 32), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);+ for (name, want) in [("one", &t1), ("two", &t2)] {+ let mut t = want.clone();+ photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format());+ doc.layers.push(Layer::new(name, 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;+ for (want, l) in [(&t1, &back.layers[0]), (&t2, &back.layers[1])] {+ let LayerContent::Text(b) = &l.content else { panic!("not text") };+ assert_eq!(chars(b), chars(want), "{}", l.name);+ }+}++/// Two imported layers can name the same Txt2 object; export must update the second+/// preserved TySh pointer so each layer restores its own automatic kerning mode.+#[test]+fn duplicate_preserved_text_indices_get_distinct_txt2_objects() {+ let mut doc = Document::new("k", photocraft_geom::Size::new(64, 32), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);+ let cases = [("optical", "AV", Kerning::Optical), ("metrics", "BC", Kerning::Metrics)];+ for (name, text, mode) in cases {+ let mut t = layer(text, &[(text.len(), mode, 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(name, 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();+ assert_eq!(txt2.path(&["1", "1"]).and_then(E::as_array).unwrap().len(), 2);+ let back = photocraft_io::import("k.psd", &bytes).unwrap().document;+ for (i, expected) in [Kerning::Optical, Kerning::Metrics].into_iter().enumerate() {+ let LayerContent::Text(t) = &back.layers[i].content else { panic!("expected text layer") };+ assert!(chars(t).iter().all(|(mode, _)| *mode == expected), "layer {i} used another layer's Txt2 object");+ }+}++/// 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.+#[test]+fn hostile_text_index_never_sizes_the_save() {+ let t = layer("AV", &[(1, Kerning::Metrics, 0.0), (1, Kerning::Optical, 0.0)]);+ 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());+ // An invalid index is remapped into the saved Txt2 rather than preserved.+ r.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::set_text_index(&photocraft_text::psd::build_tysh(&r, 72.0, None), i32::MAX).unwrap()));+ doc.layers.push(Layer::new("hostile", LayerContent::Text(r)));+ 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 slots = txt2.path(&["1", "1"]).and_then(E::as_array).unwrap();+ assert!(slots.len() <= 8, "a file-controlled TextIndex sized the save: {} slots", slots.len());+ let back = photocraft_io::import("k.psd", &bytes).unwrap().document;+ let LayerContent::Text(b) = &back.layers[0].content else { panic!("not text") };+ assert_eq!(b.text, "AV");+ assert_eq!(chars(b), chars(&t), "a remapped TextIndex must still restore Optical kerning");+}++/// A save must not drop what the file held beyond the style runs: the previous `Txt2`'s glyph+/// pen positions (`/21 /1`) survive a resave of unchanged text, and go away with the text they+/// described rather than lying about the new one.+#[test]+fn txt2_extras_survive_a_resave_of_unchanged_text() {+ let obj = E::Dict(vec![+ ("0".into(), E::Dict(vec![("0".into(), E::String("AV\r".into())), ("6".into(), E::Dict(vec![("0".into(), E::Array(vec![]))]))])),+ ("21".into(), E::Dict(vec![("1".into(), E::Array(vec![E::Real(10.0), E::Real(20.0)]))])),+ ]);+ let prev = photocraft_text::engine_data::write_bare(&[+ ("98".into(), E::Dict(vec![("0".into(), E::Int(14))])),+ ("0".into(), E::dict()),+ ("1".into(), E::Dict(vec![("1".into(), E::Array(vec![obj]))])),+ ]);+ let save = |text: &str| {+ let t = layer(text, &[(text.len(), Kerning::Metrics, 0.0)]);+ 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());+ 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;+ let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap();+ photocraft_text::psd::parse_txt2(&file.global_blocks.iter().find(|b| &b.key == b"Txt2").unwrap().data).unwrap()+ };+ let kept = save("AV");+ let object = kept.path(&["1", "1"]).and_then(E::as_array).unwrap()[0].clone();+ assert_eq!(object.path(&["21", "1"]).and_then(E::as_array).map(|items| items.len()), Some(2), "pen positions survive a resave of unchanged text");+ let stale = save("AX");+ let object = stale.path(&["1", "1"]).and_then(E::as_array).unwrap()[0].clone();+ assert!(object.get("21").is_none(), "positions of another text are stale and dropped");+}+/// Kerning that can't be represented (non-finite) and bad PSD fields never panic and stay sane.#[test]fn hostile_kerning_values() {diff --git a/crates/text/src/engine_data.rs b/crates/text/src/engine_data.rsindex d5731f663..c8115c3e1 100644--- a/crates/text/src/engine_data.rs+++ b/crates/text/src/engine_data.rs@@ -227,6 +227,25 @@ pub fn write(v: &Value) -> Vec<u8> {out}+/// Serializes `/key value` pairs without an enclosing dictionary: the layout of the document's+/// `Txt2` block (see [`crate::psd::build_txt2`]), which `parse_txt2` wraps in `<< >>` to parse.+pub fn write_bare(items: &[(String, Value)]) -> Vec<u8> {+ let mut out = b"\n\n".to_vec();+ for (k, v) in items {+ out.push(b'/');+ out.extend_from_slice(k.as_bytes());+ if is_container(v) {+ out.push(b'\n');+ indent(&mut out, 1);+ } else {+ out.push(b' ');+ }+ write_value(v, 1, &mut out);+ out.push(b'\n');+ }+ out+}+fn indent(out: &mut Vec<u8>, n: usize) {out.extend(std::iter::repeat_n(b'\t', n));}diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rsindex 200acfbe7..6c9973085 100644--- a/crates/text/src/psd.rs+++ b/crates/text/src/psd.rs@@ -690,6 +690,121 @@ pub(crate) fn font_entry(name: &str) -> E {E::Dict(vec![("Name".into(), E::String(name.into())), ("Script".into(), E::Int(0)), ("FontType".into(), E::Int(1)), ("Synthetic".into(), E::Int(0))])}+/// The `Txt2` auto-kern mode of a style: 0 manual, 1 metrics, 2 optical — the values+/// [`apply_txt2`] maps back to [`Kerning`]. EngineData's `AutoKerning` can't say Metrics from+/// Optical, so the mode only lives in `Txt2`.+fn txt2_mode(s: &CharStyle) -> i64 {+ if manual(s) {+ 0+ } else if s.kerning == Kerning::Optical {+ 2+ } else {+ 1+ }+}++/// `Txt2` style runs for `layer`: `(mode, UTF-16 length)` over the engine text (`\r` breaks and+/// the trailing `\r`, which takes the last run's mode), split where the auto-kern mode changes.+fn txt2_mode_runs(layer: &TextLayer) -> Vec<(i64, usize)> {+ let runs = layer.char_runs();+ let ed_text = format!("{}\r", layer.text.replace('\n', "\r"));+ let mut out: Vec<(i64, usize)> = 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 mode = runs.get(ri).map_or(1, |r| txt2_mode(&r.style));+ match out.last_mut() {+ Some(last) if last.0 == mode => last.1 += ch.len_utf16(),+ _ => out.push((mode, ch.len_utf16())),+ }+ }+ out+}++/// 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.+pub const MAX_TEXT_INDEX: i32 = 0xFFFF;++/// The document's `Txt2` block for `objects`: `(TextIndex, layer)` pairs, one text object each+/// at the slot its `TextIndex` names (see [`set_text_index`] and [`text_index`]; unused slots are+/// empty dictionaries), carrying the automatic kerning mode of every pair (`/11`: 0 manual,+/// 1 metrics, 2 optical) — the one thing EngineData can't say (`AutoKerning true` covers Metrics+/// and Optical alike). PSD export writes this block for the type layers it writes `TySh` data+/// for; [`apply_txt2`] reads it back. Numbers outside `0..=`[`MAX_TEXT_INDEX`] are skipped: the+/// slot array is sized by real text objects, never by a file's numbers.+///+/// `previous` is the block this replaces (the file's own). A kept object — one whose text is+/// 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. A changed text invalidates those extras along with the old+/// runs, so they are dropped rather than left stale.+pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec<u8> {+ 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<E> = Vec::new();+ for (index, layer) in objects {+ if !(0..=MAX_TEXT_INDEX).contains(index) {+ continue;+ }+ let text = format!("{}\r", layer.text.replace('\n', "\r"));+ let runs: Vec<E> = txt2_mode_runs(layer)+ .into_iter()+ .map(|(mode, len)| {+ // `<< /0 << /0 << /0 () /6 << /0 0 /11 mode >> >> >> /1 len >>`.+ let style = E::Dict(vec![("0".into(), E::Int(0)), ("11".into(), E::Int(mode))]);+ let data = E::Dict(vec![("0".into(), E::String(String::new())), ("6".into(), style)]);+ E::Dict(vec![("0".into(), E::Dict(vec![("0".into(), data)])), ("1".into(), E::Int(len as i64))])+ })+ .collect();+ 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);+ let mut model = object.get("0").cloned().filter(|m| matches!(m, E::Dict(_))).unwrap_or_else(E::dict);+ model.set("0", E::String(text));+ model.set("6", E::Dict(vec![("0".into(), E::Array(runs))]));+ object.set("0", model);+ if slots.len() <= at {+ slots.resize(at + 1, E::dict());+ }+ slots[at] = object;+ }+ // The outer dictionary keeps whatever the block held (`/98` version, block extras, …).+ let mut outer = prev.unwrap_or_else(|| E::Dict(vec![("98".into(), E::Dict(vec![("0".into(), E::Int(14))])), ("0".into(), E::dict())]));+ outer.set("1", E::Dict(vec![("1".into(), E::Array(slots))]));+ match outer {+ E::Dict(items) => ed::write_bare(&items),+ // Unreachable: `parse_txt2` and the fallback above both yield a dictionary.+ _ => ed::write_bare(&[]),+ }+}++/// The layer's text-object number in the document's `Txt2` block, when its `TySh` names one+/// within `0..=`[`MAX_TEXT_INDEX`]. PSD export keeps a preserved number — its regenerated `Txt2`+/// object sits at that slot, and [`apply_txt2`] looks the slot up — and numbers layers without+/// one (or with a file-controlled out-of-range one) afresh.+pub fn text_index(tysh: &[u8]) -> Option<i32> {+ let t = parse_tysh(tysh)?;+ match t.text.get("TextIndex") {+ Some(D::Integer(i)) if (0..=MAX_TEXT_INDEX).contains(i) => Some(*i),+ _ => None,+ }+}++/// 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<Vec<u8>> {+ 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))),+ }+ Some(write_tysh(&t))+}+/// Updates (or creates) an EngineData tree for `layer`.pub fn build_engine_data(layer: &TextLayer, template: Option<E>, dpi: f32) -> E {let k = 72.0 / if dpi > 0.0 { dpi } else { 72.0 };diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rsindex 6dd98e91c..624839ed4 100644--- a/crates/text/src/tests.rs+++ b/crates/text/src/tests.rs@@ -567,6 +567,96 @@ fn txt2_carries_optical_kerning() {assert!(l.char_runs().iter().all(|r| r.style.kerning == Kerning::Optical));}+/// A `Txt2` written by [`crate::psd::build_txt2`] (what PSD export writes for the type layers)+/// restores every auto-kern mode on import (#1348: a new Optical layer used to reopen as+/// Metrics, because EngineData's `AutoKerning true` covers both).+#[test]+fn build_txt2_round_trips_kerning_modes() {+ use photocraft_doc::text::Kerning;+ let style = |kerning: Kerning, kern: f32| CharStyle { kerning, kern, ..Default::default() };+ let t = runs_of("AVAT", &[(2, style(Kerning::Optical, 0.0)), (1, style(Kerning::Metrics, 0.0)), (1, style(Kerning::Off, 0.0))]);+ let tysh = with_text_index(&crate::psd::build_tysh(&t, 72.0, None), 0);+ let mut back = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap();+ assert!(+ back.char_runs().iter().all(|r| r.style.kerning != Kerning::Optical),+ "EngineData alone can't say Optical: {:?}",+ back.char_runs().iter().map(|r| r.style.kerning).collect::<Vec<_>>()+ );+ let txt2 = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], None)).unwrap();+ crate::psd::apply_txt2(&mut back, &tysh, &txt2);+ let modes: Vec<(usize, Kerning)> = back.char_runs().iter().map(|r| (r.len, r.style.kerning)).collect();+ assert_eq!(modes, vec![(2, Kerning::Optical), (1, Kerning::Metrics), (1, Kerning::Off)]);+ // A manual kern (a nonzero pair value) is the manual mode, as in the EngineData pair fields.+ let manual = runs_of("AB", &[(1, style(Kerning::Metrics, 50.0)), (1, style(Kerning::Metrics, 0.0))]);+ let tysh = with_text_index(&crate::psd::build_tysh(&manual, 72.0, None), 0);+ let mut back = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap();+ let txt2 = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &manual)], None)).unwrap();+ crate::psd::apply_txt2(&mut back, &tysh, &txt2);+ let modes: Vec<(usize, Kerning)> = back.char_runs().iter().map(|r| (r.len, r.style.kerning)).collect();+ assert_eq!(modes, vec![(1, Kerning::Off), (1, Kerning::Metrics)]);+}++/// A kept `Txt2` object — same text, so its extras are still true — keeps everything the file+/// held beyond the regenerated keys (Photoshop stores glyph pen positions under `/21 /1`), and a+/// changed text drops those extras with the stale runs. The block's own extras always survive.+#[test]+fn txt2_keeps_a_kept_objects_extras_and_drops_them_with_its_text() {+ use crate::engine_data::Value as E;+ use photocraft_doc::text::Kerning;+ let style = |kerning: Kerning, kern: f32| CharStyle { kerning, kern, ..Default::default() };+ // The file's block: object 0 with `/21 /1` pen positions, a model extra, and a block extra.+ let obj = E::Dict(vec![+ (+ "0".into(),+ E::Dict(vec![("0".into(), E::String("AB\r".into())), ("6".into(), E::Dict(vec![("0".into(), E::Array(vec![]))])), ("keep".into(), E::Int(7))]),+ ),+ ("21".into(), E::Dict(vec![("1".into(), E::Array(vec![E::Real(1.5), E::Real(2.5)]))])),+ ]);+ let prev = crate::engine_data::write_bare(&[+ ("98".into(), E::Dict(vec![("0".into(), E::Int(14))])),+ ("0".into(), E::dict()),+ ("1".into(), E::Dict(vec![("1".into(), E::Array(vec![obj]))])),+ ("extra".into(), E::Int(3)),+ ]);+ // Same text: the extras survive, the style runs are ours.+ let t = runs_of("AB", &[(1, style(Kerning::Optical, 0.0)), (1, style(Kerning::Metrics, 0.0))]);+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap();+ assert_eq!(out.get("extra").and_then(E::as_i64), Some(3), "block extras survive");+ let object = out.path(&["1", "1"]).and_then(E::as_array).unwrap()[0].clone();+ assert_eq!(object.path(&["21", "1"]).and_then(E::as_array).map(|items| items.len()), Some(2), "pen positions survive an unchanged text");+ assert_eq!(object.path(&["0", "keep"]).and_then(E::as_i64), Some(7), "model extras survive");+ assert_eq!(object.path(&["0", "6", "0"]).and_then(E::as_array).map(|items| items.len()), Some(2), "the style runs are regenerated");+ // Changed text: the extras go stale with the old runs and are dropped.+ let t = runs_of("XY", &[(1, style(Kerning::Optical, 0.0)), (1, style(Kerning::Metrics, 0.0))]);+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap();+ assert_eq!(out.get("extra").and_then(E::as_i64), Some(3), "block extras survive a text change too");+ let object = out.path(&["1", "1"]).and_then(E::as_array).unwrap()[0].clone();+ assert!(object.get("21").is_none(), "pen positions of another text are dropped: {:?}", object.get("21"));+ assert!(object.path(&["0", "keep"]).is_none(), "model extras of another text are dropped");+}++/// A file-controlled `TextIndex` must not size the save: out-of-range numbers are ignored (the+/// slot array is sized by real text objects, never by a file's numbers) and reading one back is+/// a no-op, so a hostile file degrades instead of allocating gigabytes on export.+#[test]+fn hostile_text_index_is_ignored_not_sized() {+ use crate::engine_data::Value as E;+ let t = runs_of("AB", &[(2, CharStyle::default())]);+ let tysh = crate::psd::build_tysh(&t, 72.0, None);+ assert_eq!(crate::psd::text_index(&crate::psd::set_text_index(&tysh, 0).unwrap()), Some(0));+ assert_eq!(crate::psd::text_index(&crate::psd::set_text_index(&tysh, crate::psd::MAX_TEXT_INDEX).unwrap()), Some(crate::psd::MAX_TEXT_INDEX));+ for hostile in [crate::psd::MAX_TEXT_INDEX + 1, i32::MAX] {+ assert_eq!(crate::psd::text_index(&crate::psd::set_text_index(&tysh, hostile).unwrap()), None, "{hostile}");+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(hostile, &t)], None)).unwrap();+ let slots = out.path(&["1", "1"]).and_then(E::as_array).unwrap();+ assert!(slots.is_empty(), "{hostile} sized {} slots", slots.len());+ }+ // The bound is real but generous: the last honoured number lands at its slot.+ let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(crate::psd::MAX_TEXT_INDEX, &t)], None)).unwrap();+ let slots = out.path(&["1", "1"]).and_then(E::as_array).unwrap();+ assert_eq!(slots.len(), crate::psd::MAX_TEXT_INDEX as usize + 1);+}+/// Photopea needs an enabled fill, not just FillColor, to paint text after an edit. Inspect the/// serialized TySh rather than our renderer, which does not consume the PSD fill flag.#[test]