diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index da1eff9085..d7e323624e 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -20,7 +20,7 @@ next to them. | `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) | | `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) | | `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) | -| `assets/icons/*.svg` except `slice-knife.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (112 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/*.svg` except `slice-knife.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (112 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/{check,chevron-down,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | @@ -30,6 +30,7 @@ next to them. | `assets/icons/brush-replace.svg` | Color Replacement tool glyph: Lucide `brush` plus two swap arrows | Lucide Icons and Contributors; arrows by PhotoCraft contributors | Derived from `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/bandage-sparkle.svg` | Remove tool glyph: Lucide `bandage` moved down, plus a sparkle mark | Lucide Icons and Contributors; mark by PhotoCraft contributors | Derived from `icons/bandage.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/direct-select.svg` | Direct Selection tool glyph: Lucide `mouse-pointer-2` plus an anchor square | Lucide Icons and Contributors; square by PhotoCraft contributors | Derived from `icons/mouse-pointer-2.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/pen-add-anchor.svg`, `assets/icons/pen-delete-anchor.svg` | Add Anchor Point and Delete Anchor Point tool glyphs: Lucide `pen-tool` plus a + or − mark | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from `icons/pen-tool.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/painting-symmetry.svg` | Painting symmetry glyph: Lucide `heart` with a central axis | Lucide Icons and Contributors; adapted by @shorbank | Derived from `icons/heart.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/symmetry-{vertical,horizontal,dual,diagonal}.svg` | Painting symmetry axis glyphs | @shorbank | Original work; supplied SVG line geometry centred on a common square canvas, stroke adjusted to match the painting-symmetry glyph | MIT OR Apache-2.0, [`assets/icons/LICENSE-symmetry-axes.txt`](assets/icons/LICENSE-symmetry-axes.txt) | | `assets/icons/lasso-magnetic.svg` | Magnetic Lasso tool glyph, adapted from "Magnetic Lasso Tool" (redrawn on the 24 px toolbar grid) | Lil' Seal (Noun Project); adapted by PhotoCraft contributors | | CC BY 3.0, [`assets/icons/LICENSE-noun-magnetic-lasso.txt`](assets/icons/LICENSE-noun-magnetic-lasso.txt) | diff --git a/README.md b/README.md index 1e550c03f0..be6e1654c4 100644 --- a/README.md +++ b/README.md @@ -178,8 +178,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
-

🧰 56 tools

- Move · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Slice · Slice Select · Eyedropper · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Horizontal and Vertical Type · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom +

🧰 58 tools

+ Move · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Slice · Slice Select · Eyedropper · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Add Anchor Point · Delete Anchor Point · Horizontal and Vertical Type · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom

🖌️ A real brush engine

diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index 2d1f48299b..cc8aa5434d 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -7,6 +7,7 @@ use std::io::Write; use std::path::{Path, PathBuf}; use photocraft_automation::{AuthorizedWorkspace, Headless, PhotocraftMcp, files, security}; +use photocraft_engine::actions_cmds::Action; use photocraft_io::ExportOptions; use serde_json::{Value, json}; @@ -23,11 +24,14 @@ USAGE: photocraft-cli run ( | --new ) --cmd [--params ] [--cmd …] [--out ] [--format ] [--quality <1-100>] [--tiff-layers] Open a file, run engine commands in order, save the result. Each --params applies to the preceding --cmd. Prints each command's JSON result. - photocraft-cli batch --actions --in --out [--format ] [--quality <1-100>] [--in-place] [--tiff-layers] + photocraft-cli batch --actions [--action ] --in --out [--format ] [--quality <1-100>] [--in-place] [--tiff-layers] Apply an action list to every image in a directory. Steps are [id, params] pairs, {\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them - (a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An --out folder that is the - --in folder is refused, as the results would replace the originals; --in-place allows it. + (a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An Actions set (the Actions + panel's actions.json, {\"actions\": [{\"name\", \"steps\"}…]}) plays the action --action names (needed + when the set holds more than one) with the whole set loaded, so its steps can play other actions + of the set. An --out folder that is the --in folder is refused, as the results would replace + the originals; --in-place allows it. photocraft-cli droplet … [--out ] Run a droplet (File › Automate › Create Droplet) on images and folders. photocraft-cli commands [--json] [--filter ] @@ -64,7 +68,12 @@ const SUBCOMMANDS: &[Subcommand] = &[ Subcommand { name: "convert", values: &["--format", "--quality"], bare: &["--tiff-layers"], run: convert }, Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) }, Subcommand { name: "run", values: &["--new", "--cmd", "--params", "--out", "--format", "--quality"], bare: &["--tiff-layers"], run: run_cmds }, - Subcommand { name: "batch", values: &["--actions", "--in", "--out", "--format", "--quality"], bare: &["--in-place", "--tiff-layers"], run: batch }, + Subcommand { + name: "batch", + values: &["--actions", "--action", "--in", "--out", "--format", "--quality"], + bare: &["--in-place", "--tiff-layers"], + run: batch, + }, Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet }, Subcommand { name: "commands", values: &["--filter"], bare: &["--json"], run: |a, out, _| commands(a, out) }, Subcommand { @@ -347,7 +356,39 @@ fn run_cmds(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R { /// list or wrapped in `{"actions": […]}`, `{"steps": […]}` or a droplet (#489). pub fn parse_actions(text: &str) -> Result, String> { let v: Value = serde_json::from_str(text).map_err(|e| format!("actions JSON: {e}"))?; - photocraft_engine::automate_cmds::parse_action(v.get("actions").unwrap_or(&v), "batch --actions").map_err(|e| e.to_string()) + steps_of(&v) +} + +fn steps_of(v: &Value) -> Result { + photocraft_engine::automate_cmds::parse_action(v.get("actions").unwrap_or(v), "batch --actions").map_err(|e| e.to_string()) +} + +/// Engine commands to run in order: `(id, params)`. +pub type Steps = Vec<(String, Value)>; + +/// The steps `batch` plays on each file, and the actions they can call. An Actions set (the +/// Actions panel's `actions.json`: `{"actions": [{"name", "steps"}…]}`, or the bare list) plays +/// the action `name` picks (optional when the set holds one) with the whole set loaded, as +/// Photoshop's Batch does; anything else is one action's steps ([`parse_actions`]) (#2786). +pub fn load_actions(text: &str, name: Option<&str>) -> Result<(Steps, Vec), String> { + let v: Value = serde_json::from_str(text).map_err(|e| format!("actions JSON: {e}"))?; + let list = v.get("actions").unwrap_or(&v); + let is_set = list.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|x| x.get("name").is_some_and(Value::is_string))); + if !is_set { + if name.is_some() { + return Err("--action picks an action from an Actions set ({\"actions\": [{\"name\", \"steps\"}…]}), but this file holds one action's steps".into()); + } + return Ok((steps_of(&v)?, Vec::new())); + } + let set: Vec = serde_json::from_value(list.clone()).map_err(|e| format!("Actions set: {e}"))?; + let names = || set.iter().map(|a| format!("`{}`", a.name)).collect::>().join(", "); + let action = match (name, set.as_slice()) { + (Some(n), _) => set.iter().find(|a| a.name == n).ok_or_else(|| format!("no action named `{n}` in the set (it holds {})", names()))?, + (None, [only]) => only, + (None, _) => return Err(format!("the Actions set holds {} actions: pick one with --action ({})", set.len(), names())), + }; + let play = vec![("actions.play".to_string(), json!({"action": action.name}))]; + Ok((play, set)) } /// Whether `a` and `b` name the same existing folder, however they are spelt (relative, with a @@ -369,7 +410,7 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R { let in_dir = PathBuf::from(a.get("--in").ok_or("batch needs --in ")?); let out_dir = PathBuf::from(a.get("--out").ok_or("batch needs --out ")?); let text = std::fs::read_to_string(actions_path).map_err(|e| format!("{actions_path}: {e}"))?; - let actions = parse_actions(&text)?; + let (actions, set) = load_actions(&text, a.get("--action"))?; let opts = export_opts(a)?; // Results are saved as `/.`, so an `--out` that is the `--in` folder would // replace the originals (#492). @@ -399,9 +440,16 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R { written.check(&target_text)?; let mut h = Headless::trusted_local(); h.session.model_backend = model_backend.clone(); + // Steps that play another action find it in the set; the session's playback stack + // stops an action that calls itself. + h.session.actions.list = set.clone(); h.open(input).map_err(|e| e.to_string())?; for (id, p) in &actions { - h.command_run(id, p.clone()).map_err(|e| format!("`{id}`: {e}"))?; + let r = h.command_run(id, p.clone()).map_err(|e| format!("`{id}`: {e}"))?; + // A failed step inside a called action makes this file an error, not a saved result. + if let Some(e) = photocraft_engine::actions_cmds::nested_failure(id, &r) { + return Err(format!("`{id}`: {e}")); + } } let r = h.save(None, Some(&target), Some(&ext), &opts).map_err(|e| e.to_string())?; Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default()) @@ -611,3 +659,54 @@ mod missing_font_warning_tests { let _ = std::fs::remove_dir_all(&folder); } } + +#[cfg(test)] +mod batch_action_set_tests { + use super::*; + + fn invoke(args: &[&str]) -> (i32, String, String) { + let (mut output, mut errors) = (Vec::new(), Vec::new()); + let args: Vec = args.iter().map(|s| s.to_string()).collect(); + let code = run(&args, &mut output, &mut errors); + (code, String::from_utf8(output).unwrap(), String::from_utf8(errors).unwrap()) + } + + /// A batched action that plays another action of its set finds it in every file's session; a + /// failure inside the called action fails the file, and a self-call stops instead of looping. + #[test] + fn batch_plays_an_action_that_calls_another_action_of_its_set() { + let dir = std::env::temp_dir().join(format!("photocraft-cli-action-set-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = |name: &str| dir.join(name).to_string_lossy().to_string(); + std::fs::create_dir_all(dir.join("in")).unwrap(); + for name in ["a", "b"] { + let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":8,"height":6}"#, "--out", &path(&format!("in/{name}.png"))]); + assert_eq!(code, 0, "{stderr}"); + } + let set = json!({"version": 1, "actions": [ + {"name": "Outer", "steps": [["actions.play", {"action": "Rotate"}]]}, + {"name": "Rotate", "steps": [["image.imageRotation.90cw", {}]]}, + {"name": "Calls bad", "steps": [["actions.play", {"action": "Bad"}]]}, + {"name": "Bad", "steps": [["layer.delete", {"layer": 999_999}]]}, + {"name": "Loop", "steps": [["actions.play", {"action": "Loop"}]]}, + ]}); + std::fs::write(dir.join("actions.json"), set.to_string()).unwrap(); + let batch = |action: &str| invoke(&["batch", "--actions", &path("actions.json"), "--action", action, "--in", &path("in"), "--out", &path(action)]); + + let (code, stdout, stderr) = batch("Outer"); + assert_eq!(code, 0, "{stdout}{stderr}"); + for name in ["a", "b"] { + let (code, info, stderr) = invoke(&["info", &path(&format!("Outer/{name}.png")), "--compact"]); + assert_eq!(code, 0, "{stderr}"); + let info: Value = serde_json::from_str(&info).unwrap(); + assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(6), Some(8)), "rotated by the called action"); + } + for action in ["Calls bad", "Loop"] { + let (code, stdout, stderr) = batch(action); + assert_ne!(code, 0, "{stdout}"); + assert_eq!(stderr.matches("FAIL").count(), 2, "{stderr}"); + assert!(!dir.join(action).join("a.png").exists(), "a file whose called action failed is not saved"); + } + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/assets/icons/pen-add-anchor.svg b/assets/icons/pen-add-anchor.svg new file mode 100644 index 0000000000..a4e565736c --- /dev/null +++ b/assets/icons/pen-add-anchor.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/assets/icons/pen-delete-anchor.svg b/assets/icons/pen-delete-anchor.svg new file mode 100644 index 0000000000..f8cee2f97c --- /dev/null +++ b/assets/icons/pen-delete-anchor.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/contributors/people.toml b/contributors/people.toml index 138ee9a079..5b92857fce 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -98,3 +98,6 @@ sync_github_name = true [people.FinnNk] sync_github_name = true + +[people.TheTeslak] +sync_github_name = true diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 3a436aabe9..00a344f98c 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -729,6 +729,8 @@ mod tests { | "path.moveHandle" | "path.bendSegment" | "path.convertPoint" + | "path.addAnchor" + | "path.deleteAnchor" | "path.clippingPath.set" | "path.rename" | "select.toWorkPath" diff --git a/crates/engine/src/path_edit_cmds.rs b/crates/engine/src/path_edit_cmds.rs index 53c4ba2528..6db84c270c 100644 --- a/crates/engine/src/path_edit_cmds.rs +++ b/crates/engine/src/path_edit_cmds.rs @@ -1,5 +1,6 @@ -//! Point-level path edits, what Photoshop's Direct Selection (A) and Convert Point tools do on -//! the canvas: move anchors, drag direction handles, bend segments and convert points. The +//! Point-level path edits, what Photoshop's Direct Selection (A), Convert Point and Add / Delete +//! Anchor Point tools do on the canvas: move anchors, drag direction handles, bend segments, +//! convert points, and insert or remove anchors. The //! geometry is `photocraft_vector::edit`; the canvas previews a drag with it and commits the //! whole drag as one command (one history step). //! @@ -109,6 +110,38 @@ fn convert_point(s: &mut Session, p: &Value) -> Result { edit_path(s, CMD, p, "Convert Point", |path| edit::convert_point(path, k, out)) } +fn add_anchor(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.addAnchor"; + let k = knot(CMD, p)?; + let t = match p.get("t") { + Some(v) => v.as_f64().filter(|t| *t > 0.0 && *t < 1.0).ok_or_else(|| bad(CMD, "`t` must be strictly between 0 and 1"))?, + None => 0.5, + }; + let mut added = None; + let mut r = edit_path(s, CMD, p, "Add Anchor Point", |path| { + added = Some(edit::add_anchor(path, k, t)?); + Ok(()) + })?; + if let (Some(o), Some([sp, kn])) = (r.as_object_mut(), added) { + o.insert("anchor".into(), json!({"subpath": sp, "knot": kn})); + } + Ok(r) +} + +fn delete_anchor(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.deleteAnchor"; + let k = knot(CMD, p)?; + let mut removed = false; + let mut r = edit_path(s, CMD, p, "Delete Anchor Point", |path| { + removed = edit::delete_anchor(path, k)?; + Ok(()) + })?; + if let Some(o) = r.as_object_mut() { + o.insert("subpathRemoved".into(), json!(removed)); + } + Ok(r) +} + pub fn specs() -> Vec { const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path or a vector mask)"#; let spec = |id: &'static str, label: &'static str, params: String, run: fn(&mut Session, &Value) -> Result| CommandSpec { @@ -141,6 +174,18 @@ pub fn specs() -> Vec { r#""subpath":i,"knot":j,"out":[x,y]? (none: corner with retracted handles; given: smooth with this out handle and its mirror)"#.into(), convert_point, ), + spec( + "path.addAnchor", + "Add Anchor Point", + r#""subpath":i,"knot":j (the segment leaving it),"t":0 serde_json::Value { + json!({"subpaths": [{"closed": false, "knots": [ + {"anchor": [10, 80], "in": [10, 80], "out": [10, 20]}, + {"anchor": [60, 50], "in": [40, 20], "out": [80, 80], "smooth": true}, + {"anchor": [110, 80], "in": [110, 20], "out": [110, 80]} + ]}]}) + } + + fn knots(s: &Session) -> usize { + work(s).subpaths.iter().map(|sp| sp.knots.len()).sum() + } + + #[test] + fn anchors_are_added_and_deleted_in_one_undoable_step_each() { + let mut s = session(); + s.execute("path.set", json!({"path": curve()})).unwrap(); + let before = work(&s); + let steps = s.active().unwrap().history.entries().len(); + let r = s.execute("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": 0.5})).unwrap(); + assert_eq!(r["anchor"], json!({"subpath": 0, "knot": 1})); + assert_eq!((knots(&s), s.active().unwrap().history.entries().len()), (4, steps + 1)); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Add Anchor Point")); + assert!(work(&s).subpaths[0].knots[1].smooth); + let added = work(&s); + assert!(s.undo()); + assert_eq!(work(&s), before, "one undo restores the path exactly"); + assert!(s.redo()); + assert_eq!(work(&s), added); + let r = s.execute("path.deleteAnchor", json!({"subpath": 0, "knot": 1})).unwrap(); + assert_eq!(r["subpathRemoved"], json!(false)); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); + assert_eq!(knots(&s), 3); + // Deleting the middle anchor of the original curve joins the ends with their own handles. + s.execute("path.set", json!({"path": curve()})).unwrap(); + s.execute("path.deleteAnchor", json!({"subpath": 0, "knot": 1})).unwrap(); + let k = &work(&s).subpaths[0].knots; + assert_eq!((k.len(), k[0].out_ctrl, k[1].in_ctrl), (2, before.subpaths[0].knots[0].out_ctrl, before.subpaths[0].knots[2].in_ctrl)); + } + + #[test] + fn anchor_tools_edit_saved_paths_shapes_and_vector_masks() { + let mut s = session(); + s.execute("path.set", json!({"name": "Outline", "path": square()})).unwrap(); + let r = s.execute("path.deleteAnchor", json!({"name": "Outline", "subpath": 0, "knot": 0})).unwrap(); + assert_eq!((r["path"]["subpaths"][0]["knots"].as_array().unwrap().len(), r["path"]["subpaths"][0]["closed"].clone()), (3, json!(true))); + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 120, "height": 100, "depth": depth})).unwrap(); + let id = s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + // Top edge, then pull the new midpoint up: the layer re-renders from the edited path. + let r = s.execute("path.addAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 0, "t": 0.5})).unwrap(); + assert_eq!(anchor(&r, 1), [30.0, 10.0]); + s.execute("path.moveAnchors", json!({"name": "layer", "layer": id, "anchors": [[0, 1]], "move": [0, -8]})).unwrap(); + let st = s.active().unwrap(); + let photocraft_doc::LayerContent::Shape(ShapeLayer { live, cache, .. }) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("shape") }; + assert!(live.is_none()); + assert_eq!(cache.as_ref().unwrap().content_bounds().y0, 2, "depth {depth}: re-rendered"); + s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 1})).unwrap(); + let st = s.active().unwrap(); + let photocraft_doc::LayerContent::Shape(ShapeLayer { cache, path, .. }) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("shape") }; + assert_eq!((path.subpaths[0].knots.len(), cache.as_ref().unwrap().content_bounds().y0), (4, 10), "depth {depth}"); + } + let id = s.active().unwrap().active_layer.unwrap().0; + s.execute("layer.vectorMask.add", json!({"layer": id, "path": square()})).unwrap(); + s.execute("path.addAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 3, "t": 0.5})).unwrap(); + let vm = s.active().unwrap().doc.layer(LayerId(id)).unwrap().vector_mask.clone().unwrap(); + assert_eq!(vm.path.subpaths[0].knots[4].anchor, photocraft_geom::Point::new(10.0, 35.0), "the closing segment's midpoint"); + } + + #[test] + fn the_last_anchor_of_a_shape_is_refused() { + let mut s = session(); + let one = json!({"subpaths": [{"closed": false, "knots": [[10, 10], [50, 10]]}]}); + let id = s.execute("shape.create", json!({"kind": "path", "path": one, "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 0})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + let e = s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 0})).unwrap_err(); + assert!(e.to_string().contains("only anchor"), "{e}"); + assert_eq!(s.active().unwrap().history.entries().len(), steps); + } + #[test] fn bad_params_fail_without_an_edit() { let mut s = session(); @@ -254,6 +380,18 @@ mod tests { ("path.convertPoint", json!({"subpath": 0, "knot": 0, "out": "x"})), ("path.convertPoint", json!({"name": "nope", "subpath": 0, "knot": 0})), ("path.convertPoint", json!({"name": "layer", "subpath": 0, "knot": 0})), + ("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": 0})), + ("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": 1})), + ("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": -0.5})), + ("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": "half"})), + ("path.addAnchor", json!({"subpath": 0, "knot": 4})), + ("path.addAnchor", json!({"subpath": 1, "knot": 0})), + ("path.addAnchor", json!({"knot": 0})), + ("path.addAnchor", json!({"name": "nope", "subpath": 0, "knot": 0})), + ("path.deleteAnchor", json!({"subpath": 0, "knot": 4})), + ("path.deleteAnchor", json!({"subpath": 0, "knot": -1})), + ("path.deleteAnchor", json!({"subpath": 0})), + ("path.deleteAnchor", json!({"name": "layer", "subpath": 0, "knot": 0})), ] { assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); } diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs index d538a6afcc..3357faa9a5 100644 --- a/crates/engine/src/type_cmds.rs +++ b/crates/engine/src/type_cmds.rs @@ -897,9 +897,52 @@ pub fn specs() -> Vec { } }, }, + size_key("type.increaseSize", "Increase Type Size", "Cmd+Shift+.", |s, p| step_size(s, p, true, 2.0)), + size_key("type.decreaseSize", "Decrease Type Size", "Cmd+Shift+,", |s, p| step_size(s, p, false, 2.0)), + size_key("type.increaseSizeMore", "Increase Type Size by 10", "Cmd+Alt+Shift+.", |s, p| step_size(s, p, true, 10.0)), + size_key("type.decreaseSizeMore", "Decrease Type Size by 10", "Cmd+Alt+Shift+,", |s, p| step_size(s, p, false, 10.0)), ] } +fn has_type_layer(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + match st.active_layer.and_then(|id| st.doc.layer(id)) { + Some(l) if matches!(l.content, LayerContent::Text(_)) => Ok(()), + _ => Err("the active layer is not a type layer".into()), + } +} + +/// Photoshop's ⇧⌘> / ⇧⌘< (⌥ for bigger steps). On a US keyboard > and < share the . and , keys. +fn size_key(id: &'static str, label: &'static str, shortcut: &'static str, run: fn(&mut Session, &Value) -> Result) -> CommandSpec { + CommandSpec { + id, + label, + menu: &[], + shortcut: Some(shortcut), + params: r##"{"layer":id?,"range":[startChar,endChar]? (default all),"by":pt? (as the layer appears)}"##, + enabled: has_type_layer, + journal: true, + run, + } +} + +/// Grows or shrinks every character in the range by `by` points as the layer appears, so mixed +/// sizes keep their differences and a scaled layer steps in the points its size field shows. +fn step_size(s: &mut Session, p: &Value, up: bool, default_by: f32) -> Result { + let id = layer_id(s, p)?; + let by = f32p(p, "by").filter(|v| v.is_finite()).unwrap_or(default_by).abs().min(TYPE_SIZE_MAX_PT as f32); + with_text_layer(s, p, "Change Type Size", |t, _, _| { + let m = t.transform.m; + let scale = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() as f32; + let scale = if scale.is_finite() && scale > 1e-3 { scale } else { 1.0 }; + let delta = if up { by } else { -by } / scale; + let (a, b) = range_param(&t.text, p); + style_range(t, a, b, &|st| st.size_pt = (st.size_pt + delta).clamp(TYPE_SIZE_MIN_PT as f32, TYPE_SIZE_MAX_PT as f32)); + Ok(()) + })?; + info(s, &json!({ "layer": id.0 })) +} + #[cfg(test)] mod tests { use super::*; @@ -1036,6 +1079,42 @@ mod tests { assert_eq!(layer_name_of(&s, id), "Type Layer"); } + #[test] + fn size_keys_step_each_run_and_respect_layer_scale() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "size": 20})).unwrap(); + s.execute("type.increaseSize", json!({})).unwrap(); + let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| r.style.size_pt).collect::>(); + assert_eq!(sizes(&s), vec![14.0, 22.0], "every run grows by 2 pt"); + s.execute("type.decreaseSizeMore", json!({"range": [0, 5]})).unwrap(); + assert_eq!(sizes(&s)[0], 4.0, "only the range, by 10 pt"); + for _ in 0..2 { + s.execute("type.decreaseSize", json!({"range": [0, 5]})).unwrap(); + } + assert_eq!(sizes(&s)[0], TYPE_SIZE_MIN_PT as f32, "never below the smallest size"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(sizes(&s)[0], 2.0, "one undo step per press"); + + let scaled = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Big", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": scaled, "transform": [2.0, 0.0, 0.0, 2.0, 0.0, 80.0]})).unwrap(); + s.execute("type.increaseSize", json!({"layer": scaled})).unwrap(); + assert_eq!(text_layer(&s, scaled).char_runs()[0].style.size_pt, 13.0, "a 200% layer shows 24 pt and steps to 26 pt"); + } + + #[test] + fn size_keys_need_a_type_layer() { + let mut s = session(); + assert!(s.execute("type.increaseSize", json!({})).is_err()); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hi", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.increaseSize", json!({"by": "big"})).unwrap(); + s.execute("type.increaseSize", json!({"by": -3})).unwrap(); + s.execute("type.decreaseSize", json!({"by": 1e30, "range": [9, 0]})).unwrap(); + assert_eq!(text_layer(&s, id).char_runs()[0].style.size_pt, TYPE_SIZE_MIN_PT as f32, "bad steps fall back or clamp, never panic"); + assert_eq!(crate::commands::find("type.increaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+.")); + assert_eq!(crate::commands::find("type.decreaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+,")); + } + #[test] fn auto_name_skips_leading_blank_lines() { let mut s = session(); diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index 0db728017e..0323533074 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -499,7 +499,7 @@ pub fn guess_from_postscript(ps: &str) -> ResolvedFont { } #[cfg(not(target_arch = "wasm32"))] -fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec) { +pub(crate) fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec) { let Ok(rd) = std::fs::read_dir(dir) else { return; }; @@ -516,7 +516,7 @@ fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec Vec { +pub(crate) fn system_font_dirs() -> Vec { use std::path::PathBuf; let home = std::env::var_os("HOME").map(PathBuf::from); let mut v = Vec::new(); diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index a63b3d9c06..173b1c84c1 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -26,6 +26,7 @@ pub mod psd; pub mod psd_styles; pub mod raster; pub mod render; +pub mod scripts; pub mod served; pub mod spell; pub mod warp; diff --git a/crates/text/src/scripts.rs b/crates/text/src/scripts.rs new file mode 100644 index 0000000000..b6e0aae74f --- /dev/null +++ b/crates/text/src/scripts.rs @@ -0,0 +1,366 @@ +//! UI fallback fonts for the non-CJK scripts the bundled Inter / JetBrains Mono don't draw +//! (Thai, Arabic, Hebrew, the Indic scripts, ...): which characters belong to which script, and +//! which installed font files to try for it. +//! +//! Candidates come from the file names in the platform font directories (the same directories +//! [`crate::fonts::FontDb`] scans), listed once per process and only when first asked for, so +//! nothing is read at startup and no path is hard-coded per distribution. Noto fonts are matched +//! by their family-derived file names (`NotoSansThai-Regular.ttf`, `NotoSansThai[wght].ttf`), +//! platform fonts by their known file names (Leelawadee UI, Nirmala UI, Segoe UI, Geeza Pro, +//! Kohinoor, DejaVu Sans, Lohit, ...). A file name is only a hint: callers check that a face +//! really maps the character ([`covering_face`]) before using it. CJK has its own, +//! locale-ordered lists ([`crate::cjk`]). + +/// A script that needs a UI fallback font. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Script { + Thai, + Lao, + Khmer, + Myanmar, + Tibetan, + Arabic, + Hebrew, + Armenian, + Georgian, + Ethiopic, + Devanagari, + Bengali, + Gurmukhi, + Gujarati, + Oriya, + Tamil, + Telugu, + Kannada, + Malayalam, + Sinhala, +} + +impl Script { + pub const ALL: [Script; 20] = [ + Script::Thai, + Script::Lao, + Script::Khmer, + Script::Myanmar, + Script::Tibetan, + Script::Arabic, + Script::Hebrew, + Script::Armenian, + Script::Georgian, + Script::Ethiopic, + Script::Devanagari, + Script::Bengali, + Script::Gurmukhi, + Script::Gujarati, + Script::Oriya, + Script::Tamil, + Script::Telugu, + Script::Kannada, + Script::Malayalam, + Script::Sinhala, + ]; + + /// Font file names for this script, most preferred first: lowercase, without extension, + /// spaces, underscores or style suffix (`NotoSansThai-Bold.ttf` and `NotoSansThai[wght].ttf` + /// are both `notosansthai`). Noto first (the usual Linux font), then Windows, macOS and + /// other Linux families. + fn file_names(self) -> &'static [&'static str] { + use Script::*; + match self { + Thai => &[ + "notosansthai", + "notosansthailooped", + "notosansthaiui", + "notoserifthai", + "leelawui", + "leelawad", + "tahoma", + "thonburi", + "sukhumvitset", + "ayuthaya", + "loma", + "garuda", + "waree", + "kinnari", + "norasi", + ], + Lao => &["notosanslao", "notosanslaoui", "notoseriflao", "leelawui", "laosangammn", "laomn", "phetsarathot", "saysetthaot"], + Khmer => &["notosanskhmer", "notosanskhmerui", "notoserifkhmer", "leelawui", "daunpenh", "khmersangammn", "khmermn", "khmeros", "khmerossys"], + Myanmar => &["notosansmyanmar", "notosansmyanmarui", "notoserifmyanmar", "mmrtext", "myanmarsangammn", "myanmarmn", "padauk"], + Tibetan => &["notoseriftibetan", "himalaya", "kailasa", "jomolhari", "tibetanmachineuni"], + Arabic => &[ + "notosansarabic", + "notosansarabicui", + "notonaskharabic", + "notonaskharabicui", + "notokufiarabic", + "segoeui", + "tahoma", + "geezapro", + "sfarabic", + "dejavusans", + "kacstone", + "kacstbook", + "amiri", + "arial", + ], + Hebrew => &["notosanshebrew", "notoserifhebrew", "segoeui", "arialhb", "sfhebrew", "dejavusans", "arial", "freesans", "culmus"], + Armenian => &["notosansarmenian", "notoserifarmenian", "segoeui", "sylfaen", "mshtakan", "dejavusans", "freesans"], + Georgian => &["notosansgeorgian", "notoserifgeorgian", "segoeui", "sylfaen", "dejavusans", "freesans"], + Ethiopic => &["notosansethiopic", "notoserifethiopic", "ebrima", "kefa", "abyssinicasil"], + Devanagari => &[ + "notosansdevanagari", + "notosansdevanagariui", + "notoserifdevanagari", + "nirmala", + "mangal", + "kohinoor", + "kohinoordevanagari", + "itfdevanagari", + "devanagarimt", + "devanagarisangammn", + "lohitdevanagari", + "lohit-devanagari", + "gargi", + "freesans", + ], + Bengali => &[ + "notosansbengali", + "notosansbengaliui", + "notoserifbengali", + "nirmala", + "vrinda", + "kohinoorbangla", + "banglasangammn", + "banglamn", + "lohitbengali", + "lohit-bengali", + "lohit-assamese", + ], + Gurmukhi => &[ + "notosansgurmukhi", + "notosansgurmukhiui", + "notoserifgurmukhi", + "nirmala", + "raavi", + "gurmukhisangammn", + "gurmukhimn", + "lohit-gurmukhi", + "lohit-punjabi", + ], + Gujarati => &[ + "notosansgujarati", + "notosansgujaratiui", + "notoserifgujarati", + "nirmala", + "shruti", + "kohinoorgujarati", + "gujaratisangammn", + "gujaratimt", + "lohit-gujarati", + ], + Oriya => &["notosansoriya", "notosansoriyaui", "notoseriforiya", "nirmala", "kalinga", "oriyasangammn", "oriyamn", "lohit-odia", "lohit-oriya"], + Tamil => &["notosanstamil", "notosanstamilui", "notoseriftamil", "nirmala", "latha", "tamilsangammn", "tamilmn", "lohit-tamil"], + Telugu => { + &["notosanstelugu", "notosansteluguui", "notoseriftelugu", "nirmala", "gautami", "kohinoortelugu", "telugusangammn", "telugumn", "lohit-telugu"] + } + Kannada => &["notosanskannada", "notosanskannadaui", "notoserifkannada", "nirmala", "tunga", "kannadasangammn", "kannadamn", "lohit-kannada"], + Malayalam => { + &["notosansmalayalam", "notosansmalayalamui", "notoserifmalayalam", "nirmala", "kartika", "malayalamsangammn", "malayalammn", "lohit-malayalam"] + } + Sinhala => &["notosanssinhala", "notosanssinhalaui", "notoserifsinhala", "nirmala", "iskpota", "sinhalasangammn", "sinhalamn", "lklug"], + } + } +} + +/// The script of a character that needs a non-CJK fallback font, or `None`. +pub fn classify(c: char) -> Option