mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
PSD: type on a path opens on its path and saves back into the file's Txt2 (#7962)
Photoshop keeps a path-text layer's path only in its Txt2 frame (EngineData calls it a text box the size of the path's bounds), so it opened as paragraph text. The frame (kind /2 /0 = 2) holds the path as a flat list of cubic segments at /1 /0, mapped to the TySh text space by /2 /2. apply_txt2_path reads it into TextShape::Path (a closed path starting at its last anchor, as Photoshop sets it); malformed or hostile frames keep the box/point shape with an import warning. build_txt2 writes a path layer's path into its object's frame (Photoshop's own frame left byte for byte when the path is unchanged; flip and a moved start written into the path), and a layer taken off its path loses its path frame. A new document still saves path text as point text. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
b097800e78
commit
020784da62
8 files changed
+697
-24
No files matched your search
@@ -368,10 +368,17 @@ impl Ctx<'_> {
|
||||
let (text, transform) = blocks::parse_tysh(&data).unwrap_or_default();
|
||||
TextLayer { text, transform, ..Default::default() }
|
||||
});
|
||||
let mut path_error = None;
|
||||
if let Some(txt2) = &self.txt2 {
|
||||
photocraft_text::psd::apply_txt2(&mut t, &data, txt2);
|
||||
// Type on a path keeps its path only in its `Txt2` frame (#7962).
|
||||
path_error = photocraft_text::psd::apply_txt2_path(&mut t, &data, txt2).err();
|
||||
photocraft_text::psd::apply_txt2_frame(&mut t, &data, txt2);
|
||||
}
|
||||
if let Some(e) = path_error {
|
||||
let shape = if matches!(t.shape, photocraft_doc::text::TextShape::Box { .. }) { "paragraph" } else { "point" };
|
||||
self.warn(format!("layer \"{name}\": its type path could not be read ({e}); it opens as {shape} text"));
|
||||
}
|
||||
// Photoshop's pixels are the cache only when the file has some: ag-psd, GIMP and
|
||||
// other writers leave type layers without image data (Photoshop re-renders them on
|
||||
// open), and an empty cache would show nothing until the layer is edited; the import
|
||||
|
||||
@@ -169,6 +169,97 @@ fn corpus_photoshop_txt2_survives_an_unedited_save() {
|
||||
println!("Txt2 kept byte-for-byte in {checked} Photoshop type files");
|
||||
}
|
||||
|
||||
/// #7962: Photoshop's type on a path (`Txt2` frames, EngineData calls it a text box) opens on its
|
||||
/// path, at the anchors the generator gave Photoshop; the circle re-renders where Photoshop drew
|
||||
/// it; and a save after an edit (new text, a moved path) reopens on the layer's path.
|
||||
#[cfg(feature = "corpus")]
|
||||
#[test]
|
||||
fn corpus_photoshop_path_text_opens_on_its_path() {
|
||||
use photocraft_doc::text::TextShape;
|
||||
use photocraft_geom::Point;
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/photoshop/text");
|
||||
let k = 0.5522847498 * 96.0;
|
||||
let cases: [(&str, bool, Vec<[f64; 2]>); 2] = [
|
||||
// Photoshop sets the type from the closed path's last anchor (the bottom).
|
||||
("path-circle.psd", true, vec![[128.0, 224.0], [32.0, 128.0], [128.0, 32.0], [224.0, 128.0]]),
|
||||
("path-wave-open.psd", false, vec![[16.0, 100.0], [160.0, 80.0], [304.0, 60.0]]),
|
||||
];
|
||||
let mut engine = photocraft_text::TextEngine::with_system_fonts();
|
||||
for (file, closed, anchors) in cases {
|
||||
let f = root.join(file);
|
||||
let bytes = std::fs::read(&f).unwrap_or_else(|e| panic!("{}: {e}: run `cargo xtask corpus --photoshop`", f.display()));
|
||||
let imp = photocraft_io::import(file, &bytes).unwrap();
|
||||
assert!(!imp.warnings.iter().any(|w| w.contains("type path")), "{file}: {:?}", imp.warnings);
|
||||
let doc = imp.document;
|
||||
let mut all = Vec::new();
|
||||
walk(&doc.layers, &mut all);
|
||||
let layer = all.iter().find(|l| matches!(l.content, LayerContent::Text(_))).unwrap();
|
||||
let LayerContent::Text(t) = &layer.content else { unreachable!() };
|
||||
let doc_anchors = |t: &photocraft_doc::TextLayer| -> Vec<Point> {
|
||||
let TextShape::Path { path, start, flip } = &t.shape else { panic!("{file}: not path text: {:?}", t.shape) };
|
||||
assert_eq!((path.closed, *start, *flip), (closed, 0.0, false), "{file}");
|
||||
path.knots.iter().map(|k| t.transform.apply(k.anchor)).collect()
|
||||
};
|
||||
let got = doc_anchors(t);
|
||||
assert_eq!(got.len(), anchors.len(), "{file}");
|
||||
for (g, [x, y]) in got.iter().zip(&anchors) {
|
||||
assert!((g.x - x).abs() < 1e-3 && (g.y - y).abs() < 1e-3, "{file}: anchor {g:?}, want ({x}, {y})");
|
||||
}
|
||||
if closed {
|
||||
// The circle's handles are the generator's (kappa × r), so the path is the circle.
|
||||
let TextShape::Path { path, .. } = &t.shape else { unreachable!() };
|
||||
let h = t.transform.apply(path.knots[0].out_ctrl);
|
||||
assert!((h.x - (128.0 - k)).abs() < 1e-3 && (h.y - 224.0).abs() < 1e-3, "{file}: handle {h:?}");
|
||||
}
|
||||
|
||||
// Photoshop's pixels (the wave's EngineData text is blank: Photoshop drew nothing).
|
||||
if let Some(ps) = t.cache.as_ref().filter(|c| !c.content_bounds().is_empty()) {
|
||||
let ps_rect = ps.content_bounds();
|
||||
let (_, ours) = engine.render(t, doc.resolution_dpi, doc.pixel_format());
|
||||
let our_rect = ours.surface.content_bounds();
|
||||
let u = Rect::new(ps_rect.x0.min(our_rect.x0), ps_rect.y0.min(our_rect.y0), ps_rect.x1.max(our_rect.x1), ps_rect.y1.max(our_rect.y1));
|
||||
let (a, b) = (alpha(ps, u), alpha(&ours.surface, u));
|
||||
let inter: f32 = a.iter().zip(&b).map(|(x, y)| x.min(*y)).sum();
|
||||
let union: f32 = a.iter().zip(&b).map(|(x, y)| x.max(*y)).sum();
|
||||
let iou = if union > 0.0 { inter / union } else { 1.0 };
|
||||
let edges = [ps_rect.x0 - our_rect.x0, ps_rect.y0 - our_rect.y0, ps_rect.x1 - our_rect.x1, ps_rect.y1 - our_rect.y1];
|
||||
println!("{file}: ps={ps_rect:?} ours={our_rect:?} iou={iou:.2} edges={edges:?}");
|
||||
assert!(edges.iter().all(|d| d.abs() <= 8), "{file}: ink bounds {our_rect:?}, Photoshop's {ps_rect:?}");
|
||||
assert!(iou > 0.2, "{file}: the glyphs sit where Photoshop drew them (IoU {iou:.2})");
|
||||
}
|
||||
|
||||
// Edited: new text and the path moved 10 px right; saved and opened again.
|
||||
let mut edited = doc.clone();
|
||||
let id = layer.id;
|
||||
for l in edited.layers.iter_mut() {
|
||||
if l.id != id {
|
||||
continue;
|
||||
}
|
||||
let LayerContent::Text(t) = &mut l.content else { continue };
|
||||
t.text = format!("{} again", t.text);
|
||||
if let Some(r) = t.runs.last_mut() {
|
||||
r.len += " again".len();
|
||||
}
|
||||
t.sync_summary();
|
||||
if let TextShape::Path { path, .. } = &mut t.shape {
|
||||
for k in &mut path.knots {
|
||||
*k = k.transform(&photocraft_geom::Affine::translate(10.0, 0.0));
|
||||
}
|
||||
}
|
||||
t.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::build_tysh(t, edited.resolution_dpi, None)));
|
||||
}
|
||||
let out = photocraft_io::export(&edited, file, &Default::default()).unwrap().bytes;
|
||||
let back = photocraft_io::import(file, &out).unwrap().document;
|
||||
let mut all = Vec::new();
|
||||
walk(&back.layers, &mut all);
|
||||
let LayerContent::Text(bt) = &all.iter().find(|l| matches!(l.content, LayerContent::Text(_))).unwrap().content else { unreachable!() };
|
||||
assert!(bt.text.ends_with(" again"), "{file}: {:?}", bt.text);
|
||||
for (g, [x, y]) in doc_anchors(bt).iter().zip(&anchors) {
|
||||
assert!((g.x - (x + 10.0)).abs() < 1e-3 && (g.y - y).abs() < 1e-3, "{file}: saved anchor {g:?}, want ({}, {y})", x + 10.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A text layer created in PhotoCraft (no PSD data) exports as an editable type layer and
|
||||
/// imports back with the same model.
|
||||
#[test]
|
||||
|
||||
@@ -24,6 +24,7 @@ pub mod glyphs;
|
||||
pub mod layout;
|
||||
pub mod optical;
|
||||
pub mod psd;
|
||||
mod psd_path;
|
||||
pub mod psd_styles;
|
||||
pub mod raster;
|
||||
pub mod render;
|
||||
|
||||
+74
-20
@@ -214,12 +214,59 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) {
|
||||
layer.sync_summary();
|
||||
}
|
||||
|
||||
/// The frame (`Txt2 /0 /8 /0` entry) of text object `index`: its rendered frame's `/10` names it.
|
||||
fn txt2_frame(txt2: &E, index: usize) -> Option<&E> {
|
||||
/// The frame (`Txt2 /0 /8 /0` entry) of text object `index`: its rendered frame's `/10` names it
|
||||
/// (with `named`, else the frame its view names; see [`object_frame`]).
|
||||
fn txt2_frame(txt2: &E, index: usize, named: bool) -> Option<&E> {
|
||||
let object = txt2.path(&["1", "1"]).and_then(E::as_array)?.get(index)?;
|
||||
let frame =
|
||||
object.path(&["1", "2"]).and_then(E::as_array)?.first()?.get("6").and_then(E::as_array)?.iter().find_map(|f| f.get("10").and_then(E::as_i64))?;
|
||||
txt2.path(&["0", "8", "0"]).and_then(E::as_array)?.get(usize::try_from(frame).ok()?)?.get("0")
|
||||
txt2.path(&["0", "8", "0"]).and_then(E::as_array)?.get(object_frame(object, named)?)?.get("0")
|
||||
}
|
||||
|
||||
/// The number of the frame the text object `object` is drawn in: its rendered frame's `/10`, else
|
||||
/// (with `named`) the frame its view names (`/1 /0 [ << /0 n >> ]`). Photoshop leaves the rendered
|
||||
/// strikes out for type it did not lay out (`text/path-wave-open.psd`, whose EngineData text is
|
||||
/// blank).
|
||||
fn object_frame(object: &E, named: bool) -> Option<usize> {
|
||||
let rendered = object
|
||||
.path(&["1", "2"])
|
||||
.and_then(E::as_array)
|
||||
.and_then(|s| s.first())
|
||||
.and_then(|s| s.get("6"))
|
||||
.and_then(E::as_array)
|
||||
.and_then(|parts| parts.iter().find_map(|f| f.get("10").and_then(E::as_i64)));
|
||||
let view = || named.then(|| object.path(&["1", "0"]).and_then(E::as_array).and_then(|f| f.first()).and_then(|f| f.get("0")).and_then(E::as_i64)).flatten();
|
||||
usize::try_from(rendered.or_else(view)?).ok()
|
||||
}
|
||||
|
||||
/// The `TySh` of `tysh` and the `Txt2` frame of its text object (`named`: see [`object_frame`]),
|
||||
/// when that object still holds `layer`'s text (an edit elsewhere leaves `Txt2` stale).
|
||||
fn layer_frame<'a>(layer: &TextLayer, tysh: &[u8], txt2: &'a E, named: bool) -> Option<(TySh, &'a E)> {
|
||||
let t = parse_tysh(tysh)?;
|
||||
let index = match t.text.get("TextIndex") {
|
||||
Some(D::Integer(i)) => usize::try_from(*i).ok()?,
|
||||
_ => return None,
|
||||
};
|
||||
let text = txt2.path(&["1", "1"]).and_then(E::as_array).and_then(|a| a.get(index)).and_then(|o| o.path(&["0", "0"])).and_then(E::as_str)?;
|
||||
if text.strip_suffix('\r').unwrap_or(text).replace('\r', "\n") != layer.text {
|
||||
return None;
|
||||
}
|
||||
let frame = txt2_frame(txt2, index, named)?;
|
||||
Some((t, frame))
|
||||
}
|
||||
|
||||
/// Puts `layer` on its path when its `Txt2` frame is type on a path (#7962): Photoshop keeps the
|
||||
/// path only there, and EngineData describes the layer as a text box the size of the path's
|
||||
/// bounds. The path is read into the `TySh` text space, the type starting where Photoshop starts
|
||||
/// it (see `psd_path`). `Ok(true)` when the layer is now path text, `Ok(false)` when its frame is
|
||||
/// no path (or `Txt2` holds another text for it), `Err` with the reason when the path can't be
|
||||
/// read: the layer then stays the box or point text EngineData describes.
|
||||
pub fn apply_txt2_path(layer: &mut TextLayer, tysh: &[u8], txt2: &E) -> Result<bool, String> {
|
||||
let Some((_, frame)) = layer_frame(layer, tysh, txt2, true) else { return Ok(false) };
|
||||
if crate::psd_path::frame_kind(frame) != crate::psd_path::PATH_FRAME {
|
||||
return Ok(false);
|
||||
}
|
||||
let path = crate::psd_path::read(frame)?;
|
||||
layer.shape = TextShape::Path { path, start: 0.0, flip: false };
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Places `layer` where Photoshop draws it when the text object's frame in `Txt2` is moved
|
||||
@@ -231,18 +278,11 @@ fn txt2_frame(txt2: &E, index: usize) -> Option<&E> {
|
||||
/// alignment anchor. Only when the layer's `TextIndex` entry still holds the layer's text, as
|
||||
/// for [`apply_txt2`], and the frame agrees with the `TySh` `bounds`.
|
||||
pub fn apply_txt2_frame(layer: &mut TextLayer, tysh: &[u8], txt2: &E) {
|
||||
let Some(t) = parse_tysh(tysh) else { return };
|
||||
let Some(index) = (match t.text.get("TextIndex") {
|
||||
Some(D::Integer(i)) => usize::try_from(*i).ok(),
|
||||
_ => None,
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let text = txt2.path(&["1", "1"]).and_then(E::as_array).and_then(|a| a.get(index)).and_then(|o| o.path(&["0", "0"])).and_then(E::as_str);
|
||||
if text.is_none_or(|t| t.strip_suffix('\r').unwrap_or(t).replace('\r', "\n") != layer.text) {
|
||||
// Type on a path: [`apply_txt2_path`] already read the path through the frame's matrix.
|
||||
if matches!(layer.shape, TextShape::Path { .. }) {
|
||||
return;
|
||||
}
|
||||
let Some(frame) = txt2_frame(txt2, index) else { return };
|
||||
let Some((t, frame)) = layer_frame(layer, tysh, txt2, false) else { return };
|
||||
let m = arr_f(frame.path(&["2", "2"]));
|
||||
let matrix = if m.len() == 6 && m.iter().all(|v| v.is_finite()) { Affine { m: [m[0], m[1], m[2], m[3], m[4], m[5]] } } else { Affine::IDENTITY };
|
||||
let at = match layer.shape {
|
||||
@@ -1111,6 +1151,9 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi
|
||||
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());
|
||||
// The frame each written object is drawn in, with its layer's shape (type on a path lives
|
||||
// only in the frame, #7962).
|
||||
let mut frame_shapes: Vec<(usize, &TextShape)> = Vec::new();
|
||||
for (index, layer) in objects {
|
||||
if !(0..=MAX_TEXT_INDEX).contains(index) {
|
||||
continue;
|
||||
@@ -1162,6 +1205,9 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi
|
||||
_ => model.set("6", E::Dict(vec![("0".into(), E::Array(runs))])),
|
||||
}
|
||||
object.set("0", model);
|
||||
if let Some(frame) = object_frame(&object, true) {
|
||||
frame_shapes.push((frame, &layer.shape));
|
||||
}
|
||||
if slots.len() <= at {
|
||||
slots.resize(at + 1, E::dict());
|
||||
}
|
||||
@@ -1173,6 +1219,15 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi
|
||||
// `/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());
|
||||
// A path layer's frame holds its path; a layer taken off its path loses its path frame. An
|
||||
// unchanged path leaves the file's frame as it was.
|
||||
if let Some(E::Array(frames)) = outer.get_mut("0").and_then(|v| v.get_mut("8")).and_then(|v| v.get_mut("0")) {
|
||||
for (at, shape) in frame_shapes {
|
||||
if let Some(entry) = frames.get_mut(at) {
|
||||
crate::psd_path::update_frame(entry, shape);
|
||||
}
|
||||
}
|
||||
}
|
||||
if fonts.len() != fonts_before
|
||||
&& let Some(list @ E::Dict(_)) = outer.get_mut("0").and_then(|v| v.get_mut("1"))
|
||||
{
|
||||
@@ -1260,10 +1315,7 @@ 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);
|
||||
frames.resize(count, crate::psd_path::point_frame());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1512,7 +1564,9 @@ pub fn build_engine_data(layer: &TextLayer, template: Option<E>, dpi: f32) -> E
|
||||
dict.set("UseFractionalGlyphWidths", E::Bool(true));
|
||||
}
|
||||
let (shape_type, box_bounds) = match layer.shape {
|
||||
// PSD path type is not written yet: the layer saves as point text.
|
||||
// Type on a path: the path goes into the layer's `Txt2` frame ([`build_txt2`], #7962),
|
||||
// which only a file that already has a `Txt2` object for the layer gets; EngineData
|
||||
// keeps it as point text, one line for readers (and files) without that frame.
|
||||
TextShape::Point | TextShape::Path { .. } => (0, None),
|
||||
TextShape::Box { x, y, width, height } => (1, Some([x, y, x + width, y + height])),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
//! Type on a path in a PSD (#7962): the path lives only in the type layer's frame in the
|
||||
//! document's `Txt2` block (EngineData marks such a layer as box text, `ShapeType 1`, with the
|
||||
//! path's bounds as its `BoxBounds`).
|
||||
//!
|
||||
//! Observed layout (Photoshop 2026, `text/path-circle.psd` and `text/path-wave-open.psd` in
|
||||
//! photocraft-corpus): a frame `<< /0 << /1 << /0 [ … ] >> /2 << /0 2 /2 [ matrix ] … >> >> >>`
|
||||
//! has the kind `/2 /0` (absent for point text, 1 for a text box, 2 for type on a path) and its
|
||||
//! outline at `/1 /0` as a flat list of cubic Bézier segments, eight numbers each
|
||||
//! (`p0 c1 c2 p1`, the next segment starting where the previous one ends, a closed path ending
|
||||
//! where it started), in the frame's space; `/2 /2` maps the frame's space to the `TySh` text
|
||||
//! space. On a closed path Photoshop sets the type from the path's last anchor (the circle's
|
||||
//! glyph 0 sits on its fourth anchor and runs on through the first), on an open path from its
|
||||
//! first. Neither oracle has a moved start or flipped type, so those are written into the path
|
||||
//! itself (see [`frame_path`]).
|
||||
|
||||
use photocraft_doc::text::TextShape;
|
||||
use photocraft_doc::vector::{Knot, PathOp, Subpath};
|
||||
use photocraft_geom::{Affine, Point};
|
||||
|
||||
use crate::engine_data::Value as E;
|
||||
|
||||
/// The `Txt2` frame kind (`/2 /0`) of type on a path.
|
||||
pub(crate) const PATH_FRAME: i64 = 2;
|
||||
/// The `Txt2` frame kind (`/2 /0`) of a text box.
|
||||
const BOX_FRAME: i64 = 1;
|
||||
/// Most cubic segments read from a frame (a hostile file cannot make this large).
|
||||
const MAX_SEGMENTS: usize = 4096;
|
||||
/// How close (px) two points must be to count as the same: Photoshop writes a segment's start as
|
||||
/// an exact copy of the previous segment's end.
|
||||
const SAME: f64 = 1e-3;
|
||||
|
||||
/// The kind of the frame dictionary `frame` (the entry's `/0`): 0 point text, 1 box, 2 path.
|
||||
pub(crate) fn frame_kind(frame: &E) -> i64 {
|
||||
frame.path(&["2", "0"]).and_then(E::as_i64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Every entry of `v` as a finite number, or `None`.
|
||||
fn numbers(v: &E) -> Option<Vec<f64>> {
|
||||
v.as_array()?.iter().map(E::as_f64).collect()
|
||||
}
|
||||
|
||||
fn same(a: Point, b: Point) -> bool {
|
||||
(a.x - b.x).hypot(a.y - b.y) <= SAME
|
||||
}
|
||||
|
||||
/// Whether the handles `a` (in) and `b` (out) of `anchor` are collinear on opposite sides.
|
||||
fn smooth(anchor: Point, a: Point, b: Point) -> bool {
|
||||
let (ax, ay, bx, by) = (a.x - anchor.x, a.y - anchor.y, b.x - anchor.x, b.y - anchor.y);
|
||||
let (la, lb) = (ax.hypot(ay), bx.hypot(by));
|
||||
la > SAME && lb > SAME && (ax * by - ay * bx).abs() <= 1e-3 * la * lb && ax * bx + ay * by < 0.0
|
||||
}
|
||||
|
||||
fn knot(in_ctrl: Point, anchor: Point, out_ctrl: Point) -> Knot {
|
||||
Knot { anchor, in_ctrl, out_ctrl, smooth: smooth(anchor, in_ctrl, out_ctrl) }
|
||||
}
|
||||
|
||||
/// The type path of a path frame `frame` (the entry's `/0`), in the `TySh` text space, with the
|
||||
/// type starting at its first knot. `Err` says why it can't be read (the caller keeps the box or
|
||||
/// point text EngineData describes).
|
||||
pub(crate) fn read(frame: &E) -> Result<Subpath, String> {
|
||||
let raw = frame.path(&["1", "0"]).ok_or("the frame has no path")?;
|
||||
let v = numbers(raw).ok_or("a path coordinate is not a number")?;
|
||||
if v.is_empty() || v.len() % 8 != 0 {
|
||||
return Err(format!("its path has {} coordinates, not whole curve segments", v.len()));
|
||||
}
|
||||
if v.len() / 8 > MAX_SEGMENTS {
|
||||
return Err(format!("its path has more than {MAX_SEGMENTS} segments"));
|
||||
}
|
||||
let matrix = match frame.path(&["2", "2"]) {
|
||||
None => Affine::IDENTITY,
|
||||
Some(m) => {
|
||||
let Some([a, b, c, d, e, f]) = numbers(m).and_then(|m| <[f64; 6]>::try_from(m).ok()) else {
|
||||
return Err("its frame matrix is not six numbers".into());
|
||||
};
|
||||
let m = Affine { m: [a, b, c, d, e, f] };
|
||||
let det = m.determinant();
|
||||
if !det.is_finite() || det.abs() <= 1e-12 {
|
||||
return Err("its frame matrix is degenerate".into());
|
||||
}
|
||||
m
|
||||
}
|
||||
};
|
||||
let pts: Vec<Point> = v.as_chunks::<2>().0.iter().map(|&[x, y]| matrix.apply(Point::new(x, y))).collect();
|
||||
if pts.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
|
||||
return Err("its path is out of range".into());
|
||||
}
|
||||
let segs: Vec<[Point; 4]> = pts.as_chunks::<4>().0.to_vec();
|
||||
if segs.windows(2).any(|w| matches!(w, [a, b] if !same(a[3], b[0]))) {
|
||||
return Err("its path has more than one piece".into());
|
||||
}
|
||||
let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Err("the frame has no path".into()) };
|
||||
let (x0, x1) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.x), hi.max(p.x)));
|
||||
let (y0, y1) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.y), hi.max(p.y)));
|
||||
if x1 - x0 <= SAME && y1 - y0 <= SAME {
|
||||
return Err("its path has no length".into());
|
||||
}
|
||||
let closed = same(last[3], first[0]);
|
||||
let mut knots: Vec<Knot> = Vec::with_capacity(segs.len() + 1);
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
let prev = match i.checked_sub(1).and_then(|j| segs.get(j)) {
|
||||
Some(p) => p[2],
|
||||
None if closed => last[2],
|
||||
None => s[0],
|
||||
};
|
||||
knots.push(knot(prev, s[0], s[1]));
|
||||
}
|
||||
if closed {
|
||||
// The type starts on the closing segment: from the last anchor.
|
||||
knots.rotate_right(1);
|
||||
} else {
|
||||
knots.push(knot(last[2], last[3], last[3]));
|
||||
}
|
||||
Ok(Subpath { closed, knots, op: PathOp::Combine })
|
||||
}
|
||||
|
||||
/// `path` with its knots in the opposite order (the segments run backwards).
|
||||
fn reversed(path: &Subpath) -> Subpath {
|
||||
let mut knots: Vec<Knot> = path.knots.iter().rev().map(|k| Knot { anchor: k.anchor, in_ctrl: k.out_ctrl, out_ctrl: k.in_ctrl, smooth: k.smooth }).collect();
|
||||
if path.closed {
|
||||
// Keep the first knot first: k0, k(n-1), …, k1.
|
||||
knots.rotate_right(1);
|
||||
}
|
||||
Subpath { closed: path.closed, knots, op: path.op }
|
||||
}
|
||||
|
||||
fn lerp(a: Point, b: Point, t: f64) -> Point {
|
||||
Point::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)
|
||||
}
|
||||
|
||||
fn cubic(s: &[Point; 4], t: f64) -> Point {
|
||||
let (a, b, c) = (lerp(s[0], s[1], t), lerp(s[1], s[2], t), lerp(s[2], s[3], t));
|
||||
lerp(lerp(a, b, t), lerp(b, c, t), t)
|
||||
}
|
||||
|
||||
/// Pieces each segment is measured in for [`starting_at`].
|
||||
const STEPS: usize = 64;
|
||||
|
||||
/// `path` starting `s` px along it (the type origin moved there): an open path loses the part
|
||||
/// before `s`, a closed one starts at a new smooth knot there. Unchanged for `s` at or before the
|
||||
/// start, or (open) at or past the end.
|
||||
fn starting_at(path: &Subpath, s: f64) -> Subpath {
|
||||
let segs = path.segments();
|
||||
let lengths: Vec<f64> = segs
|
||||
.iter()
|
||||
.map(|seg| {
|
||||
(1..=STEPS)
|
||||
.map(|i| (cubic(seg, (i - 1) as f64 / STEPS as f64), cubic(seg, i as f64 / STEPS as f64)))
|
||||
.map(|(a, b)| (b.x - a.x).hypot(b.y - a.y))
|
||||
.sum()
|
||||
})
|
||||
.collect();
|
||||
let total: f64 = lengths.iter().sum();
|
||||
if !s.is_finite() || !total.is_finite() || total <= SAME {
|
||||
return path.clone();
|
||||
}
|
||||
let s = if path.closed { s.rem_euclid(total) } else { s };
|
||||
if s <= SAME || (!path.closed && s >= total - SAME) || (path.closed && s >= total - SAME) {
|
||||
return path.clone();
|
||||
}
|
||||
// The segment and parameter at arc length `s` (linear within a measured piece).
|
||||
let mut left = s;
|
||||
let mut at = None;
|
||||
for (i, (seg, len)) in segs.iter().zip(&lengths).enumerate() {
|
||||
if left > *len {
|
||||
left -= len;
|
||||
continue;
|
||||
}
|
||||
let mut walked = 0.0;
|
||||
for k in 1..=STEPS {
|
||||
let (t0, t1) = ((k - 1) as f64 / STEPS as f64, k as f64 / STEPS as f64);
|
||||
let (a, b) = (cubic(seg, t0), cubic(seg, t1));
|
||||
let piece = (b.x - a.x).hypot(b.y - a.y);
|
||||
if walked + piece >= left || k == STEPS {
|
||||
let f = if piece > 0.0 { ((left - walked) / piece).clamp(0.0, 1.0) } else { 0.0 };
|
||||
at = Some((i, t0 + (t1 - t0) * f, *seg));
|
||||
break;
|
||||
}
|
||||
walked += piece;
|
||||
}
|
||||
break;
|
||||
}
|
||||
let Some((i, t, seg)) = at else { return path.clone() };
|
||||
// de Casteljau: left half p0 a ab m, right half m bc c p3.
|
||||
let (a, b, c) = (lerp(seg[0], seg[1], t), lerp(seg[1], seg[2], t), lerp(seg[2], seg[3], t));
|
||||
let (ab, bc) = (lerp(a, b, t), lerp(b, c, t));
|
||||
let m = lerp(ab, bc, t);
|
||||
let n = path.knots.len();
|
||||
if n == 0 {
|
||||
return path.clone();
|
||||
}
|
||||
let next = (i + 1) % n;
|
||||
let mut knots = Vec::with_capacity(n + 1);
|
||||
knots.push(Knot { anchor: m, in_ctrl: if path.closed { ab } else { m }, out_ctrl: bc, smooth: path.closed });
|
||||
let count = if path.closed { n } else { n - next };
|
||||
for r in 0..count {
|
||||
let j = (next + r) % n;
|
||||
let Some(mut k) = path.knots.get(j).copied() else { continue };
|
||||
if j == next {
|
||||
k.in_ctrl = c;
|
||||
}
|
||||
if path.closed && j == i {
|
||||
k.out_ctrl = a;
|
||||
}
|
||||
knots.push(k);
|
||||
}
|
||||
Subpath { closed: path.closed, knots, op: path.op }
|
||||
}
|
||||
|
||||
/// The path a frame is written with for `TextShape::Path { path, start, flip }`: flipped type is
|
||||
/// the path run backwards and a moved start the path from there on (exactly how PhotoCraft lays
|
||||
/// type on a path out), so Photoshop, which starts at the path's beginning, sets the same type.
|
||||
pub(crate) fn frame_path(path: &Subpath, start: f32, flip: bool) -> Subpath {
|
||||
let path = if flip { reversed(path) } else { path.clone() };
|
||||
starting_at(&path, f64::from(start))
|
||||
}
|
||||
|
||||
fn real(v: f64) -> E {
|
||||
E::Real(v)
|
||||
}
|
||||
|
||||
/// The segment list (`/1 /0`) Photoshop reads `path` from: on a closed path the type starts at
|
||||
/// the last anchor, so the first knot goes last.
|
||||
fn segment_list(path: &Subpath) -> Option<Vec<E>> {
|
||||
let mut knots = path.knots.clone();
|
||||
if path.closed && !knots.is_empty() {
|
||||
knots.rotate_left(1);
|
||||
}
|
||||
let segs = Subpath { closed: path.closed, knots, op: path.op }.segments();
|
||||
let out: Vec<E> = segs.iter().flatten().flat_map(|p| [real(p.x), real(p.y)]).collect();
|
||||
(!out.is_empty() && segs.iter().flatten().all(|p| p.x.is_finite() && p.y.is_finite())).then_some(out)
|
||||
}
|
||||
|
||||
/// Whether two type paths are the same within [`SAME`] (the smooth flags aside).
|
||||
fn same_path(a: &Subpath, b: &Subpath) -> bool {
|
||||
a.closed == b.closed
|
||||
&& a.knots.len() == b.knots.len()
|
||||
&& a.knots.iter().zip(&b.knots).all(|(p, q)| same(p.anchor, q.anchor) && same(p.in_ctrl, q.in_ctrl) && same(p.out_ctrl, q.out_ctrl))
|
||||
}
|
||||
|
||||
/// The point-text frame Photoshop writes (`<< /0 << /2 << /6 [ -1.0 -1.0 ] /11 << /4 -1 /7 false
|
||||
/// >> >> >> >>`; also what [`crate::psd`] pads the frame list with).
|
||||
pub(crate) fn point_frame() -> E {
|
||||
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![real(-1.0), real(-1.0)])), ("11".into(), kind)]);
|
||||
E::Dict(vec![("0".into(), E::Dict(vec![("2".into(), data)]))])
|
||||
}
|
||||
|
||||
/// A text box's frame as Photoshop writes it (`text/paragraph-box-left.psd`): the rectangle as
|
||||
/// four straight segments from its top left, clockwise.
|
||||
fn box_frame(x: f64, y: f64, w: f64, h: f64) -> E {
|
||||
let c = [(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)];
|
||||
let pts: Vec<E> =
|
||||
c.windows(2).flat_map(|p| p.iter().flat_map(|&(a, b)| [(a, b), (a, b)]).collect::<Vec<_>>()).flat_map(|(a, b)| [real(a), real(b)]).collect();
|
||||
let kind = E::Dict(vec![("4".into(), E::Int(-2)), ("18".into(), real(-2.0)), ("22".into(), real(0.025))]);
|
||||
let data = E::Dict(vec![("0".into(), E::Int(BOX_FRAME)), ("6".into(), E::Array(vec![real(-2.0), real(-2.0)])), ("11".into(), kind)]);
|
||||
E::Dict(vec![("0".into(), E::Dict(vec![("1".into(), E::Dict(vec![("0".into(), E::Array(pts))])), ("2".into(), data)]))])
|
||||
}
|
||||
|
||||
/// Brings the frame list entry `entry` (`<< /0 frame >>`) of a type layer up to date with its
|
||||
/// `shape`: type on a path gets a path frame for its path (left byte for byte when it already
|
||||
/// holds that path, e.g. Photoshop's own after an unedited save), and a layer no longer on a path
|
||||
/// loses its path frame (else it would reopen on the path).
|
||||
pub(crate) fn update_frame(entry: &mut E, shape: &TextShape) {
|
||||
let frame = entry.get("0");
|
||||
let kind = frame.map_or(0, frame_kind);
|
||||
match shape {
|
||||
TextShape::Path { path, start, flip } => {
|
||||
let path = frame_path(path, *start, *flip);
|
||||
if kind == PATH_FRAME && frame.and_then(|f| read(f).ok()).is_some_and(|p| same_path(&p, &path)) {
|
||||
return;
|
||||
}
|
||||
let Some(list) = segment_list(&path) else { return };
|
||||
// Keep the other keys of a path frame; anything else becomes one.
|
||||
let mut data = match frame.and_then(|f| f.get("2")) {
|
||||
Some(d @ E::Dict(_)) if kind == PATH_FRAME => d.clone(),
|
||||
_ => E::Dict(vec![("6".into(), E::Array(vec![real(-1.0), real(-1.0)]))]),
|
||||
};
|
||||
data.set("0", E::Int(PATH_FRAME));
|
||||
// The path is written in text space.
|
||||
data.set("2", E::Array([1.0, 0.0, 0.0, 1.0, 0.0, 0.0].map(real).to_vec()));
|
||||
let mut frame = match frame {
|
||||
Some(f @ E::Dict(_)) if kind == PATH_FRAME => f.clone(),
|
||||
_ => E::dict(),
|
||||
};
|
||||
frame.set("1", E::Dict(vec![("0".into(), E::Array(list))]));
|
||||
frame.set("2", data);
|
||||
*entry = E::Dict(vec![("0".into(), frame)]);
|
||||
}
|
||||
_ if kind != PATH_FRAME => {}
|
||||
TextShape::Box { x, y, width, height } => *entry = box_frame(f64::from(*x), f64::from(*y), f64::from(*width), f64::from(*height)),
|
||||
TextShape::Point => *entry = point_frame(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::engine_data::parse;
|
||||
|
||||
fn frame(src: &str) -> E {
|
||||
parse(src.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
/// The frame of `text/path-circle.psd` (Photoshop 2026).
|
||||
const CIRCLE: &str = "<< /1 << /0 [ 32.0 128.0 32.0 74.98067 74.98067 32.0 128.0 32.0 128.0 32.0 181.01933 32.0 224.0 74.98067 224.0 128.0 224.0 128.0 224.0 181.01933 181.01933 224.0 128.0 224.0 128.0 224.0 74.98067 224.0 32.0 181.01933 32.0 128.0 ] >> /2 << /0 2 /2 [ 1.0 0.0 0.0 1.0 -32.0 -32.0 ] /6 [ -1.0 -1.0 ] >> >>";
|
||||
/// The frame of `text/path-wave-open.psd` (Photoshop 2026).
|
||||
const WAVE: &str = "<< /1 << /0 [ 16.0 100.0 46.0 40.0 120.0 40.0 160.0 80.0 160.0 80.0 200.0 120.0 274.0 100.0 304.0 60.0 ] >> /2 << /0 2 /2 [ 1.0 0.0 0.0 1.0 -16.0 -52.12246 ] /6 [ -1.0 -1.0 ] >> >>";
|
||||
|
||||
#[test]
|
||||
fn photoshop_path_frames_read_into_text_space() {
|
||||
let wave = read(&frame(WAVE)).unwrap();
|
||||
assert!(!wave.closed);
|
||||
assert_eq!(wave.knots.len(), 3);
|
||||
let p = |x: f64, y: f64| Point::new(x - 16.0, y - 52.12246);
|
||||
let k = &wave.knots;
|
||||
assert!(same(k[0].anchor, p(16.0, 100.0)) && same(k[0].in_ctrl, p(16.0, 100.0)) && same(k[0].out_ctrl, p(46.0, 40.0)));
|
||||
assert!(same(k[1].in_ctrl, p(120.0, 40.0)) && same(k[1].anchor, p(160.0, 80.0)) && same(k[1].out_ctrl, p(200.0, 120.0)) && k[1].smooth);
|
||||
assert!(same(k[2].in_ctrl, p(274.0, 100.0)) && same(k[2].anchor, p(304.0, 60.0)));
|
||||
|
||||
let circle = read(&frame(CIRCLE)).unwrap();
|
||||
assert!(circle.closed);
|
||||
assert_eq!(circle.knots.len(), 4);
|
||||
// The type starts at the bottom anchor (Photoshop's glyph 0) and runs to the left one.
|
||||
assert!(same(circle.knots[0].anchor, Point::new(96.0, 192.0)));
|
||||
assert!(same(circle.knots[1].anchor, Point::new(0.0, 96.0)));
|
||||
assert!(circle.knots.iter().all(|k| k.smooth));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn written_frames_read_back() {
|
||||
for src in [CIRCLE, WAVE] {
|
||||
let path = read(&frame(src)).unwrap();
|
||||
let mut entry = E::Dict(vec![("0".into(), frame(src))]);
|
||||
let before = entry.clone();
|
||||
update_frame(&mut entry, &TextShape::Path { path: path.clone(), start: 0.0, flip: false });
|
||||
assert_eq!(entry, before, "an unchanged path keeps Photoshop's frame");
|
||||
let mut moved = path.clone();
|
||||
for k in &mut moved.knots {
|
||||
*k = k.transform(&Affine::translate(5.0, -3.0));
|
||||
}
|
||||
update_frame(&mut entry, &TextShape::Path { path: moved.clone(), start: 0.0, flip: false });
|
||||
let back = read(entry.get("0").unwrap()).unwrap();
|
||||
assert!(same_path(&back, &moved), "{back:?}");
|
||||
assert_eq!(entry.path(&["0", "2", "6"]), before.path(&["0", "2", "6"]), "the frame's other keys stay");
|
||||
}
|
||||
}
|
||||
|
||||
/// Flipped type and a moved start are written into the path, which lays the type out the same.
|
||||
#[test]
|
||||
fn flip_and_start_are_baked_into_the_frame() {
|
||||
use crate::warp::Warp;
|
||||
for src in [CIRCLE, WAVE] {
|
||||
let path = read(&frame(src)).unwrap();
|
||||
for (start, flip) in [(40.0, false), (0.0, true), (25.0, true)] {
|
||||
let shape = TextShape::Path { path: path.clone(), start, flip };
|
||||
let baked = TextShape::Path { path: frame_path(&path, start, flip), start: 0.0, flip: false };
|
||||
let (a, b) = (Warp::on_path(&shape).unwrap(), Warp::on_path(&baked).unwrap());
|
||||
for x in [0.0, 10.0, 50.0, 120.0] {
|
||||
for y in [-12.0, 0.0, 4.0] {
|
||||
let (p, q) = (a.apply(x, y), b.apply(x, y));
|
||||
assert!((p.0 - q.0).hypot(p.1 - q.1) < 0.5, "{src:.10} start {start} flip {flip} at ({x}, {y}): {p:?} vs {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_frames_are_errors() {
|
||||
for src in [
|
||||
"<< /2 << /0 2 >> >>",
|
||||
"<< /1 << /0 [ ] >> /2 << /0 2 >> >>",
|
||||
"<< /1 << /0 [ 1.0 2.0 3.0 ] >> /2 << /0 2 >> >>",
|
||||
"<< /1 << /0 [ 0 0 1 1 2 2 (x) 3 ] >> /2 << /0 2 >> >>",
|
||||
"<< /1 << /0 [ 0 0 1 1 2 2 1e999 3 ] >> /2 << /0 2 >> >>",
|
||||
"<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 0 0 0 0 0 0 ] >> >>",
|
||||
"<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 1 0 0 ] >> >>",
|
||||
"<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 1e300 0 0 1e300 0 0 ] >> >>",
|
||||
"<< /1 << /0 [ 0 0 1 1 2 2 3 3 50 50 60 60 70 70 80 80 ] >> /2 << /0 2 >> >>",
|
||||
"<< /1 << /0 [ 5 5 5 5 5 5 5 5 ] >> /2 << /0 2 >> >>",
|
||||
"<< /1 << /0 (path) >> /2 << /0 2 >> >>",
|
||||
] {
|
||||
assert!(read(&frame(src)).is_err(), "{src}");
|
||||
}
|
||||
let many = format!("<< /1 << /0 [ {} ] >> /2 << /0 2 >> >>", "0 0 1 1 2 2 0 0 ".repeat(MAX_SEGMENTS + 1));
|
||||
assert!(read(&frame(&many)).is_err());
|
||||
}
|
||||
|
||||
fn d(items: Vec<(&str, E)>) -> E {
|
||||
E::Dict(items.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
|
||||
}
|
||||
|
||||
/// A Photoshop-shaped `Txt2` block with one point-text object for `text` (`\r` breaks, trailing
|
||||
/// `\r`) drawn in frame 0.
|
||||
fn photoshop_txt2(text: &str) -> Vec<u8> {
|
||||
photoshop_txt2_in(text, point_frame())
|
||||
}
|
||||
|
||||
/// [`photoshop_txt2`] with the frame list entry `frame`.
|
||||
fn photoshop_txt2_in(text: &str, frame: E) -> Vec<u8> {
|
||||
let len = text.encode_utf16().count() as i64;
|
||||
let run = || {
|
||||
d(vec![("0", d(vec![("0", d(vec![("0", E::String(String::new())), ("6", d(vec![("0", E::Int(0)), ("1", E::Real(12.0))]))]))])), ("1", E::Int(len))])
|
||||
};
|
||||
let model = d(vec![("0", E::String(text.into())), ("5", d(vec![("0", E::Array(vec![run()]))])), ("6", d(vec![("0", E::Array(vec![run()]))]))]);
|
||||
let strike = d(vec![("99", E::Name("PC".into())), ("6", E::Array(vec![d(vec![("99", E::Name("F".into())), ("10", E::Int(0))])]))]);
|
||||
let view = d(vec![
|
||||
("0", E::Array(vec![d(vec![("0", E::Int(0))])])),
|
||||
("1", d(vec![("0", E::Array(vec![d(vec![("0", d(vec![("1", E::Int(1))])), ("1", E::Int(len))])]))])),
|
||||
("2", E::Array(vec![strike])),
|
||||
]);
|
||||
let object = d(vec![("0", model), ("1", view)]);
|
||||
crate::engine_data::write_bare(&[
|
||||
("98".into(), d(vec![("0", E::Int(14))])),
|
||||
("0".into(), d(vec![("8", d(vec![("0", E::Array(vec![frame]))]))])),
|
||||
("1".into(), d(vec![("1", E::Array(vec![object]))])),
|
||||
])
|
||||
}
|
||||
|
||||
fn layer(text: &str, shape: TextShape) -> photocraft_doc::TextLayer {
|
||||
use photocraft_doc::text::{CharStyle, TextRun};
|
||||
let mut t = photocraft_doc::TextLayer {
|
||||
text: text.into(),
|
||||
runs: vec![TextRun { len: text.len(), style: CharStyle { size_pt: 12.0, ..Default::default() } }],
|
||||
shape,
|
||||
transform: Affine::translate(32.0, 20.0),
|
||||
..Default::default()
|
||||
};
|
||||
t.sync_summary();
|
||||
t
|
||||
}
|
||||
|
||||
/// A layer read back, with what [`crate::psd::apply_txt2_path`] said.
|
||||
type Opened = (photocraft_doc::TextLayer, Result<bool, String>);
|
||||
|
||||
/// Saves `layers` (object `i` each) into a file whose `Txt2` is `prev`, then reads each back:
|
||||
/// its `TySh` and what [`crate::psd::apply_txt2_path`] makes of the saved `Txt2`.
|
||||
fn save_and_open(layers: &[&photocraft_doc::TextLayer], prev: &[u8]) -> (Vec<u8>, Vec<Opened>) {
|
||||
let objects: Vec<(i32, &photocraft_doc::TextLayer)> = layers.iter().enumerate().map(|(i, l)| (i as i32, *l)).collect();
|
||||
let txt2 = crate::psd::build_txt2(&objects, Some(prev));
|
||||
let parsed = crate::psd::parse_txt2(&txt2).unwrap();
|
||||
let back = objects
|
||||
.iter()
|
||||
.map(|(i, l)| {
|
||||
let tysh = crate::psd::set_text_index(&crate::psd::build_tysh(l, 72.0, None), *i).unwrap();
|
||||
let mut back = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap();
|
||||
crate::psd::apply_txt2(&mut back, &tysh, &parsed);
|
||||
let applied = crate::psd::apply_txt2_path(&mut back, &tysh, &parsed);
|
||||
crate::psd::apply_txt2_frame(&mut back, &tysh, &parsed);
|
||||
(back, applied)
|
||||
})
|
||||
.collect();
|
||||
(txt2, back)
|
||||
}
|
||||
|
||||
/// #7962: type on a path survives a PSD save and open, for the file's own text object and for
|
||||
/// a layer the file had no object for; a moved start and flipped type come back laid out the
|
||||
/// same, in the path; a second save changes nothing.
|
||||
#[test]
|
||||
fn path_text_round_trips_through_tysh_and_txt2() {
|
||||
let circle = read(&frame(CIRCLE)).unwrap();
|
||||
let wave = read(&frame(WAVE)).unwrap();
|
||||
let a = layer("On a circle", TextShape::Path { path: circle.clone(), start: 0.0, flip: false });
|
||||
let b = layer("Along a wave", TextShape::Path { path: wave.clone(), start: 30.0, flip: true });
|
||||
let prev = photoshop_txt2("On a circle\r");
|
||||
let (txt2, back) = save_and_open(&[&a, &b], &prev);
|
||||
for ((l, applied), (want, start, flip)) in back.iter().zip([(&circle, 0.0, false), (&wave, 30.0, true)]) {
|
||||
assert_eq!(applied, &Ok(true), "{}", l.text);
|
||||
let TextShape::Path { path, start: s, flip: f } = &l.shape else { panic!("{}: {:?}", l.text, l.shape) };
|
||||
assert_eq!((*s, *f), (0.0, false));
|
||||
assert!(same_path(path, &frame_path(want, start, flip)), "{}: {path:?}", l.text);
|
||||
assert_eq!(l.transform, Affine::translate(32.0, 20.0), "the frame's matrix is not applied twice");
|
||||
}
|
||||
let (again, _) = save_and_open(&[&back[0].0, &back[1].0], &txt2);
|
||||
assert_eq!(again, txt2, "a re-save of the opened file changes nothing");
|
||||
// Off its path, the layer opens as point text again.
|
||||
let detached = layer("On a circle", TextShape::Point);
|
||||
let (_, back) = save_and_open(&[&detached], &txt2);
|
||||
assert_eq!(back[0].1, Ok(false));
|
||||
assert_eq!(back[0].0.shape, TextShape::Point);
|
||||
}
|
||||
|
||||
/// A malformed path frame leaves the layer as EngineData describes it, with the reason.
|
||||
#[test]
|
||||
fn a_malformed_path_frame_keeps_the_engine_data_shape() {
|
||||
let a = layer("Hostile", TextShape::Box { x: 0.0, y: 0.0, width: 50.0, height: 20.0 });
|
||||
let tysh = crate::psd::set_text_index(&crate::psd::build_tysh(&a, 72.0, None), 0).unwrap();
|
||||
for bad in ["<< /1 << /0 [ 1 2 3 ] >> /2 << /0 2 >> >>", "<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 0 0 0 0 0 0 ] >> >>"] {
|
||||
let entry = E::Dict(vec![("0".into(), frame(bad))]);
|
||||
let txt2 = crate::psd::parse_txt2(&photoshop_txt2_in("Hostile\r", entry)).unwrap();
|
||||
let mut l = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap();
|
||||
let before = l.shape.clone();
|
||||
assert!(crate::psd::apply_txt2_path(&mut l, &tysh, &txt2).is_err(), "{bad}");
|
||||
assert_eq!(l.shape, before);
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer taken off its path doesn't keep its path frame (it would reopen on the path).
|
||||
#[test]
|
||||
fn a_layer_off_its_path_loses_the_path_frame() {
|
||||
let mut entry = E::Dict(vec![("0".into(), frame(CIRCLE))]);
|
||||
update_frame(&mut entry, &TextShape::Point);
|
||||
assert_eq!(entry, point_frame());
|
||||
let mut entry = E::Dict(vec![("0".into(), frame(WAVE))]);
|
||||
update_frame(&mut entry, &TextShape::Box { x: 1.0, y: 2.0, width: 30.0, height: 40.0 });
|
||||
assert_eq!(entry.get("0").map(frame_kind), Some(BOX_FRAME));
|
||||
assert_eq!(
|
||||
entry.path(&["0", "1", "0"]).and_then(numbers).unwrap()[..8],
|
||||
[1.0, 2.0, 1.0, 2.0, 31.0, 2.0, 31.0, 2.0],
|
||||
"Photoshop's box outline: corners as straight segments from the top left"
|
||||
);
|
||||
// A point or box frame is left alone.
|
||||
let mut point = point_frame();
|
||||
update_frame(&mut point, &TextShape::Point);
|
||||
assert_eq!(point, point_frame());
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -1,6 +1,6 @@
|
||||
# Where PhotoCraft falls short of Photoshop
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** minor (G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
|
||||
on the way to beta. This is the work list agents pick from: take the highest-ranked entry that
|
||||
@@ -82,7 +82,9 @@ what an agent can't finish alone.
|
||||
- **Estimate:** 80–140 h.
|
||||
|
||||
### G8. Type depth
|
||||
- **Missing:** type on a path (TYPE-218-1), paragraph direction UI (TYPE-218-2), complex-script
|
||||
- **Missing:** type on a path (TYPE-218-1: the Type tool clicking a path, the caret on the curve,
|
||||
and PSD path text in a new document, which still saves as point text; Photoshop's path text
|
||||
opens on its path and saves back into the file's `Txt2` since 2026-10-21, #7962), paragraph direction UI (TYPE-218-2), complex-script
|
||||
fallback fonts and golden tests (TYPE-218-3), OpenType Numerals and Stylistic Sets submenus
|
||||
(TYPE-218-5; the Character panel buttons landed 2026-10-11, #3752), live Warp Text preview
|
||||
(TYPE-218-7, #2689), "rasterize and continue" for distort/perspective on type
|
||||
@@ -274,6 +276,7 @@ what an agent can't finish alone.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-21 | minor | G8: Photoshop's type on a path opens on its path (read from the `Txt2` frame) and saves back into the file's `Txt2` object (#7962); TYPE-218-1 stays partial (new documents save path text as point text) |
|
||||
| 2026-10-15 | minor | G1 / #5972 A1: render only provably constant-RGB `GdFl` noise fills; variable noise synthesis remains open |
|
||||
| 2026-10-18 | minor | G9: with no selection, Copy takes fill and adjustment layers whole and Paste recreates them (#2344); UI-217-23 stays partial (a single pixel layer copies its pixels only); estimate unchanged |
|
||||
| 2026-10-14 | minor | G1: a PSD smart object's filter mask shows when the file opens (Photoshop stores the filtered pixels unmasked); export stores them that way too; Photoshop-oracle floor 185 → 188 of 258 |
|
||||
|
||||
+1
-1
@@ -214,7 +214,7 @@ Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_w
|
||||
|
||||
| Id | Target | Status | Issue | Note |
|
||||
|---|---|---|---|---|
|
||||
| TYPE-218-1 | Type on a path: path shape, glyphs along the curve, caret follows, PSD round trip | partial | [#218](https://github.com/storytold/photocraft/issues/218) | TextShape::Path (doc text.rs) with glyphs placed rigidly along the curve by arc length (text warp.rs PathFrame), type.attachToPath and type.detachFromPath (#4365), .pcraft round trip. Missing: clicking a path with the Type tool, the caret and selection following the curve, and PSD path text (it saves as point text) |
|
||||
| TYPE-218-1 | Type on a path: path shape, glyphs along the curve, caret follows, PSD round trip | partial | [#218](https://github.com/storytold/photocraft/issues/218) | TextShape::Path (doc text.rs) with glyphs placed rigidly along the curve by arc length (text warp.rs PathFrame), type.attachToPath and type.detachFromPath (#4365), .pcraft round trip; PSD path text opens on its path from its Txt2 frame and saves back into the file's Txt2 object (#7962). Missing: clicking a path with the Type tool, the caret and selection following the curve, and PSD path text in a file without Photoshop's Txt2 object for the layer (a new document saves it as point text) |
|
||||
| TYPE-218-2 | Paragraph direction (Auto/LTR/RTL) in the panel and options bar; visual RTL caret | missing | [#218](https://github.com/storytold/photocraft/issues/218) | Engine has TextDirection (text.rs:155); no UI |
|
||||
| TYPE-218-3 | Thai/Khmer/Indic fallback fonts; golden shaping tests for complex scripts and RTL | partial | [#218](https://github.com/storytold/photocraft/issues/218) | Fallback fonts are covered for Thai, Khmer, Lao, Myanmar (THAI_FAMILIES, KHMER_FAMILIES, LAO_FAMILIES, MYANMAR_FAMILIES in fonts.rs; #1909, #3259), the nine Indic scripts (INDIC_FAMILIES: Nirmala UI, Kohinoor and Sangam MN, Noto Sans) and Arabic and Hebrew. Still missing: per-script golden shaping tests against reference output (only smoke tests that an installed font shapes without .notdef, plus a bidi test) |
|
||||
| TYPE-218-4 | Variable font axis sliders from the font's axes; opsz follows the point size | done | [#218](https://github.com/storytold/photocraft/issues/218) | One slider per axis of the style's font in the Character section (Properties and Window > Character), setting type.setStyle variations; opsz follows the type size unless set (layout.rs variation_list); a style or weight resets the wght axis (#2985). PSD does not round-trip axis values yet |
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ id = "TYPE-218-1"
|
||||
target = "Type on a path: path shape, glyphs along the curve, caret follows, PSD round trip"
|
||||
status = "partial"
|
||||
issue = 218
|
||||
note = "TextShape::Path (doc text.rs) with glyphs placed rigidly along the curve by arc length (text warp.rs PathFrame), type.attachToPath and type.detachFromPath (#4365), .pcraft round trip. Missing: clicking a path with the Type tool, the caret and selection following the curve, and PSD path text (it saves as point text)"
|
||||
note = "TextShape::Path (doc text.rs) with glyphs placed rigidly along the curve by arc length (text warp.rs PathFrame), type.attachToPath and type.detachFromPath (#4365), .pcraft round trip; PSD path text opens on its path from its Txt2 frame and saves back into the file's Txt2 object (#7962). Missing: clicking a path with the Type tool, the caret and selection following the curve, and PSD path text in a file without Photoshop's Txt2 object for the layer (a new document saves it as point text)"
|
||||
|
||||
[[item]]
|
||||
id = "TYPE-218-2"
|
||||
|
||||
Reference in new issue
Block a user