From 6e471d298875920a411cdcf43a139b3c0a54ccf9 Mon Sep 17 00:00:00 2001 From: Rozaq Date: Fri, 9 Oct 2026 09:10:32 +0700 Subject: [PATCH 1/2] fix: keep legacy PSD text origins visible when editing --- crates/ui-egui/src/type_tool.rs | 35 ++++++++++++++++++++++++--- crates/ui-egui/src/type_tool_tests.rs | 25 +++++++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index bfd4f41851..6a831333a1 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -74,11 +74,31 @@ fn hit_layer(app: &mut PhotocraftApp, x: f64, y: f64) -> Option { /// Photoshop's pixels until it is edited, and with substituted fonts or a different line layout /// they sit somewhere else than the glyphs the caret and selection are placed on. fn shows_own_layout(doc: &Document, t: &TextLayer) -> bool { - let Some(cache) = &t.cache else { return false }; - let Ok(mut eng) = photocraft_text::shared().lock() else { return true }; + let Some((ours, have)) = layout_and_cache_bounds(doc, t) else { return false }; + [(ours.x0, have.x0), (ours.y0, have.y0), (ours.x1, have.x1), (ours.y1, have.y1)].iter().all(|(a, b)| (a - b).abs() <= 1) +} + +/// The bounds of PhotoCraft's text layout and the Photoshop pixels retained from an imported PSD. +fn layout_and_cache_bounds(doc: &Document, t: &TextLayer) -> Option<(photocraft_geom::Rect, photocraft_geom::Rect)> { + let cache = t.cache.as_ref()?; + let Ok(mut eng) = photocraft_text::shared().lock() else { return None }; let ours = eng.render(t, doc.resolution_dpi, doc.pixel_format()).1.surface.content_bounds(); let have = cache.content_bounds(); - [(ours.x0, have.x0), (ours.y0, have.y0), (ours.x1, have.x1), (ours.y1, have.y1)].iter().all(|(a, b)| (a - b).abs() <= 1) + (!ours.is_empty() && !have.is_empty()).then_some((ours, have)) +} + +/// Some PSDs use a legacy text origin that puts the TySh translation far outside the canvas. +/// Their cached Photoshop pixels are correctly positioned, but replacing that cache on the first +/// edit makes the text appear to jump away. Keep the existing linear transform and translate the +/// internal layout back onto the cached pixels before beginning the edit. +fn cached_text_alignment(doc: &Document, t: &TextLayer) -> Option<[f64; 2]> { + let (ours, have) = layout_and_cache_bounds(doc, t)?; + let delta = [f64::from(have.x0 - ours.x0), f64::from(have.y0 - ours.y0)]; + let canvas = photocraft_geom::Rect::from_size(doc.size); + // Font substitution can shift glyph bounds by a few pixels; retain the ordinary behaviour in + // that case. The legacy origin is distinguishable because our layout is entirely off-canvas + // while Photoshop's retained pixels are visible on it. + (canvas.intersect(&ours).is_empty() && !canvas.intersect(&have).is_empty() && delta.iter().all(|v| v.is_finite())).then_some(delta) } /// Start editing an existing type layer. Like Photoshop, editing shows the text as the type @@ -90,7 +110,14 @@ fn begin_edit(app: &mut PhotocraftApp, id: LayerId, key: &str) -> Result<(), Str if let Some(t) = text_layer(&doc, id) && !shows_own_layout(&doc, t) { - app.run("type.edit", json!({"layer": id.0, "coalesce": key}))?; + let mut params = json!({"layer": id.0, "coalesce": key}); + if let Some([dx, dy]) = cached_text_alignment(&doc, t) { + let mut transform = t.transform.m; + transform[4] += dx; + transform[5] += dy; + params["transform"] = json!(transform); + } + app.run("type.edit", params)?; } Ok(()) } diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index 9c8d4c8654..c8b232dd96 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -198,6 +198,31 @@ fn editing_psd_type_shows_our_layout_and_cancel_restores_it() { assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps); } +/// PSDs can carry a legacy TySh origin far outside the document while their retained Photoshop +/// pixels are in the right place. Entering Type mode must align the replacement layout to those +/// pixels instead of making the text disappear off-canvas (#1469). +#[test] +fn editing_psd_type_with_a_legacy_origin_stays_on_its_cached_pixels() { + let mut app = new_app(); + let id = LayerId(app.run("type.create", json!({"text": "Name", "size": 120, "x": 300, "y": 420})).unwrap()["layer"].as_u64().unwrap()); + let expected = text(&app, id).cache.unwrap(); + let hit = expected.content_bounds(); + + let st = app.session.active_mut().unwrap(); + let mut doc = (*st.doc).clone(); + if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) { + t.transform = Affine { m: [1.0, 0.0, 0.0, 1.0, -32375.0, -32887.5] }; + t.cache = Some(expected.clone()); + } + st.doc = std::sync::Arc::new(doc); + st.revision += 1; + + assert!(super::pointer_down(&mut app, f64::from(hit.x0 + 1), f64::from(hit.y0 + 1), false)); + let repaired = text(&app, id); + assert_eq!(repaired.cache.unwrap().content_bounds(), hit); + assert!(repaired.transform.m[4] > 0.0 && repaired.transform.m[5] > 0.0, "{:?}", repaired.transform.m); +} + fn size_at(app: &PhotocraftApp, id: LayerId, ci: usize) -> f32 { let t = text(app, id); let b = t.text.char_indices().nth(ci).map_or(t.text.len(), |(b, _)| b); From 00ca258dc43bce19140aea7100e79069ac2874d9 Mon Sep 17 00:00:00 2001 From: Rozaq Date: Fri, 9 Oct 2026 13:15:55 +0700 Subject: [PATCH 2/2] fix: normalize legacy TySh origins on import --- crates/text/src/psd.rs | 47 +++++++++++++++++++++++++++ crates/text/src/tests.rs | 42 ++++++++++++++++++++++++ crates/ui-egui/src/type_tool.rs | 37 +++------------------ crates/ui-egui/src/type_tool_tests.rs | 25 -------------- 4 files changed, 94 insertions(+), 57 deletions(-) diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 1f32fbefa8..0e368a997e 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -221,10 +221,57 @@ pub fn text_layer_from_tysh(data: &[u8], dpi: f32) -> Option { } else { layer.text = txt.unwrap_or_default().replace('\r', "\n"); } + // Some legacy PSDs store point text at a large local origin even though PointBase is zero. + // Their transform maps that origin onto the canvas, but maps our zero-based layout far away. + // Move the imported layout to the descriptor's ink origin so editing, engine commands, and + // writing the TySh all agree on the visible position (#1469). + if let Some([x, y]) = legacy_point_origin(&t) { + let [a, b, c, d, e, f] = layer.transform.m; + layer.transform.m = [a, b, c, d, a * x + c * y + e, b * x + d * y + f]; + } layer.sync_summary(); Some(layer) } +/// The local origin to fold into a legacy point-text transform, if present. +/// +/// Photoshop normally keeps point text close to its PointBase. The affected legacy files instead +/// use a zero PointBase plus a very large `boundingBox` origin, with an equally remote transform +/// translation that cancels it out. Do not apply this to ordinary point text: its transform origin +/// is already the layout origin, and shifting it by the ink bounds would move the layer. +fn legacy_point_origin(t: &TySh) -> Option<[f64; 2]> { + let e = engine_data(&t.text)?; + let point_base = e + .path(&["EngineDict", "Rendered", "Shapes", "Children"]) + .and_then(E::as_array) + .and_then(|children| children.first()) + .and_then(|shape| shape.path(&["Cookie", "Photoshop", "PointBase"])) + .and_then(E::as_array)?; + let [px, py] = point_base else { return None }; + if px.as_f64() != Some(0.0) || py.as_f64() != Some(0.0) { + return None; + } + let bounds = descriptor_rect(&t.text, "boundingBox")?; + let [a, b, c, d, e, f] = t.transform.m; + let values = [a, b, c, d, e, f, bounds[0], bounds[1]]; + if !values.iter().all(|v| v.is_finite()) { + return None; + } + let shifted = [a * bounds[0] + c * bounds[1] + e, b * bounds[0] + d * bounds[1] + f]; + let origin_distance = e.abs().max(f.abs()); + let shifted_distance = shifted[0].abs().max(shifted[1].abs()); + // A local bounding-box origin in the thousands and a transform origin beyond a normal canvas + // are the signature of this old writer. Requiring that the bounding-box origin is closer to + // the document prevents applying the correction again after export/import. + (bounds[0].abs().max(bounds[1].abs()) > 1024.0 && origin_distance > 4096.0 && shifted_distance < origin_distance).then_some([bounds[0], bounds[1]]) +} + +fn descriptor_rect(text: &Descriptor, key: &str) -> Option<[f64; 4]> { + let D::Descriptor(rect) = text.get(key)? else { return None }; + let bounds = [dnum(rect.get("Left"))?, dnum(rect.get("Top "))?, dnum(rect.get("Rght"))?, dnum(rect.get("Btom"))?]; + (bounds.iter().all(|v| v.is_finite()) && bounds[2] > bounds[0] && bounds[3] > bounds[1]).then_some(bounds) +} + pub(crate) fn arr_f(v: Option<&E>) -> Vec { v.and_then(E::as_array).map(|a| a.iter().filter_map(E::as_f64).collect()).unwrap_or_default() } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 5b107c7934..e4cf16cae8 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -600,6 +600,48 @@ fn psd_round_trips_antialias_opentype_and_warp() { } } +/// #1469: Some older PSD writers combine a zero PointBase with an enormous local ink origin. +/// The TySh transform cancels that origin, so importing it as a zero-based layout puts text far +/// off-canvas. Fold the descriptor origin into the imported transform and preserve it on a TySh +/// round trip so every editing and export path uses the same position. +#[test] +fn legacy_tysh_point_origin_imports_and_round_trips_on_canvas() { + use photocraft_psd::descriptor::{Descriptor, Id, Value as D}; + + let source = styled("Name", CharStyle { font_family: "Inter".into(), size_pt: 120.0, ..Default::default() }); + let mut tysh = crate::psd::parse_tysh(&crate::psd::build_tysh(&source, 72.0, None)).unwrap(); + tysh.transform = Affine { m: [4.1667, 0.0, 0.0, 4.1667, -32375.0, -32887.5] }; + let ink = [8050.0, 8160.0, 8220.0, 8300.0]; + let rect = |class| { + D::Descriptor( + Descriptor::new(class) + .with("Left", D::UnitFloat { unit: *b"#Pnt", value: ink[0] }) + .with("Top ", D::UnitFloat { unit: *b"#Pnt", value: ink[1] }) + .with("Rght", D::UnitFloat { unit: *b"#Pnt", value: ink[2] }) + .with("Btom", D::UnitFloat { unit: *b"#Pnt", value: ink[3] }), + ) + }; + tysh.text.items.retain(|(key, _)| !key.is("bounds") && !key.is("boundingBox")); + tysh.text.items.push((Id::new("bounds"), rect("bounds"))); + tysh.text.items.push((Id::new("boundingBox"), rect("boundingBox"))); + let data = crate::psd::write_tysh(&tysh); + + let imported = crate::psd::text_layer_from_tysh(&data, 72.0).unwrap(); + let expected = [4.1667, 0.0, 0.0, 4.1667, 1166.935, 1112.772]; + for (got, want) in imported.transform.m.iter().zip(expected) { + assert!((got - want).abs() < 0.001, "{:?}", imported.transform.m); + } + let (_, rendered) = TextEngine::new().render(&imported, 72.0, PixelFormat::RGBA8); + let placed = rendered.surface.content_bounds(); + assert!(!placed.is_empty(), "the normalized layer renders"); + assert!((1000..3000).contains(&placed.x0) && (500..2000).contains(&placed.y0), "{placed:?}"); + + let round_trip = crate::psd::text_layer_from_tysh(&crate::psd::build_tysh(&imported, 72.0, Some(ink.map(|v| v as f32))), 72.0).unwrap(); + for (got, want) in round_trip.transform.m.iter().zip(expected) { + assert!((got - want).abs() < 0.001, "{:?}", round_trip.transform.m); + } +} + /// Regression: a PSD whose text engine data has no `EngineDict` (or isn't a dictionary) /// panicked with `expect("EngineDict")` when the layer was written back (PSD export). #[test] diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 6a831333a1..e3fc52efdb 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -4,7 +4,7 @@ //! typing session is one "Edit Type" history step and automation sees exactly what the user does. //! Offsets in [`TextEdit`] are character indices (the engine's unit); the layout works in bytes. -use std::sync::Arc; +use std::sync::{Arc, PoisonError}; use egui::{Color32, Pos2, Stroke}; use photocraft_doc::{Document, LayerContent, LayerId, TextLayer}; @@ -74,31 +74,11 @@ fn hit_layer(app: &mut PhotocraftApp, x: f64, y: f64) -> Option { /// Photoshop's pixels until it is edited, and with substituted fonts or a different line layout /// they sit somewhere else than the glyphs the caret and selection are placed on. fn shows_own_layout(doc: &Document, t: &TextLayer) -> bool { - let Some((ours, have)) = layout_and_cache_bounds(doc, t) else { return false }; - [(ours.x0, have.x0), (ours.y0, have.y0), (ours.x1, have.x1), (ours.y1, have.y1)].iter().all(|(a, b)| (a - b).abs() <= 1) -} - -/// The bounds of PhotoCraft's text layout and the Photoshop pixels retained from an imported PSD. -fn layout_and_cache_bounds(doc: &Document, t: &TextLayer) -> Option<(photocraft_geom::Rect, photocraft_geom::Rect)> { - let cache = t.cache.as_ref()?; - let Ok(mut eng) = photocraft_text::shared().lock() else { return None }; + let Some(cache) = &t.cache else { return false }; + let mut eng = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner); let ours = eng.render(t, doc.resolution_dpi, doc.pixel_format()).1.surface.content_bounds(); let have = cache.content_bounds(); - (!ours.is_empty() && !have.is_empty()).then_some((ours, have)) -} - -/// Some PSDs use a legacy text origin that puts the TySh translation far outside the canvas. -/// Their cached Photoshop pixels are correctly positioned, but replacing that cache on the first -/// edit makes the text appear to jump away. Keep the existing linear transform and translate the -/// internal layout back onto the cached pixels before beginning the edit. -fn cached_text_alignment(doc: &Document, t: &TextLayer) -> Option<[f64; 2]> { - let (ours, have) = layout_and_cache_bounds(doc, t)?; - let delta = [f64::from(have.x0 - ours.x0), f64::from(have.y0 - ours.y0)]; - let canvas = photocraft_geom::Rect::from_size(doc.size); - // Font substitution can shift glyph bounds by a few pixels; retain the ordinary behaviour in - // that case. The legacy origin is distinguishable because our layout is entirely off-canvas - // while Photoshop's retained pixels are visible on it. - (canvas.intersect(&ours).is_empty() && !canvas.intersect(&have).is_empty() && delta.iter().all(|v| v.is_finite())).then_some(delta) + [(ours.x0, have.x0), (ours.y0, have.y0), (ours.x1, have.x1), (ours.y1, have.y1)].iter().all(|(a, b)| (a - b).abs() <= 1) } /// Start editing an existing type layer. Like Photoshop, editing shows the text as the type @@ -110,14 +90,7 @@ fn begin_edit(app: &mut PhotocraftApp, id: LayerId, key: &str) -> Result<(), Str if let Some(t) = text_layer(&doc, id) && !shows_own_layout(&doc, t) { - let mut params = json!({"layer": id.0, "coalesce": key}); - if let Some([dx, dy]) = cached_text_alignment(&doc, t) { - let mut transform = t.transform.m; - transform[4] += dx; - transform[5] += dy; - params["transform"] = json!(transform); - } - app.run("type.edit", params)?; + app.run("type.edit", json!({"layer": id.0, "coalesce": key}))?; } Ok(()) } diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index c8b232dd96..9c8d4c8654 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -198,31 +198,6 @@ fn editing_psd_type_shows_our_layout_and_cancel_restores_it() { assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps); } -/// PSDs can carry a legacy TySh origin far outside the document while their retained Photoshop -/// pixels are in the right place. Entering Type mode must align the replacement layout to those -/// pixels instead of making the text disappear off-canvas (#1469). -#[test] -fn editing_psd_type_with_a_legacy_origin_stays_on_its_cached_pixels() { - let mut app = new_app(); - let id = LayerId(app.run("type.create", json!({"text": "Name", "size": 120, "x": 300, "y": 420})).unwrap()["layer"].as_u64().unwrap()); - let expected = text(&app, id).cache.unwrap(); - let hit = expected.content_bounds(); - - let st = app.session.active_mut().unwrap(); - let mut doc = (*st.doc).clone(); - if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) { - t.transform = Affine { m: [1.0, 0.0, 0.0, 1.0, -32375.0, -32887.5] }; - t.cache = Some(expected.clone()); - } - st.doc = std::sync::Arc::new(doc); - st.revision += 1; - - assert!(super::pointer_down(&mut app, f64::from(hit.x0 + 1), f64::from(hit.y0 + 1), false)); - let repaired = text(&app, id); - assert_eq!(repaired.cache.unwrap().content_bounds(), hit); - assert!(repaired.transform.m[4] > 0.0 && repaired.transform.m[5] > 0.0, "{:?}", repaired.transform.m); -} - fn size_at(app: &PhotocraftApp, id: LayerId, ci: usize) -> f32 { let t = text(app, id); let b = t.text.char_indices().nth(ci).map_or(t.text.len(), |(b, _)| b);