Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Integration: line the layout's ink box up with the TySh ink box (#6094)

David Mannfd8a2856d42f
diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs
index ed050940c..43b99b6d4 100644
--- a/crates/text/src/psd.rs
+++ b/crates/text/src/psd.rs
@@ -412,11 +412,14 @@ pub fn refine_legacy_point_origin(layer: &mut TextLayer, dpi: f32, engine: &mut
if layer.transform != guessed {
return;
}
- let Some(bounds) = engine.layout(layer, dpi).bounds() else { return };
- if !bounds.iter().all(|v| v.is_finite()) {
+ // `boundingBox` is the tight ink box (Photoshop writes the layout box as `bounds`), so match
+ // it with the layout's ink, not its logical box: text whose ink starts below the ascent
+ // line (`...`, `_`, lowercase) would otherwise land too low.
+ let Some(ink) = crate::render::ink_bounds(&engine.layout(layer, dpi)) else { return };
+ if !ink.iter().all(|v| v.is_finite()) {
return;
}
- let corrected = t.transform.mul(&Affine::translate(x - f64::from(bounds[0]), y - f64::from(bounds[1])));
+ let corrected = t.transform.mul(&Affine::translate(x - ink[0], y - ink[1]));
if corrected.m.iter().all(|v| v.is_finite()) {
layer.transform = corrected;
// A valid frame can coincide with the initial estimate; numeric equality cannot tell
diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs
index fe32982d9..963fe08c8 100644
--- a/crates/text/src/render.rs
+++ b/crates/text/src/render.rs
@@ -287,6 +287,14 @@ fn rect_from_bounds([x0, y0, x1, y1]: [f64; 4]) -> Rect {
Rect::new(x0 as i32, y0 as i32, x1 as i32, y1 as i32)
}
+/// Text-space bounds of the drawn glyph outlines and decorations, unrounded (`[x0, y0, x1, y1]`),
+/// or `None` when nothing is drawn.
+pub fn ink_bounds(layout: &TextLayout) -> Option<[f64; 4]> {
+ let mut b = Bounds::default();
+ draw(layout, &Xform::IDENTITY, &mut b, None, None);
+ b.rect
+}
+
/// [`ink_rect`] of warped text.
pub fn ink_rect_warped(layout: &TextLayout, transform: &Affine, warp: Option<&Warp>) -> Rect {
let mut b = Bounds::default();
diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs
index 30a892a67..0267199bf 100644
--- a/crates/text/src/tests.rs
+++ b/crates/text/src/tests.rs
@@ -1650,69 +1650,79 @@ fn psd_round_trips_antialias_opentype_and_warp() {
}
}
+/// A legacy-signature `TySh` (#1469): zero PointBase, `bounds` (the layout box) and `boundingBox`
+/// (the ink box, as Photoshop writes it) both around `anchor` in a remote local space, and a
+/// `transform` that cancels the remote origin.
+fn legacy_tysh(source: &TextLayer, transform: Affine, anchor: [f64; 2], engine: &mut TextEngine) -> Vec<u8> {
+ use photocraft_psd::descriptor::{Descriptor, Id, Value as D};
+ let layout = engine.layout(source, 72.0);
+ let logical = layout.bounds().unwrap().map(f64::from);
+ let ink = crate::render::ink_bounds(&layout).unwrap();
+ let rect = |class, r: [f64; 4]| {
+ D::Descriptor(
+ Descriptor::new(class)
+ .with("Left", D::UnitFloat { unit: *b"#Pnt", value: anchor[0] + r[0] })
+ .with("Top ", D::UnitFloat { unit: *b"#Pnt", value: anchor[1] + r[1] })
+ .with("Rght", D::UnitFloat { unit: *b"#Pnt", value: anchor[0] + r[2] })
+ .with("Btom", D::UnitFloat { unit: *b"#Pnt", value: anchor[1] + r[3] }),
+ )
+ };
+ let mut tysh = crate::psd::parse_tysh(&crate::psd::build_tysh(source, 72.0, None)).unwrap();
+ tysh.transform = transform;
+ tysh.text.items.retain(|(key, _)| !key.is("bounds") && !key.is("boundingBox"));
+ tysh.text.items.push((Id::new("bounds"), rect("bounds", logical)));
+ tysh.text.items.push((Id::new("boundingBox"), rect("boundingBox", ink)));
+ crate::psd::write_tysh(&tysh)
+}
+
+fn assert_transform_near(got: Affine, want: Affine, tolerance: f64, what: &str) {
+ assert!(got.m.iter().zip(want.m).all(|(g, w)| (g - w).abs() < tolerance), "{what}: {:?} vs {:?}", got.m, want.m);
+}
+
/// #1469: Some older PSD writers combine a zero PointBase with an enormous local ink origin.
-/// Recover the saved ink origin relative to style-aware layout bounds, so point alignment anchors
-/// stay fixed for left, centered and right text through import and a TySh round trip.
+/// The layout's own ink box is lined up with the saved ink box, so point alignment anchors stay
+/// fixed for left, centered and right text through import and a TySh round trip.
#[test]
fn legacy_tysh_point_origin_imports_and_round_trips_on_canvas() {
- use photocraft_psd::descriptor::{Descriptor, Id, Value as D};
+ use photocraft_psd::descriptor::Value as D;
let original = Affine { m: [4.1667, 0.0, 0.0, 4.1667, -32375.0, -32887.5] };
- let saved_ink_origin = [8050.0, 8160.0];
+ // The file's layout origin (the anchor on the first baseline) in its local space.
+ let anchor = [8050.0, 8160.0];
+ let expected = original.mul(&Affine::translate(anchor[0], anchor[1]));
for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] {
let mut source = styled("Name", CharStyle { font_family: "Inter".into(), size_pt: 120.0, ..Default::default() });
source.paragraphs = vec![ParagraphRun { len: source.text.len(), style: ParagraphStyle { align, ..Default::default() } }];
- let native = TextEngine::new().layout(&source, 72.0).bounds().unwrap();
- let saved_ink = [
- saved_ink_origin[0],
- saved_ink_origin[1],
- saved_ink_origin[0] + f64::from(native[2] - native[0]),
- saved_ink_origin[1] + f64::from(native[3] - native[1]),
- ];
- let rect = |class| {
- D::Descriptor(
- Descriptor::new(class)
- .with("Left", D::UnitFloat { unit: *b"#Pnt", value: saved_ink[0] })
- .with("Top ", D::UnitFloat { unit: *b"#Pnt", value: saved_ink[1] })
- .with("Rght", D::UnitFloat { unit: *b"#Pnt", value: saved_ink[2] })
- .with("Btom", D::UnitFloat { unit: *b"#Pnt", value: saved_ink[3] }),
- )
- };
- let mut tysh = crate::psd::parse_tysh(&crate::psd::build_tysh(&source, 72.0, None)).unwrap();
- tysh.transform = original;
- 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 mut engine = TextEngine::new();
+ let data = legacy_tysh(&source, original, anchor, &mut engine);
let mut imported = crate::psd::text_layer_from_tysh(&data, 72.0).unwrap();
imported.psd_raw = Some(std::sync::Arc::new(data.clone()));
- let mut engine = TextEngine::new();
crate::psd::refine_legacy_point_origin(&mut imported, 72.0, &mut engine, None);
assert_eq!(imported.paragraph_runs()[0].style.align, align);
- let expected_anchor = original.apply(photocraft_geom::Point::new(saved_ink_origin[0], saved_ink_origin[1]));
- let recovered_ink = imported.transform.apply(photocraft_geom::Point::new(f64::from(native[0]), f64::from(native[1])));
- assert!((recovered_ink.x - expected_anchor.x).abs() < 0.001, "{align:?}: {recovered_ink:?} vs {expected_anchor:?}");
- assert!((recovered_ink.y - expected_anchor.y).abs() < 0.001, "{align:?}: {recovered_ink:?} vs {expected_anchor:?}");
+ assert_transform_near(imported.transform, expected, 1e-6, &format!("{align:?}: anchor"));
let (_, rendered) = engine.render(&imported, 72.0, PixelFormat::RGBA8);
let placed = rendered.surface.content_bounds();
assert!(!placed.is_empty(), "{align:?}: no rendered pixels");
- let mut expected = source.clone();
- expected.transform = original.mul(&Affine::translate(saved_ink_origin[0] - f64::from(native[0]), saved_ink_origin[1] - f64::from(native[1])));
- let (_, expected_pixels) = engine.render(&expected, 72.0, PixelFormat::RGBA8);
+ let mut want = source.clone();
+ want.transform = expected;
+ let (_, expected_pixels) = engine.render(&want, 72.0, PixelFormat::RGBA8);
assert_eq!(placed, expected_pixels.surface.content_bounds(), "{align:?}: raster placement");
- let round_trip_data = crate::psd::build_tysh(&imported, 72.0, Some(native));
- let round_trip = crate::psd::text_layer_from_tysh(&round_trip_data, 72.0).unwrap();
- let round_trip_ink = TextEngine::new().layout(&round_trip, 72.0).bounds().unwrap();
- let round_trip_origin = round_trip.transform.apply(photocraft_geom::Point::new(f64::from(round_trip_ink[0]), f64::from(round_trip_ink[1])));
- assert!((round_trip_origin.x - expected_anchor.x).abs() < 1.0, "{align:?}: {round_trip_origin:?}");
- assert!((round_trip_origin.y - expected_anchor.y).abs() < 1.0, "{align:?}: {round_trip_origin:?}");
+ let native = engine.layout(&imported, 72.0).bounds();
+ let round_trip = crate::psd::text_layer_from_tysh(&crate::psd::build_tysh(&imported, 72.0, native), 72.0).unwrap();
+ assert_transform_near(round_trip.transform, expected, 0.01, &format!("{align:?}: round trip"));
// A valid frame may equal the old ink-corner estimate. It must still win over refinement.
+ let t = crate::psd::parse_tysh(&data).unwrap();
+ let Some(D::Descriptor(ink_box)) = t.text.get("boundingBox") else { panic!("boundingBox") };
+ let corner = |k| match ink_box.get(k) {
+ Some(D::UnitFloat { value, .. }) => *value,
+ _ => panic!("{k}"),
+ };
let framed = with_text_index(&data, 0);
- let txt2 = crate::psd::parse_txt2(&txt2_with_frame("Name", Some(saved_ink_origin), [1.0, 0.0, 0.0, 1.0, 0.0, 0.0])).unwrap();
+ let txt2 = crate::psd::parse_txt2(&txt2_with_frame("Name", Some([corner("Left"), corner("Top ")]), [1.0, 0.0, 0.0, 1.0, 0.0, 0.0])).unwrap();
let mut with_frame = crate::psd::text_layer_from_tysh(&framed, 72.0).unwrap();
with_frame.psd_raw = Some(std::sync::Arc::new(framed.clone()));
crate::psd::apply_txt2_frame(&mut with_frame, &framed, &txt2);
@@ -1722,6 +1732,25 @@ fn legacy_tysh_point_origin_imports_and_round_trips_on_canvas() {
}
}
+/// #6094 review: `boundingBox` is the tight ink box (a Photoshop-saved Arial 120 pt "..." has
+/// `bounds` top -102.98 but `boundingBox` top -11). Text whose ink starts well below the ascent
+/// line keeps its baseline: lining the layout box up with the ink box put "..." and "_" about
+/// 116 pt too low.
+#[test]
+fn legacy_origin_lines_up_ink_with_the_ink_bounding_box() {
+ let original = Affine { m: [1.0, 0.0, 0.0, 1.0, -7900.0, -7550.0] };
+ for text in ["Name", "...", "_"] {
+ let source = styled(text, CharStyle { font_family: "Inter".into(), size_pt: 120.0, ..Default::default() });
+ let mut engine = TextEngine::new();
+ let data = legacy_tysh(&source, original, [8000.0, 8000.0], &mut engine);
+ let mut imported = crate::psd::text_layer_from_tysh(&data, 72.0).unwrap();
+ imported.psd_raw = Some(std::sync::Arc::new(data));
+ crate::psd::refine_legacy_point_origin(&mut imported, 72.0, &mut engine, None);
+ let baseline = imported.transform.apply(photocraft_geom::Point::new(0.0, 0.0));
+ assert!((baseline.x - 100.0).abs() < 1e-6 && (baseline.y - 450.0).abs() < 1e-6, "{text:?}: {baseline:?}");
+ }
+}
+
#[test]
fn legacy_origin_uses_the_rendering_engines_registered_face() {
let mut engine = TextEngine::new();
@@ -1730,25 +1759,15 @@ fn legacy_origin_uses_the_rendering_engines_registered_face() {
engine.fonts.select_named_face(&mut style);
assert!(style.font_family.starts_with(".PhotoCraft-face-"));
let source = with_para(styled("Name", style), ParagraphStyle { align: TextAlign::Right, ..Default::default() });
- let native = engine.layout(&source, 72.0).bounds().unwrap();
- let mut t = crate::psd::parse_tysh(&crate::psd::build_tysh(&source, 72.0, None)).unwrap();
- t.transform = Affine::translate(-8000.0, -8000.0);
- let saved = [8100.0, 8200.0, 8100.0 + f64::from(native[2] - native[0]), 8200.0 + f64::from(native[3] - native[1])];
- let raw = with_bounds(&crate::psd::write_tysh(&t), saved);
- let mut t = crate::psd::parse_tysh(&raw).unwrap();
- let bounds = t.text.get("bounds").unwrap().clone();
- t.text.items.retain(|(k, _)| !k.is("boundingBox"));
- t.text.items.push((photocraft_psd::descriptor::Id::new("boundingBox"), bounds));
- let raw = crate::psd::write_tysh(&t);
+ let raw = legacy_tysh(&source, Affine::translate(-8000.0, -8000.0), [8100.0, 8200.0], &mut engine);
let mut imported = crate::psd::text_layer_from_tysh(&raw, 72.0).unwrap();
// Import preparation has resolved the face before refining placement.
imported.runs = source.runs.clone();
imported.sync_summary();
imported.psd_raw = Some(std::sync::Arc::new(raw));
crate::psd::refine_legacy_point_origin(&mut imported, 72.0, &mut engine, None);
- let bounds = engine.layout(&imported, 72.0).bounds().unwrap();
- let placed = imported.transform.apply(photocraft_geom::Point::new(f64::from(bounds[0]), f64::from(bounds[1])));
- assert!((placed.x - 100.0).abs() < 0.001 && (placed.y - 200.0).abs() < 0.001, "{placed:?}");
+ let placed = imported.transform.apply(photocraft_geom::Point::new(0.0, 0.0));
+ assert!((placed.x - 100.0).abs() < 1e-6 && (placed.y - 200.0).abs() < 1e-6, "{placed:?}");
}
/// Regression: a PSD whose text engine data has no `EngineDict` (or isn't a dictionary)