From acc07f19d6a07aa41e00e749f8d5dbcbb51b5162 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:00:16 -0800 Subject: [PATCH] Links: Unembed leaves a released or edited clipping mask as it is Unembed re-applied the clipping path read back from the PNG or TIFF it had just written, with a path and with a folder. A clipping mask released in the document came back, and a mask edited in the document got a clip group of the file's original path nested inside it. The same held for a distorted image. Unembed now leaves a clipping mask released, edited or made in the document as it is. A clip group of the file's own clipping path still follows the file written, as before. --- crates/engine/src/cmd/fileio/tests_psdread.rs | 72 +++++++++++++++++++ crates/engine/src/cmd/links.rs | 42 ++++++++--- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 109 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 7a56932aed..37f4b132b5 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -863,6 +863,78 @@ fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { } } +/// Unembed leaves a clipping mask released or edited in the document as it is, with a path and with +/// a folder, for a plain image and for a distorted one: no clip group of the file's clipping path is +/// put back or nested inside the edited mask. Every case runs, and the test names each one that +/// fails. +#[test] +fn unembed_keeps_a_released_or_edited_clipping_mask() { + let dir = vectorcraft_testkit::TempDir::new("psd-unembed-mask"); + let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources())); + let cases = ["release", "move"] + .into_iter() + .flat_map(|edit| [false, true].into_iter().flat_map(move |distort| [(edit, distort, false), (edit, distort, true)])); + let failed: Vec<_> = cases + .filter(|&(edit, distort, folder)| { + std::panic::catch_unwind(|| unembed_mask_case(&dir.join(format!("{edit}-{distort}-{folder}")), &data, edit, distort, folder)).is_err() + }) + .collect(); + assert!(failed.is_empty(), "failed: {failed:?}"); +} + +/// One case of [`unembed_keeps_a_released_or_edited_clipping_mask`]: the clipping mask of a placed +/// PSD file's image released or moved (`edit`), the image or the clip group then distorted with +/// `distort`, and the image unembedded into `out`. +fn unembed_mask_case(out: &std::path::Path, data: &str, edit: &str, distort: bool, folder: bool) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + if edit == "release" { + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.clippingMask.release", &json!({})).unwrap(); + } else { + let Some(NodeKind::Group { children, .. }) = s.doc().unwrap().doc.node(group).map(|n| &n.kind) else { panic!("a clip group") }; + let mask = children[0].id; + s.execute("select.set", &json!({"ids": [mask.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + } + if distort { + let target = if edit == "release" { image } else { group }; + s.execute("select.set", &json!({"ids": [target.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image(), "{edit}, folder: {folder}: distorted"); + } + let parent = |s: &Session| s.doc().unwrap().doc.parent_of(image); + let before = (parent(&s), parent(&s).and_then(|p| s.doc().unwrap().doc.node(p).cloned())); + std::fs::create_dir_all(out).unwrap(); + if folder { + s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap(); + } else { + s.execute("links.unembed", &json!({"id": image.0, "path": out.join("cut")})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; + assert!(im.link.is_some(), "{edit}, folder: {folder}: linked to the file written"); + assert_eq!(parent(&s), before.0, "{edit}, folder: {folder}: the image stays where it was"); + let after = before.0.and_then(|p| d.node(p)); + match (edit, after.map(|n| &n.kind), before.1.as_ref().map(|n| &n.kind)) { + // Released: the image is in no clip group, as before. + ("release", Some(NodeKind::Group { clip, .. }), _) => assert!(!clip, "folder: {folder}: the released mask came back"), + ("release", _, _) => {} + // Moved: the same clip group of the moved path holds just the image. + (_, Some(NodeKind::Group { children: a, clip: true }), Some(NodeKind::Group { children: b, clip: true })) => { + assert_eq!(a.len(), 2, "{edit}, folder: {folder}: a clip group was nested inside the edited mask"); + let path = |c: &std::sync::Arc| match &c.kind { + NodeKind::Path { path, .. } => path.anchors().map(|(_, _, a)| [a.p.x, a.p.y]).collect::>(), + _ => vec![], + }; + assert_eq!((path(&a[0]), a[1].id), (path(&b[0]), image), "{edit}, folder: {folder}: the clipping mask"); + } + other => panic!("{edit}, folder: {folder}: {other:?}"), + } +} + /// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a /// text chunk within the size limit that reads as a path gives one back. #[test] diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index fccff66c0c..29da4d0524 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners). The image is written as stored (PNG, JPEG, GIF, WebP or TIFF; as PNG when that format is not one of VectorCraft's raster file formats) when path has no extension or names the stored format, and converted when path ends in another of .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp. Written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group (drawn through a distorted image's corners); a converted file holds no clipping path, and the clip group becomes a plain group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners). The image is written as stored (PNG, JPEG, GIF, WebP or TIFF; as PNG when that format is not one of VectorCraft's raster file formats) when path has no extension or names the stored format, and converted when path ends in another of .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp. Written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group (drawn through a distorted image's corners); a converted file holds no clipping path, and the clip group becomes a plain group. A clipping mask released, edited or made in the document stays as it is, in either case. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -1264,7 +1264,31 @@ fn warped(path: &PathData, map: &Homography) -> Option { /// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); /// with `also` (a file's path and the content shown), so do the images outside the layer tree that /// show that content. -fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { +fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { + install_with(d, ids, read, force, also, false) +} + +/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it +/// has a clipping path (`held`): a clipping mask released, edited or made in the document stays as +/// it is, and only a clip group of the old file's own clipping path follows the file written. +fn unembed_clip(to: ClipTo, held: bool) -> ClipTo { + match to { + ClipTo::Nest(_) => ClipTo::Keep, + ClipTo::File(_) if !held => ClipTo::Keep, + to => to, + } +} + +/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`]. +fn install_with( + d: &mut Document, + ids: &[NodeId], + (link, img): FileRead, + force: Option, + also: Option<(&str, &str)>, + unembed: bool, +) -> Result<()> { + let keep = |to: ClipTo, held: bool| if unembed { unembed_clip(to, held) } else { to }; let new_pt = super::place::pt_per_px(img.ppi); let mut clips = vec![]; let nested = nested_ids(d, ids); @@ -1290,7 +1314,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio _ => None, }; let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held); - return (n, clip); + return (n, keep(clip, held.is_some())); } if let NodeKind::Image(im) = &mut n.kind { let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; @@ -1300,7 +1324,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio None => (super::place::pt_per_px(None), None), }; let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); - clip = clip_to(im.xf, old_clip, c, &img, xf, held); + clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some()); (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); } (n, clip) @@ -1315,7 +1339,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio }; let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule)); if let Some(n) = d.node_mut(*id) { - clips.push((*id, refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))))); + let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); + clips.push((*id, keep(clip, held.is_some()))); } continue; } @@ -1326,7 +1351,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio // Placement Options' clip, else the clipping path of a DCS file (read again with its // plates) or of a PSD or PSB file. let old_clip = d.images.get(&im.key).and_then(file_clip); - clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id)))); + let held = clip_path_of(d, *id); + clips.push((*id, keep(clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, held), held.is_some()))); if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind { @@ -2829,7 +2855,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { write_file(&path, &bytes)?; let read = (link_info(&path, &bytes), img); drop(doc); - s.edit("Unembed", |d, _| editing_brush_art(d, |d| install(d, &[id], read, Some(Preserve::Bounds), None)))?; + s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?; Ok(json!({ "id": id.0, "path": path })) } @@ -2896,7 +2922,7 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re drop(doc); let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); let edited = s.edit("Unembed", |d, _| { - editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None))) + editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true))) }); if let Err(e) = edited { remove_written(&written); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..0f9f86dbcc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9899,7 +9899,8 @@ file is missing stays linked: relink it first); `links.unembed {id, path}` write (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. An image from a PSD or PSB file written as stored (PNG, or TIFF for a CMYK file), with `path` or `folder`, keeps the clip group of the clipping path that file names, and the file written keeps the path: Open, Place, Relink and Update Links read the file -with its clip group. +with its clip group. A clipping mask released, edited or made in the document stays as it is, whatever format the +image is written in. `ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of `id`; default: the selected embedded images) to a new file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..7ec540063d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2325,7 +2325,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group and leaves a clipping mask released, edited or made in the document as it is, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`).