Merge PR #9321: feat: type on a path follows its path when the path is edited (#9114)

This commit is contained in:
David Mann committed 2026-10-27 13:12:53 +01:00
commit f811db8f65
7 files changed
+228 -11

No files matched your search

+20 -2
View File
@@ -6,7 +6,8 @@
//!
//! Every command targets a path like `path.transform`: `"name":"work"` (default), a saved path's
//! name, or `"layer"` with `"layer":id?` for a shape layer's path (re-rendered; it stops being a
//! live shape) or a layer's vector mask. Knots are addressed by `subpath` and `knot` index, as
//! live shape), a layer's vector mask, or type on a path's Type Path (`"typePath":true` when the
//! type layer also has a vector mask). Knots are addressed by `subpath` and `knot` index, as
//! listed by `path.info`, and the result is `{name, path}` in the compact JSON form.
use photocraft_doc::{LayerContent, Path};
@@ -49,6 +50,23 @@ fn knot(cmd: &str, p: &Value) -> Result<[usize; 2]> {
fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(&mut Path) -> std::result::Result<(), String>) -> Result<Value> {
let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned();
let layer = if name == "layer" { Some(layer_id(s, p)?) } else { None };
// Type on a path: its own path, the text laid along it again (#9114). A vector mask on the
// layer stays what `"layer"` edits, as with `path.info`, unless `"typePath": true`.
let type_path = p.get("typePath").and_then(Value::as_bool).unwrap_or(false);
let typed = layer.filter(|id| {
s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| {
matches!(&l.content, LayerContent::Text(t) if crate::type_extra_cmds::type_path(t).is_some()) && (type_path || l.vector_mask.is_none())
})
});
if let Some(id) = typed {
let path = crate::type_extra_cmds::with_text(s, &json!({"layer": id.0}), label, |t, _| {
let mut path = crate::type_extra_cmds::type_path(t).ok_or_else(|| bad(cmd, "the type layer is not on a path"))?;
f(&mut path).map_err(|e| bad(cmd, e))?;
crate::type_extra_cmds::set_type_path(t, &path)?;
Ok(path_json(&path))
})?;
return Ok(json!({ "name": name, "path": path }));
}
let shape = layer.filter(|id| s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| matches!(l.content, LayerContent::Shape(_))));
let path = match shape {
Some(id) => with_shape(s, id, label, |sh, _| {
@@ -149,7 +167,7 @@ fn delete_anchor(s: &mut Session, p: &Value) -> Result<Value> {
}
pub fn specs() -> Vec<CommandSpec> {
const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path or a vector mask)"#;
const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path, a vector mask, or else type on a path's Type Path),"typePath":bool=false (with "layer": the Type Path even when the type layer has a vector mask)"#;
let spec = |id: &'static str, label: &'static str, params: String, run: fn(&mut Session, &Value) -> Result<Value>| CommandSpec {
id,
label,
+32
View File
@@ -415,6 +415,38 @@ fn attach_to_path(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"layer": id.0, "start": start, "flip": flip}))
}
/// Type on a path's own path in document space (#9114): what the Direct Selection tool shows and
/// edits, as Photoshop's Type Path. `None` unless `t` is type on a path.
pub fn type_path(t: &TextLayer) -> Option<Path> {
let TextShape::Path { path, .. } = &t.shape else { return None };
let map = |q: Point| t.transform.apply(q);
let knots = path.knots.iter().map(|k| Knot { anchor: map(k.anchor), in_ctrl: map(k.in_ctrl), out_ctrl: map(k.out_ctrl), smooth: k.smooth }).collect();
Some(Path::new(vec![Subpath { closed: path.closed, knots, op: path.op }]))
}
/// Puts an edited [`type_path`] back into `t` (its text space), keeping where the type starts and
/// which side it runs on. It must still be one subpath with two or more points.
pub(crate) fn set_type_path(t: &mut TextLayer, edited: &Path) -> Result<()> {
let TextShape::Path { start, flip, .. } = &t.shape else { return Err(EngineError::Other("the type layer is not on a path".into())) };
let (start, flip) = (*start, *flip);
let [sub] = edited.subpaths.as_slice() else { return Err(EngineError::Other("type on a path follows one path".into())) };
if sub.knots.len() < 2 {
return Err(EngineError::Other("type on a path needs a path of two or more points".into()));
}
if sub.knots.len() > MAX_TYPE_PATH_KNOTS {
return Err(EngineError::Other("the type path has too many anchor points".into()));
}
let inv = t.transform.inverse().ok_or_else(|| EngineError::Other("the type layer's transform cannot be inverted".into()))?;
let map = |q: Point| inv.apply(q);
let knots: Vec<Knot> =
sub.knots.iter().map(|k| Knot { anchor: map(k.anchor), in_ctrl: map(k.in_ctrl), out_ctrl: map(k.out_ctrl), smooth: k.smooth }).collect();
if !knots.iter().all(|k| [k.anchor, k.in_ctrl, k.out_ctrl].iter().all(|q| q.x.is_finite() && q.y.is_finite())) {
return Err(EngineError::Other("the path cannot be mapped into the type layer".into()));
}
t.shape = TextShape::Path { path: Subpath { closed: sub.closed, knots, op: sub.op }, start, flip };
Ok(())
}
fn is_path_text(s: &Session) -> std::result::Result<(), String> {
match active_text(s)?.shape {
TextShape::Path { .. } | TextShape::Area { .. } => Ok(()),
@@ -314,6 +314,80 @@ fn type_attaches_to_a_path_and_releases_it() {
assert!(matches!(text(&s, id).shape, TextShape::Path { .. }));
}
/// #9114: type on a path follows its own path when the path is edited (Direct Selection's
/// `path.*` commands with `"name": "layer"`), as Photoshop's Type Path does; the Paths list names
/// it, an edit is one undo step, and an edit that leaves no path is refused.
#[test]
fn type_follows_its_path_when_the_path_is_edited() {
let mut s = session(8);
let id = text_layer(&mut s, "Hello path");
s.edit("path", |doc, _| {
doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])]));
Ok(())
})
.unwrap();
s.execute("type.attachToPath", json!({"start": 4})).unwrap();
// In document space, the type path is where the work path was.
let path = crate::type_extra_cmds::type_path(text(&s, id)).unwrap();
let ends: Vec<(f64, f64)> = path.subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect();
assert!(ends.iter().zip([(150.0, 10.0), (150.0, 110.0)]).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{ends:?}");
let listed = s.execute("path.list", json!({})).unwrap();
assert_eq!(listed["typePath"]["kind"], "typePath", "{listed}");
// Swing the path's end to the right: the type now runs down and to the right.
let before = ink(&s, id);
let r = s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 1]], "move": [120, 0]})).unwrap();
assert_eq!(r["name"], "layer");
let after = ink(&s, id);
assert!(after.width() > before.width() + 20, "{before:?} → {after:?}");
assert!(matches!(text(&s, id).shape, TextShape::Path { start, .. } if start == 4.0), "where the type starts is kept");
// The work path it came from is untouched; Undo puts the type path back.
assert_eq!(s.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots[1].anchor.x, 150.0);
assert!(s.undo());
assert_eq!(ink(&s, id), before);
// An edit that would leave fewer than two points is refused and changes nothing.
assert!(s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id.0, "subpath": 0, "knot": 0})).is_err());
assert_eq!(ink(&s, id), before);
}
/// #9114: a type-on-a-path layer's vector mask is still what `"name": "layer"` edits, as on main
/// and as `path.info` reads it; `"typePath": true` edits the Type Path; `path.list` reports both.
#[test]
fn a_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() {
let mut s = session(8);
let id = text_layer(&mut s, "Hello path");
s.edit("path", |doc, _| {
doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])]));
Ok(())
})
.unwrap();
s.execute("type.attachToPath", json!({})).unwrap();
let rect = json!({"subpaths": [{"closed": true, "knots": [[10, 10], [200, 10], [200, 100], [10, 100]]}]});
s.execute("layer.vectorMask.add", json!({"layer": id.0, "path": rect})).unwrap();
let listed = s.execute("path.list", json!({})).unwrap();
assert_eq!((listed["layerPath"]["kind"].as_str(), listed["typePath"]["kind"].as_str()), (Some("vectorMask"), Some("typePath")), "{listed}");
let type_path = |s: &Session| crate::type_extra_cmds::type_path(text(s, id)).unwrap();
let before = type_path(&s);
let mask = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().vector_mask.as_ref().unwrap().path.subpaths[0].knots[0].anchor;
s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 0]], "move": [10, 0]})).unwrap();
assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask's corner moved");
assert_eq!(type_path(&s), before, "the Type Path stays");
s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "typePath": true, "anchors": [[0, 1]], "move": [20, 0]})).unwrap();
assert!((type_path(&s).subpaths[0].knots[1].anchor.x - before.subpaths[0].knots[1].anchor.x - 20.0).abs() < 1e-6, "the Type Path moved");
assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask stays");
}
/// An edit can't grow the Type Path past the cap `type.attachToPath` keeps.
#[test]
fn an_edited_type_path_keeps_the_knot_cap() {
let mut s = session(8);
let id = text_layer(&mut s, "Hi");
let knots: Vec<(f64, f64)> = (0..=MAX_TYPE_PATH_KNOTS).map(|i| (i as f64 * 0.001, 50.0)).collect();
let mut t = text(&s, id).clone();
t.shape = TextShape::Path { path: Subpath::polyline(&knots[..2]), start: 0.0, flip: false };
assert!(set_type_path(&mut t, &Path::new(vec![Subpath::polyline(&knots[..MAX_TYPE_PATH_KNOTS])])).is_ok());
assert!(set_type_path(&mut t, &Path::new(vec![Subpath::polyline(&knots)])).is_err());
}
/// The Type tool's click on a path: `"at"` starts the type where the path passes nearest the
/// click, and the paragraph alignment is kept about that point, as in Photoshop.
#[test]
+9 -2
View File
@@ -889,7 +889,8 @@ fn paths_list(s: &Session) -> Result<Value> {
let d = s.active().ok_or(EngineError::NoDocument)?;
let doc = &d.doc;
let knots = |p: &Path| p.subpaths.iter().map(|s| s.knots.len()).sum::<usize>();
let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| match &l.content {
let active = d.active_layer.and_then(|id| doc.layer(id));
let layer = active.and_then(|l| match &l.content {
LayerContent::Shape(sh) => Some(json!({ "kind": "shape", "layer": l.id.0, "name": format!("{} Shape Path", l.name), "knots": knots(&sh.path) })),
_ => {
l.vector_mask.as_ref().map(|v| json!({ "kind": "vectorMask", "layer": l.id.0, "name": format!("{} Vector Mask", l.name), "knots": knots(&v.path) }))
@@ -900,6 +901,12 @@ fn paths_list(s: &Session) -> Result<Value> {
"workPath": doc.work_path.as_ref().map(|p| json!({ "knots": knots(p), "subpaths": p.subpaths.len() })),
"clippingPath": doc.clipping_path.as_ref().map(|c| json!({ "name": c.name, "flatness": c.flatness })),
"layerPath": layer,
// Type on a path: Photoshop's Type Path, which Direct Selection edits (#9114).
"typePath": active.and_then(|l| match &l.content {
LayerContent::Text(t) => crate::type_extra_cmds::type_path(t)
.map(|p| json!({ "kind": "typePath", "layer": l.id.0, "name": format!("{} Type Path", l.name), "knots": knots(&p) })),
_ => None,
}),
}))
}
@@ -1835,7 +1842,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "List Paths",
menu: &[],
shortcut: None,
params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask)}"##,
params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask),typePath (active type layer's Type Path, if it is on a path)}"##,
enabled: has_doc,
run: |s, _| paths_list(s),
journal: false,
+14 -7
View File
@@ -1,7 +1,7 @@
//! Direct Selection tool (A, #790), the Convert Point tool (#3204), the Pens' ⌘/Ctrl (Direct
//! Selection: the Pen, Freeform Pen and Curvature Pen) and the Pen's ⌥/Alt (Convert Point)
//! modifiers, as in Photoshop. It edits the paths the canvas shows: the targeted vector mask or
//! the active shape layer's path, and the work path.
//! modifiers, as in Photoshop. It edits the paths the canvas shows: the targeted vector mask, the
//! active shape layer's path or the active type layer's Type Path, and the work path.
//!
//! * Click an anchor to select it (⇧ adds or removes, ⌥ selects its whole subpath), drag on empty
//! canvas to marquee-select anchors, click empty canvas to deselect.
@@ -39,6 +39,8 @@ pub enum PathRef {
Work,
/// A layer's shape path, or its vector mask.
Layer(u64),
/// A type layer's Type Path (#9114), apart from a vector mask the layer may have.
TypePath(u64),
/// The Pen path being drawn (`ui.pen`): edited in place, not through the engine.
Pen,
}
@@ -49,6 +51,7 @@ impl PathRef {
match self {
PathRef::Work => json!({"name": "work"}),
PathRef::Layer(id) => json!({"name": "layer", "layer": id}),
PathRef::TypePath(id) => json!({"name": "layer", "layer": id, "typePath": true}),
// Never sent: edits to the Pen path being drawn don't go through the engine.
PathRef::Pen => json!({}),
}
@@ -163,12 +166,16 @@ pub fn shows(app: &PhotocraftApp, mods: Modifiers) -> bool {
|| matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint)
}
/// The active paths, front first: the targeted vector mask or the active shape layer's path, then
/// the work path. The Pen's Auto Add/Delete edits these (`anchor_tools::pen_auto`).
/// The active paths, front first: the targeted vector mask, the active shape layer's path or the
/// active type layer's Type Path (#9114), then the work path. The Pen's Auto Add/Delete edits these
/// (`anchor_tools::pen_auto`).
pub(crate) fn active_paths(app: &PhotocraftApp) -> Vec<(PathRef, Path)> {
let layer = crate::vector_ui::targeted_vector_mask(app).or_else(|| crate::vector_ui::active_shape_path(app));
let layer = crate::vector_ui::targeted_vector_mask(app)
.or_else(|| crate::vector_ui::active_shape_path(app))
.map(|(id, p)| (PathRef::Layer(id), p))
.or_else(|| crate::vector_ui::active_type_path(app).map(|(id, p)| (PathRef::TypePath(id), p)));
let work = app.session.active().and_then(|st| st.doc.work_path.clone());
layer.map(|(id, p)| (PathRef::Layer(id), p)).into_iter().chain(work.map(|p| (PathRef::Work, p))).collect()
layer.into_iter().chain(work.map(|p| (PathRef::Work, p))).collect()
}
/// The paths Direct Selection edits, front first: the Pen path being drawn, the active paths, then
@@ -301,7 +308,7 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) -
app.ui.direct_selection.drag = Some(Drag::Marquee { start: p, end: p, add: mods.shift });
return true;
};
if let PathRef::Layer(id) = target
if let PathRef::Layer(id) | PathRef::TypePath(id) = target
&& app.session.active().and_then(|st| st.active_layer).map(|l| l.0) != Some(id)
{
let _ = app.run("layer.select", json!({"layer": id}));
+52
View File
@@ -517,3 +517,55 @@ fn a_curvature_pen_double_click_through_the_canvas_rounds_a_corner() {
assert!(k.smooth && k.in_ctrl != k.anchor, "the double-clicked corner is smooth: {k:?}");
assert!(h.state().ui.pen.is_none(), "and no path was started");
}
/// #9114: with type on a path selected, Direct Selection reshapes the type's own path (in front of
/// the work path it was made from) and the type follows, in one undoable step.
#[test]
fn dragging_an_anchor_of_type_on_a_path_moves_the_type() {
let mut app = app(Tool::DirectSelection);
app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[100, 20], [100, 180]]}]}})).unwrap();
let id = app.run("type.create", json!({"x": 20, "y": 70, "text": "On a path", "size": 24})).unwrap()["layer"].as_u64().unwrap();
app.run("type.attachToPath", json!({})).unwrap();
let type_path = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content {
photocraft_doc::LayerContent::Text(t) => photocraft_engine::type_extra_cmds::type_path(t).unwrap(),
_ => panic!("not a type layer"),
};
let n = steps(&app);
drag(&mut app, [100.2, 180.2], [160.2, 180.2], Modifiers::NONE);
assert_eq!(app.ui.direct_selection.target, Some(PathRef::TypePath(id)), "the type path, in front of the work path");
let end = type_path(&app).subpaths[0].knots[1].anchor;
assert!((end.x - 160.0).abs() < 1e-6 && (end.y - 180.0).abs() < 1e-6, "{end:?}");
assert_eq!(work(&app).subpaths[0].knots[1].anchor, Point::new(100.0, 180.0), "the work path stays");
assert_eq!(steps(&app), n + 1);
assert!(app.session.undo());
assert_eq!(type_path(&app).subpaths[0].knots[1].anchor.x.round(), 100.0);
}
/// #9114: with a type-on-a-path layer's vector mask targeted, Direct Selection edits the mask, not
/// the Type Path; untargeted, it edits the Type Path and the mask stays.
#[test]
fn a_targeted_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() {
let mut app = app(Tool::DirectSelection);
app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[100, 20], [100, 180]]}]}})).unwrap();
let id = app.run("type.create", json!({"x": 20, "y": 70, "text": "On a path", "size": 24})).unwrap()["layer"].as_u64().unwrap();
app.run("type.attachToPath", json!({})).unwrap();
let rect = json!({"subpaths": [{"closed": true, "knots": [[20, 20], [180, 20], [180, 160], [20, 160]]}]});
app.run("layer.vectorMask.add", json!({"layer": id, "path": rect})).unwrap();
app.ui.vector_mask_target = true;
let layer = |app: &PhotocraftApp| app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().clone();
let type_path = |app: &PhotocraftApp| match &layer(app).content {
photocraft_doc::LayerContent::Text(t) => photocraft_engine::type_extra_cmds::type_path(t).unwrap(),
_ => panic!("not a type layer"),
};
let before = type_path(&app);
drag(&mut app, [20.2, 20.2], [40.2, 30.2], Modifiers::NONE);
assert_eq!(app.ui.direct_selection.target, Some(PathRef::Layer(id)));
assert_eq!(layer(&app).vector_mask.unwrap().path.subpaths[0].knots[0].anchor, Point::new(40.0, 30.0), "the mask's corner moved");
assert_eq!(type_path(&app), before, "the Type Path stays");
// With the mask no longer targeted, the Type Path is in front again and the mask stays.
app.ui.vector_mask_target = false;
drag(&mut app, [100.2, 180.2], [160.2, 180.2], Modifiers::NONE);
assert_eq!(app.ui.direct_selection.target, Some(PathRef::TypePath(id)));
assert!((type_path(&app).subpaths[0].knots[1].anchor.x - 160.0).abs() < 1e-6);
assert_eq!(layer(&app).vector_mask.unwrap().path.subpaths[0].knots[0].anchor, Point::new(40.0, 30.0));
}
+27
View File
@@ -920,6 +920,16 @@ pub(crate) fn targeted_vector_mask(app: &PhotocraftApp) -> Option<(u64, Path)> {
l.vector_mask.as_ref().map(|m| (l.id.0, m.path.clone()))
}
/// The active type layer's path in document space, if it is type on a path (#9114).
pub(crate) fn active_type_path(app: &PhotocraftApp) -> Option<(u64, Path)> {
let st = app.session.active()?;
let l = st.active_layer.and_then(|id| st.doc.layer(id))?;
match &l.content {
LayerContent::Text(t) => photocraft_engine::type_extra_cmds::type_path(t).map(|p| (l.id.0, p)),
_ => None,
}
}
/// The active shape layer's path, if the active layer is a shape layer.
pub(crate) fn active_shape_path(app: &PhotocraftApp) -> Option<(u64, Path)> {
let st = app.session.active()?;
@@ -1238,6 +1248,10 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform
if let Some((_, p)) = targeted_vector_mask(app) {
draw_path(&p, anchors);
}
// So does type on a path's Type Path, which the Pen's Auto Add/Delete edits (#9114).
if let Some((_, p)) = active_type_path(app) {
draw_path(&p, anchors);
}
crate::corner_radius::draw(app, painter, &to_scr, accent);
}
// Pen path in progress, with handles of the last knot and a rubber band to the pointer. While
@@ -2305,6 +2319,19 @@ mod tests {
}
}
/// #9114: the active type layer's Type Path shows with the Pen, whose Auto Add/Delete edits it.
#[test]
fn the_type_path_of_type_on_a_path_is_drawn_with_the_pen() {
let ctx = egui::Context::default();
let mut app = app();
app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[100, 20], [100, 180]]}]}})).unwrap();
app.run("type.create", json!({"x": 20, "y": 70, "text": "On a path", "size": 24})).unwrap();
app.run("type.attachToPath", json!({})).unwrap();
app.run("path.delete", json!({"name": "work"})).unwrap();
app.ui.tool = Tool::Pen;
assert!(overlay_shapes(&app, &ctx) > 0, "the Type Path is drawn");
}
#[test]
fn show_target_path_and_extras_hide_the_path_outlines() {
// #1119: View › Show › Target Path only flipped its checkmark; the canvas kept drawing the