Merge pull request #9576 from dotCooCoo/fix/replace-browser-picked-image

Replace Image: use files picked in the browser
This commit is contained in:
BFlat authored and GitHub committed 2026-11-27 08:35:17 +07:00
commit 459dcc54c5
5 files changed
+131 -18

No files matched your search

+55 -14
View File
@@ -76,6 +76,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
relink
),
cmd!(
"links.replaceEmbedded",
"Replace Image",
[],
None,
"{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}",
has_doc,
replace_embedded
),
cmd!(
query "links.list",
"Links",
@@ -1248,6 +1257,28 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
install(d, &[id], read, Some(Preserve::Bounds), None)
}
/// The browser's Replace Image uses embedded bytes and the same Fit installer as a path-based replacement.
fn replace_embedded(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.replaceEmbedded";
let ids = ids_param(p, "ids", C)?.filter(|ids| !ids.is_empty()).ok_or_else(|| bad(C, "give the image ids to replace"))?;
let doc = &s.doc()?.doc;
let mut seen = BTreeSet::new();
for id in &ids {
if !seen.insert(*id) {
return Err(bad(C, format!("image {} is listed twice", id.0)));
}
if !doc.node(*id).is_some_and(|node| matches!(node.kind, NodeKind::Image(_))) {
return Err(bad(C, format!("object {} is not an image", id.0)));
}
}
let data = text_param(p, "dataBase64", C)?.ok_or_else(|| bad(C, "give dataBase64"))?;
let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?;
let mut img = fileio::raster_image(&bytes)?;
img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?;
s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?;
Ok(json!({ "replaced": ids_json(&ids) }))
}
/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels
/// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the
/// transform still gives it its old size. Its Placement Options do not apply. The result is what
@@ -1256,13 +1287,19 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
/// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it:
/// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a
/// distort maps a path's.
fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo {
fn refill_distorted(
n: &mut Node,
old_clip: Option<&FileClip>,
link: Option<&LinkInfo>,
img: &RasterImage,
held: Option<(&PathData, FillRule)>,
) -> ClipTo {
let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule)));
if let NodeKind::Image(im) = &mut n.kind {
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
}
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, link.cloned());
}
let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule)));
placed_clip_to(old.as_ref(), None, file, held)
@@ -1292,8 +1329,8 @@ fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
/// 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], read: FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
install_with(d, ids, read, force, also, false)
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
install_with(d, ids, Some(&link), img, force, also, false)
}
/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it
@@ -1307,11 +1344,13 @@ fn unembed_clip(to: ClipTo, held: bool) -> ClipTo {
}
}
/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`].
/// Installs raster pixels with their filesystem link, if any. With `unembed`, each clip goes
/// through [`unembed_clip`].
fn install_with(
d: &mut Document,
ids: &[NodeId],
(link, img): FileRead,
link: Option<&LinkInfo>,
img: RasterImage,
force: Option<Preserve>,
also: Option<(&str, &str)>,
unembed: bool,
@@ -1341,7 +1380,7 @@ fn install_with(
NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()),
_ => None,
};
let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held);
let clip = refill_distorted(&mut n, old_clip.as_ref(), link, &img, held);
return (n, keep(clip, held.is_some()));
}
if let NodeKind::Image(im) = &mut n.kind {
@@ -1353,7 +1392,7 @@ fn install_with(
};
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
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()));
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
}
(n, clip)
};
@@ -1367,7 +1406,7 @@ fn install_with(
};
let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule));
if let Some(n) = d.node_mut(*id) {
let clip = 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;
@@ -1384,12 +1423,12 @@ fn install_with(
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
{
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
}
}
// A DCS file's spot plates print on spot swatches of their inks.
super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates());
store_image(d, &img.key, img.blob, true);
store_image(d, &img.key, img.blob, link.is_some());
clips.into_iter().try_for_each(|(id, clip)| match clip {
ClipTo::Keep => Ok(()),
ClipTo::Path(path) => clip_image_to(d, id, path),
@@ -2881,9 +2920,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
// Read before writing: pixels that can't be read leave no file behind.
let img = linked_image(&bytes, Some(&path))?;
write_file(&path, &bytes)?;
let read = (link_info(&path, &bytes), img);
let link = link_info(&path, &bytes);
drop(doc);
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?;
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)))?;
Ok(json!({ "id": id.0, "path": path }))
}
@@ -2950,7 +2989,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
drop(doc);
let done: Vec<Value> = 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_with(d, &[id], read, Some(Preserve::Bounds), None, true)))
editing_brush_art(d, |d| {
reads.into_iter().try_for_each(|(id, (link, img))| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true))
})
});
if let Err(e) = edited {
remove_written(&written);
+18 -4
View File
@@ -23,7 +23,7 @@ use std::collections::HashMap;
use std::sync::Arc;
use craft::behavior::{IconId, Selection, keyed};
use craft::host::{PickKind, PickRequest};
use craft::host::{PickKind, PickRequest, Picked};
use craft::keymap::CommandRef;
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _};
@@ -364,12 +364,26 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest, then: impl FnOnce(&mut Ve
/// say.
pub(crate) fn replace(app: &mut VectorcraftApp, ids: Vec<u64>) {
let request = vectorcraft_engine::cmd::fileio::place_filters().fold(PickRequest::open("links"), |r, (name, exts)| r.filter(name, exts));
ask(app, request, move |app, path| {
let r = app.run("links.relink", json!({ "ids": ids, "path": path, "preserve": "fit" }));
report(app, r, |v| crate::i18n::msg_n(v["relinked"].as_array().map_or(0, Vec::len) as u64, "Replaced {n} image", "Replaced {n} images", &[]));
file_asks::ask(app, request, Owner::Document, move |app, picked| {
if let Picked::Contents(files) = picked {
if let Some((name, bytes)) = files.into_iter().next() {
let result = app
.run("links.replaceEmbedded", json!({ "ids": ids, "dataBase64": vectorcraft_format::base64_encode(&bytes) }))
.map_err(|err| format!("{name}: {err}"));
report(app, result, |v| replaced_status(v["replaced"].as_array().map_or(0, Vec::len)));
}
} else if let Some(path) = picked.first_path() {
let r = app.run("links.relink", json!({ "ids": ids, "path": path.to_string_lossy(), "preserve": "fit" }));
report(app, r, |v| replaced_status(v["relinked"].as_array().map_or(0, Vec::len)));
}
Ok(Value::Null)
});
}
fn replaced_status(n: usize) -> String {
crate::i18n::msg_n(n as u64, "Replaced {n} image", "Replaced {n} images", &[])
}
/// Relink images `ids` (none: every missing one) to the files of their names in a picked folder.
fn relink_to_folder(app: &mut VectorcraftApp, ids: Vec<u64>) {
ask(app, PickRequest::folder("links"), move |app, folder| {
+55
View File
@@ -653,6 +653,61 @@ fn properties_shows_the_selected_image_and_its_link_actions() {
assert!(text.contains("Linked File") && text.contains("Edit Original") && text.contains("Embed"), "{text}");
}
#[test]
fn replace_image_uses_browser_picker_bytes_and_fits_them_in_one_undo_step() {
use crate::tests::picks::{poll, scripted};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::Rect;
let dir = Folder::new("replace-browser-bytes");
let (mut app, linked, _) = app(&dir);
let before = app.session.doc().unwrap().doc.clone();
let undo = app.session.doc().unwrap().history.undo.len();
let journal = app.session.journal.len();
let picker = scripted(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
let bytes = png(10, 20);
super::links::replace(&mut app, vec![linked]);
assert_eq!(picker.requests().len(), 1);
picker.answer_contents(&[("replacement.png", &bytes)]);
poll(&mut app, &ctx);
let state = app.session.doc().unwrap();
let NodeKind::Image(image) = &state.doc.node(NodeId(linked)).unwrap().kind else { panic!("replacement must keep the image's id") };
assert_eq!((image.width, image.height), (10, 20));
assert!(image.link.is_none(), "browser file contents are embedded");
assert_eq!(state.doc.images[&image.key].bytes.as_slice(), bytes);
let bounds = image.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 10.0, 20.0));
assert_eq!((bounds.width(), bounds.height()), (100.0, 200.0), "fit in the old 300 by 200 bounds");
assert_eq!(state.history.undo.len(), undo + 1);
assert_eq!(app.session.journal.get(journal).map(|(command, _)| command.as_str()), Some("links.replaceEmbedded"));
app.run("edit.undo", json!({})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, before);
}
#[test]
fn replace_image_with_a_desktop_path_remains_linked() {
use crate::tests::picks::{poll, scripted};
use vectorcraft_doc::{NodeId, NodeKind};
let dir = Folder::new("replace-desktop-path");
let (mut app, _, embedded) = app(&dir);
let path = dir.file("replacement.png", &png(10, 20));
let picker = scripted(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
super::links::replace(&mut app, vec![embedded]);
picker.answer(&[&path]);
poll(&mut app, &ctx);
let state = app.session.doc().unwrap();
let NodeKind::Image(image) = &state.doc.node(NodeId(embedded)).unwrap().kind else { panic!("replacement must keep the image's id") };
assert_eq!((image.width, image.height), (10, 20));
assert_eq!(image.link.as_ref().unwrap().path, path);
}
/// Unembed… acts on several selected embedded images: it asks for one folder, writes a file for
/// each image there and links each one to its file; with no folder picked, nothing changes.
#[test]
+2
View File
@@ -10690,6 +10690,8 @@ listed in `warnings`. ASCII and binary DXF files are read; DWG files answer an e
## Links panel
`links.replaceEmbedded {ids, dataBase64}` uses raster file bytes to replace existing canvas images. It embeds the new pixels and keeps the image ids. The new aspect ratio fits inside the old bounds, and a distorted image keeps its corners. The command records one undo step and returns `{replaced: [ids]}`. The browser's Replace Image uses this operation with the file picker result.
`links.list {show?: all|missing|modified|embedded, sort?: name|kind|status|size}` lists every image in the layers, top
first, as the Links panel does (`sort: "size"`, the panel menu's Sort by Size, puts the smallest file first by the
size Link Info shows; rows without one, embedded images and missing files whose size is not kept, come last, and equal
+1
View File
@@ -2538,6 +2538,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing.
- On Windows, a link on a drive mapped to a network share other than the document's (`Y:\…`) is missing, with the reason that the path is on another computer, as a link stored with that share's own path is; links on this computer's drives and on the document's share are followed.
- In the Links panel, Shift-click selects a range of links and Ctrl/Cmd-click adds or removes one.
- Replace Image in the browser embeds the picked raster in the existing image and fits it within the old bounds in one undo step. The desktop picker continues to link to the chosen file. Evidence includes `replace_image_uses_browser_picker_bytes_and_fits_them_in_one_undo_step` and `replace_image_with_a_desktop_path_remains_linked`.
- The Links panel menu's Sort by Size ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) lists the links by file size, smallest first (`links.list {sort: "size"}`). VectorCraft's own rules: a file's size is the one Link Info shows, rows without one (embedded images, a missing file whose size the document does not keep) come last, and equal sizes go by name.
- When a document opens with notes and with linked files that changed on disk (Update Links: Manually) or, on the web, can't be read, the status bar shows the line about the linked files, then counts the notes and names the first, and hovering it lists the notes. The same holds when the line about modified files follows the Linked File Not Found dialog, and File › New from Template… shows the notes of the file it opens as File › Open does (`an_open_with_modified_links_keeps_link_notice_and_import_notes_reachable`, `new_from_template_preserves_open_warnings`, `an_open_with_unreadable_links_keeps_import_notes_reachable`, `modified_links_after_the_missing_ones_keep_the_open_notes`, `combined_open_and_link_status_lists_notes_on_hover_and_for_accessibility`).
- On the web, when a document opens with linked files that can't be read and linked files that changed on disk (Update Links: Manually), the status bar shows the line about the unreadable files, and the line about the changed files is the first of the notes its hover lists, ahead of the open's notes. With Ask When Modified the update question opens and the line about the unreadable files stays (`a_web_open_with_unreadable_and_modified_links_keeps_both_lines`).