diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 68842b2691..61e810e497 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1597,26 +1597,36 @@ 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 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(); - 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 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; + } + 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). @@ -1745,8 +1755,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 b75a6542ae..ad492fce25 100644 --- a/crates/io/tests/psd_kerning.rs +++ b/crates/io/tests/psd_kerning.rs @@ -144,6 +144,154 @@ 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 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 /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} >> ] >> ] >> >> " + )); + } + 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() +} + +/// 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, 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)]); + 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, *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()); + 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 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 [Reopened], name: &str) -> &'a Reopened { + 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() { + 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: +/// 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() { + 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 /// `Txt2` is sized by real text objects, never by a file's numbers) and the document still saves /// and reopens with its text. @@ -186,6 +334,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 8c502c75af..aaa901eb2d 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,90 @@ 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 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(_))) || !fits(base, &mut { TEMPLATE_NODES }) { + 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()); + 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 = *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 { + 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. @@ -964,15 +1048,30 @@ 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). 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); + // 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; @@ -980,11 +1079,34 @@ 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())); - let mut object = kept.cloned().unwrap_or_else(E::dict); + // 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(|| 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. + 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(); + 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); - let file_runs = kept.and_then(|_| model.path(&["6", "0"]).and_then(E::as_array)).and_then(|runs| with_modes(runs, &modes)); - let runs = file_runs.unwrap_or_else(|| { + // 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 = styled.or(file_runs).unwrap_or_else(|| { modes .iter() .map(|&(mode, len)| { @@ -1011,6 +1133,12 @@ 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()); + 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))])), @@ -1028,6 +1156,149 @@ 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 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(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)); + } + 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 }; + 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)]); + 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 +/// 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 @@ -1085,13 +1356,24 @@ 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> { 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)) } @@ -1322,9 +1604,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 a6c24e5da0..5440f5aaa4 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1129,6 +1129,143 @@ 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![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(); + 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"); + // 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(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"); + } + } +} + +/// 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 /6 [ << /99 /F /10 0 >> ] >> ] >> /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()); + 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]); + 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"); + // 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 [ << >> ] >> "; + 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!("/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]; + 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 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]