PhotoCraft: An open-source, photo editor written by scratch in pure Rust
feat(engine): add type.fillPath to wrap type inside a closed path
PanPDX2160d5d735b5
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 7ddad8073..9f5b359cd 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1356,6 +1356,7 @@ fn build() -> Vec<CommandSpec> {v.extend(crate::file_cmds::specs());v.extend(crate::exr_cmds::specs());v.extend(crate::type_extra_cmds::specs());+ v.extend(crate::type_area_cmds::specs());v.extend(crate::type_styles_cmds::specs());v.extend(crate::type_spell_cmds::specs());v.extend(crate::type_caret_cmds::specs());diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex d2aecf37d..40316fd9f 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -115,6 +115,7 @@ pub mod symmetry_cmds;mod timeline_cmds;pub mod transform_cmds;mod trap_cmds;+pub mod type_area_cmds;pub mod type_caret_cmds;pub mod type_cmds;pub mod type_extra_cmds;diff --git a/crates/engine/src/type_area_cmds.rs b/crates/engine/src/type_area_cmds.rsnew file mode 100644index 000000000..09b22b0fc--- /dev/null+++ b/crates/engine/src/type_area_cmds.rs@@ -0,0 +1,97 @@+//! Area type (#218): type that wraps inside a closed path, like Photoshop's Type tool clicked+//! inside a closed path or shape. `type.detachFromPath` (type_extra_cmds.rs) releases it.++use photocraft_doc::text::TextShape;+use photocraft_doc::vector::{Knot, Path};+use photocraft_doc::{Document, LayerContent, LayerId};+use photocraft_geom::Point;+use serde_json::{Value, json};++use crate::commands::{CommandSpec, layer_param};+use crate::type_extra_cmds::with_text;+use crate::{EngineError, Result, Session};++const CMD: &str = "type.fillPath";++/// Largest total anchor count of a path area type can fill (as for type on a path).+const MAX_AREA_KNOTS: usize = 100_000;++fn bad(m: &str) -> EngineError {+ EngineError::BadParams { cmd: CMD.into(), msg: m.into() }+}++fn has_text(s: &Session) -> std::result::Result<(), String> {+ let d = s.active().ok_or("no document open")?;+ match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) {+ Some(LayerContent::Text(_)) => Ok(()),+ _ => Err("the active layer is not a type layer".into()),+ }+}++/// The path area type fills, in document space: the work path (default) or a shape layer's+/// path (`"shape":id`). Every closed subpath counts, with its path operation.+fn area_source(doc: &Document, p: &Value) -> Result<Path> {+ let path = match p.get("shape") {+ None | Some(Value::Null) => doc.work_path.as_ref().ok_or_else(|| bad("the document has no work path; draw a closed path or pass \"shape\":layerId"))?,+ Some(v) => {+ let id = v.as_u64().ok_or_else(|| bad("\"shape\" must be a layer id"))?;+ match doc.layer(LayerId(id)).map(|l| &l.content) {+ Some(LayerContent::Shape(sh)) => &sh.path,+ Some(_) => return Err(bad("\"shape\" is not a shape layer")),+ None => return Err(EngineError::NoLayer(LayerId(id))),+ }+ }+ };+ let knots = path.subpaths.iter().fold(0usize, |n, s| n.saturating_add(s.knots.len()));+ if knots > MAX_AREA_KNOTS {+ return Err(bad("the path has too many anchor points"));+ }+ if path.inverted {+ return Err(bad("an inverted path has no inside to fill"));+ }+ Ok(path.clone())+}++fn fill_path(s: &mut Session, p: &Value) -> Result<Value> {+ let id = layer_param(s, p)?;+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;+ if doc.effective_locks(id).all {+ return Err(EngineError::Other("the type layer is locked".into()));+ }+ let source = area_source(doc, p)?;+ let n = source.subpaths.len();+ with_text(s, p, "Area Type", |t, _| {+ // The path is in document space; the layer keeps it in text space so the type lands+ // inside the path where it is drawn.+ 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 mut path = source.clone();+ for k in path.subpaths.iter_mut().flat_map(|s| s.knots.iter_mut()) {+ *k = Knot { anchor: map(k.anchor), in_ctrl: map(k.in_ctrl), out_ctrl: map(k.out_ctrl), smooth: k.smooth };+ }+ let vertical = t.orientation == photocraft_doc::text::Orientation::Vertical;+ if photocraft_text::area::AreaShape::new(&path, vertical).is_none() {+ return Err(bad("the path encloses no area; draw a closed path"));+ }+ t.shape = TextShape::Area { path };+ Ok(())+ })?;+ Ok(json!({"layer": id.0, "subpaths": n}))+}++pub fn specs() -> Vec<CommandSpec> {+ vec![CommandSpec {+ id: CMD,+ label: "Area Type",+ menu: &[],+ shortcut: None,+ params: r##"{"layer":id? (default active Type layer),"shape":layerId? (a shape layer; default the work path)} → the text wraps inside the path's closed subpaths, holes included"##,+ enabled: has_text,+ journal: true,+ run: fill_path,+ }]+}++#[cfg(test)]+#[path = "type_area_cmds/tests.rs"]+mod tests;diff --git a/crates/engine/src/type_area_cmds/tests.rs b/crates/engine/src/type_area_cmds/tests.rsnew file mode 100644index 000000000..083b01ffc--- /dev/null+++ b/crates/engine/src/type_area_cmds/tests.rs@@ -0,0 +1,115 @@+use super::*;+use photocraft_doc::text::TextShape;+use photocraft_doc::vector::{Path, PathOp, Subpath};+use photocraft_doc::{LayerContent, LayerId, TextLayer};+use serde_json::json;++fn session(depth: u32) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "background": "white"})).unwrap();+ s+}++fn text_layer(s: &mut Session, text: &str) -> LayerId {+ let r = s.execute("type.create", json!({"x": 100, "y": 100, "text": text, "size": 14, "color": "#000000"})).unwrap();+ LayerId(r["layer"].as_u64().unwrap())+}++fn text(s: &Session, id: LayerId) -> &TextLayer {+ match &s.active().unwrap().doc.layer(id).unwrap().content {+ LayerContent::Text(t) => t,+ c => panic!("not text: {}", c.kind_name()),+ }+}++fn set_work_path(s: &mut Session, p: Path) {+ s.edit("path", |doc, _| {+ doc.work_path = Some(p);+ Ok(())+ })+ .unwrap();+}++const WORDS: &str = "Well, that went better than expected. Now where did the cat hide the keys?";++#[test]+fn fill_path_wraps_text_inside_the_work_path_in_one_step() {+ for depth in [8, 16, 32] {+ let mut s = session(depth);+ let id = text_layer(&mut s, WORDS);+ set_work_path(&mut s, Path::new(vec![Subpath::polygon(&[(50.0, 50.0), (250.0, 50.0), (250.0, 200.0), (50.0, 200.0)])]));+ let steps = s.active().unwrap().history.entries().len();+ let r = s.execute("type.fillPath", json!({})).unwrap();+ assert_eq!(r["layer"], json!(id.0));+ assert_eq!(s.active().unwrap().history.entries().len(), steps + 1, "one history step");+ assert!(matches!(text(&s, id).shape, TextShape::Area { .. }));+ // The ink stays inside the path, in document space.+ let ink = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds();+ assert!(ink.x0 >= 49 && ink.x1 <= 251 && ink.y0 >= 49 && ink.y1 <= 201, "depth {depth}: {ink:?}");+ assert!(ink.height() > 30, "several lines");+ assert!(s.undo());+ assert_eq!(text(&s, id).shape, TextShape::Point);+ assert!(s.redo());+ assert!(matches!(text(&s, id).shape, TextShape::Area { .. }));+ }+}++#[test]+fn fill_path_uses_a_shape_layer_with_its_hole() {+ let mut s = session(8);+ let shape = s.execute("shape.create", json!({"kind": "rect", "rect": [20, 20, 300, 200], "fill": "#cccccc"})).unwrap()["layer"].as_u64().unwrap();+ s.execute("shape.create", json!({"kind": "rect", "rect": [140, 80, 60, 80], "addTo": shape, "op": "subtract"})).unwrap();+ let id = text_layer(&mut s, &WORDS.repeat(3));+ s.execute("type.fillPath", json!({"layer": id.0, "shape": shape})).unwrap();+ let TextShape::Area { path } = &text(&s, id).shape else { panic!("area") };+ assert_eq!(path.subpaths.len(), 2);+ assert_eq!(path.subpaths[1].op, PathOp::Subtract);+}++#[test]+fn fill_path_maps_the_path_into_text_space() {+ let mut s = session(8);+ let id = text_layer(&mut s, WORDS); // transform: translate(100, 100)+ set_work_path(&mut s, Path::new(vec![Subpath::polygon(&[(100.0, 100.0), (300.0, 100.0), (300.0, 250.0), (100.0, 250.0)])]));+ s.execute("type.fillPath", json!({})).unwrap();+ let TextShape::Area { path } = &text(&s, id).shape else { panic!("area") };+ let a = path.subpaths[0].knots[0].anchor;+ assert!((a.x, a.y) == (0.0, 0.0), "{a:?}");+}++#[test]+fn fill_path_rejects_bad_paths_without_history() {+ let mut s = session(8);+ assert!(!s.is_enabled("type.fillPath"), "no type layer");+ let id = text_layer(&mut s, WORDS);+ assert!(s.is_enabled("type.fillPath"));+ let history = |s: &Session| s.active().unwrap().history.entries().len();+ // No work path.+ assert!(s.execute("type.fillPath", json!({})).is_err());+ for bad in [+ Path::new(vec![Subpath::polyline(&[(0.0, 0.0), (90.0, 90.0), (0.0, 90.0)])]), // open only+ Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (90.0, 0.0), (180.0, 0.0)])]), // no area+ Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (f64::NAN, 0.0), (9.0, 9.0)])]),+ {+ let mut p = Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (90.0, 0.0), (90.0, 90.0)])]);+ p.inverted = true;+ p+ },+ Path::new(vec![Subpath::polygon(&(0..100_001).map(|i| ((i as f64).cos() * 90.0, (i as f64).sin() * 90.0)).collect::<Vec<_>>())]),+ ] {+ set_work_path(&mut s, bad);+ let h = history(&s);+ assert!(s.execute("type.fillPath", json!({})).is_err());+ assert_eq!(history(&s), h, "no history step on error");+ assert_eq!(text(&s, id).shape, TextShape::Point);+ }+ for p in [json!({"shape": "x"}), json!({"shape": u64::MAX}), json!({"layer": u64::MAX})] {+ assert!(s.execute("type.fillPath", p).is_err());+ }+ // A shape param that is not a shape layer.+ assert!(s.execute("type.fillPath", json!({"shape": id.0})).is_err());+ // Locked layer.+ set_work_path(&mut s, Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (200.0, 0.0), (200.0, 200.0)])]));+ s.execute("layer.setProps", json!({"layer": id.0, "locked": true})).unwrap();+ assert!(s.execute("type.fillPath", json!({})).is_err());+}diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/type_extra_cmds.rsindex 569af27c9..907b991c4 100644--- a/crates/engine/src/type_extra_cmds.rs+++ b/crates/engine/src/type_extra_cmds.rs@@ -70,7 +70,7 @@ fn has_defaults(s: &Session) -> std::result::Result<(), String> {// ---------- helpers ----------/// Edits a type layer as one history step and re-renders it.-fn with_text<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut TextLayer, &Document) -> Result<R>) -> Result<R> {+pub(crate) fn with_text<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut TextLayer, &Document) -> Result<R>) -> Result<R> {let id = layer_param(s, p)?;check_text_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?;s.edit(label, |doc, _| {