PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(psd): write complete Txt2 style runs from the layer, number only file indices as kept
NetterSilver20c9103148e3
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 4350ffd06..419f9156f 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.rsindex 9c5e3dd8c..6eeebc43b 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<u8> {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<i32>, Vec<String>) {+/// 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<i32>, Vec<String>)>, 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<i32>, Vec<String>)], name: &str) -> &'a (String, Option<i32>, Vec<String>) {+ 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 regenerateddiff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rsindex 828a50a0a..6d8fd8f45 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<E>) {+ 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<E>, dpi: f32) -> Option<Vec<E>> {+ 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<E>, name: &str) -> Option<i64> {+ 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<u8> {+ 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<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> = prev_objects.to_vec();+ 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// 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<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))),+ // 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<u8>};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.rsindex 95d8902e0..5c18460b0 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]