mirror of
https://github.com/storytold/designcraft.git
synced 2026-12-02 20:21:15 -05:00
Merge pull request #1244 from seanth/web-relink
[fix] Web relink of images
This commit is contained in:
10 files changed
+681
-26
No files matched your search
@@ -613,6 +613,7 @@ Newest first.
|
||||
- **2026-10-17** · Cross-references keep text typed over their generated text (IDML import and export), with the page number still live, as InDesign shows them until updated; a cross-reference whose destination is gone shows its saved text and page instead of "??"; and a cross-reference's text breaks at its spaces instead of inside words. No readiness percentage change.
|
||||
- **2026-10-17** · Parent pages: while parents are edited, the document pages' hidden characters, spelling squiggles and other overlays no longer pile onto the right parent page. No readiness percentage change.
|
||||
- **2026-10-16** · A Direct Selection click on an image whose frame is already selected selects the image, so Delete removes only the image and leaves the empty frame, as in InDesign. No readiness percentage change.
|
||||
- **2026-10-18** · Web build: linked graphics relink from files handed over — Links › Relink… opens the browser's file picker for one graphic, Relink to Folder… its folder picker (each missing graphic takes the file whose path in the folder ends like its link; same-named files nothing tells apart are left missing and reported); one undo step per batch. New `links.relinkFiles`. Before, both buttons did nothing in the browser, so an IDML opened without its Links folder had no way to get its pictures. No readiness percentage change.
|
||||
- **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change.
|
||||
- **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change.
|
||||
- **2026-10-17** · File › Package writes the document's and the IDML's links relative to the package (`Links/logo.png`, `file:Links/logo.png`), so a package holds no path from the machine that made it; opening a document resolves them to the files beside it. Links › Copy Link(s) To still links by full path. (#340). No readiness percentage change.
|
||||
|
||||
@@ -30,4 +30,4 @@ rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Event", "EventTarget", "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration"] }
|
||||
web-sys = { version = "0.3", features = ["Event", "EventTarget", "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "HtmlInputElement", "FileList", "File"] }
|
||||
@@ -9,7 +9,10 @@
|
||||
//! - File → Open / Place use the browser file picker; bytes arrive asynchronously through
|
||||
//! `Services::inbox` (`.designcraft` → `file.openBytes`, images → `file.place`);
|
||||
//! - Save and Export trigger a browser download;
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox.
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
|
||||
//! - linked graphics can't be read from their paths (an IDML's Links folder): they show as
|
||||
//! missing, and relink from files handed over instead (Links › Relink… and Relink to Folder…
|
||||
//! pick the files, `links.relinkFiles`).
|
||||
//!
|
||||
//! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?sample` opens the
|
||||
//! sample magazine on start. Flags match case-sensitive, percent-decoded query keys; values
|
||||
|
||||
@@ -28,6 +28,8 @@ const IMAGE_EXTS: &[&str] = &[
|
||||
"idml",
|
||||
"designcraft",
|
||||
];
|
||||
/// Graphics a relink reads (the image and vector formats placing accepts).
|
||||
const GRAPHIC_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "psd", "svg", "pdf", "ai"];
|
||||
const CANVAS_ID: &str = "designcraft_canvas";
|
||||
const LOADING_ID: &str = "designcraft_loading";
|
||||
|
||||
@@ -418,11 +420,29 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
rfd::AsyncFileDialog::new().add_filter("Swatch Exchange (ASE)", &["ase"])
|
||||
} else if request.purpose == "shortcuts" {
|
||||
rfd::AsyncFileDialog::new().add_filter("Shortcut set (JSON, InDesign text)", &["json", "txt"])
|
||||
} else if request.purpose.starts_with("relink") {
|
||||
rfd::AsyncFileDialog::new().add_filter("Graphics", GRAPHIC_EXTS)
|
||||
} else if request.purpose == "place" {
|
||||
rfd::AsyncFileDialog::new().add_filter("Graphics", IMAGE_EXTS)
|
||||
} else {
|
||||
rfd::AsyncFileDialog::new().add_filter("DesignCraft, IDML or InDesign", DOC_EXTS)
|
||||
};
|
||||
// Relink to Folder: the browser's folder picker hands over every graphic in the
|
||||
// chosen folder; they arrive together, to relink in one step.
|
||||
if request.purpose == "relinkFiles" {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let files: Vec<ImportedFile> = pick_folder_files(&request.wanted)
|
||||
.await
|
||||
.into_iter()
|
||||
.map(|(name, bytes)| ImportedFile { request: request.clone(), name, bytes })
|
||||
.collect();
|
||||
if !files.is_empty() {
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// Place takes several files, loaded into the place cursor in the order chosen.
|
||||
let handles = if request.purpose == "place" {
|
||||
@@ -446,6 +466,73 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most files a chosen folder hands over for relinking, and the most bytes in all.
|
||||
const MAX_FOLDER_FILES: usize = 2000;
|
||||
// The bytes are copied a few times on the way (base64 for the command, then decoded), so the
|
||||
// cap keeps the peak well inside the browser's memory for a tab.
|
||||
const MAX_FOLDER_BYTES: f64 = 256.0 * 1024.0 * 1024.0;
|
||||
|
||||
/// The graphics named in `wanted` (lower-case file names; empty: every graphic) in a folder the
|
||||
/// user chooses with the browser's folder picker (an `<input type=file webkitdirectory>`, which
|
||||
/// every current browser supports), each named by its path in the folder. Only those files are
|
||||
/// read, up to [`MAX_FOLDER_FILES`] and [`MAX_FOLDER_BYTES`]; empty when the picker is cancelled
|
||||
/// or can't be shown.
|
||||
async fn pick_folder_files(wanted: &[String]) -> Vec<(String, Vec<u8>)> {
|
||||
let Some(document) = web_sys::window().and_then(|w| w.document()) else { return Vec::new() };
|
||||
let Some(input) = document.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
input.set_type("file");
|
||||
input.set_multiple(true);
|
||||
if input.set_attribute("webkitdirectory", "").is_err() {
|
||||
return Vec::new();
|
||||
}
|
||||
// Settles when files are chosen or the picker is cancelled. The listener is this call's and
|
||||
// goes when the picker settles, not kept for the page's life. (A browser that fires neither
|
||||
// event leaves this call waiting; current browsers fire `cancel`.)
|
||||
let mut resolve = None;
|
||||
let chosen = js_sys::Promise::new(&mut |r, _reject| resolve = Some(r));
|
||||
let Some(resolve) = resolve else { return Vec::new() };
|
||||
let done = wasm_bindgen::closure::Closure::<dyn FnMut()>::new(move || {
|
||||
let _ = resolve.call0(&wasm_bindgen::JsValue::UNDEFINED);
|
||||
});
|
||||
for event in ["change", "cancel"] {
|
||||
let _ = input.add_event_listener_with_callback(event, done.as_ref().unchecked_ref());
|
||||
}
|
||||
input.click();
|
||||
let _ = wasm_bindgen_futures::JsFuture::from(chosen).await;
|
||||
for event in ["change", "cancel"] {
|
||||
let _ = input.remove_event_listener_with_callback(event, done.as_ref().unchecked_ref());
|
||||
}
|
||||
drop(done);
|
||||
let Some(list) = input.files() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let mut bytes = 0.0;
|
||||
for i in 0..list.length() {
|
||||
let Some(file) = list.get(i) else { continue };
|
||||
let name = file.name();
|
||||
let graphic = name.rsplit_once('.').is_some_and(|(_, ext)| GRAPHIC_EXTS.iter().any(|e| e.eq_ignore_ascii_case(ext)));
|
||||
if !graphic || !(wanted.is_empty() || wanted.contains(&name.to_lowercase())) {
|
||||
continue;
|
||||
}
|
||||
if out.len() >= MAX_FOLDER_FILES || bytes + file.size() > MAX_FOLDER_BYTES {
|
||||
log::warn!("Relink to Folder: more graphics than can be read at once; the rest are left");
|
||||
break;
|
||||
}
|
||||
bytes += file.size();
|
||||
// Its path within the chosen folder tells same-named files in different folders apart.
|
||||
let path = js_sys::Reflect::get(&file, &wasm_bindgen::JsValue::from_str("webkitRelativePath"))
|
||||
.ok()
|
||||
.and_then(|v| v.as_string())
|
||||
.filter(|p| !p.is_empty())
|
||||
.unwrap_or(name);
|
||||
if let Ok(buf) = wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await {
|
||||
out.push((path, js_sys::Uint8Array::new(&buf).to_vec()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Trigger a browser download of `bytes` named after the last component of `path`.
|
||||
fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
|
||||
@@ -57,6 +57,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
relink_folder
|
||||
),
|
||||
cmd!(
|
||||
"links.relinkFiles",
|
||||
"Relink to Files",
|
||||
[],
|
||||
None,
|
||||
"{files: [{name, base64, path?: the file's path within a chosen folder}], asset?: id} — relink from files handed over by name (the web build's file and folder pickers, which give no path on disk): with `asset`, that graphic from the first file; otherwise each missing graphic from the file whose path ends most like its link (the same name at least, any case), all in one undo step — a graphic those can't tell apart (two equally likely files, or one file named only like graphics linking to different files) stays missing. A file named like the link keeps the link's path → {relinked, notFound: [names no file matched], ambiguous: [names left missing], failed: [{name, error}: matching files that couldn't be read, their graphics left missing], unused: [files that matched nothing]}",
|
||||
has_doc,
|
||||
relink_files
|
||||
),
|
||||
cmd!(
|
||||
"links.update",
|
||||
"Update Link",
|
||||
@@ -893,24 +902,64 @@ fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, document: Option<&Pat
|
||||
// The size and time from before the read: a change during it is seen by the next check.
|
||||
let before = super::datamerge::fingerprint_of(read);
|
||||
let (bytes, px) = reload(read)?;
|
||||
let page = if designcraft_render::is_pdf(&bytes) { a.page } else { 0 };
|
||||
let mut a = relinked_from(a, &bytes, px, &read.display().to_string())?;
|
||||
a.name = file_name(&read.to_string_lossy());
|
||||
let file = FileLink::of(read, before);
|
||||
give_bytes(&mut a, bytes, Some(file), false, document);
|
||||
Ok(Arc::new(a))
|
||||
}
|
||||
|
||||
/// [`relinked_asset`] from a file handed over as bytes with its name (the browser's file and
|
||||
/// folder pickers give no path). The bytes become the document's own copy. A file of the same
|
||||
/// name as the link keeps the link's record, so the document still knows the file on the computer
|
||||
/// the link came from; another name becomes the link.
|
||||
fn relinked_bytes(a: &designcraft_doc::Asset, name: &str, bytes: Vec<u8>) -> Result<Arc<designcraft_doc::Asset>> {
|
||||
if designcraft_render::is_pdf(&bytes) {
|
||||
designcraft_render::check_pdf_input_size(bytes.len()).map_err(|e| bad("links", format!("{name}: {e}")))?;
|
||||
}
|
||||
let px = designcraft_render::image_size(&bytes).ok_or_else(|| bad("links", format!("{name}: unsupported or corrupt image")))?;
|
||||
let mut a = relinked_from(a, &bytes, px, name)?;
|
||||
let same = a.link.as_deref().is_some_and(|old| link_file_name(old).eq_ignore_ascii_case(name));
|
||||
if !same {
|
||||
a.set_link(Some(name.to_string()), None);
|
||||
a.link_relative = None;
|
||||
} else {
|
||||
// The file's size and time on that computer aren't these bytes'.
|
||||
let link = a.link.clone();
|
||||
a.set_link(link, None);
|
||||
}
|
||||
// The link kept may come from another platform: named after its last part, either separator.
|
||||
a.name = a.link.as_deref().map_or_else(|| name.to_string(), |l| link_file_name(l).to_string());
|
||||
a.proxy = None;
|
||||
a.link_hash = Some(crate::asset_io::content_hash(&bytes));
|
||||
a.storage = Storage::Embedded;
|
||||
a.data = AssetData::embedded(Arc::new(bytes));
|
||||
Ok(Arc::new(a))
|
||||
}
|
||||
|
||||
/// The file name at the end of a link (either kind of separator).
|
||||
fn link_file_name(link: &str) -> &str {
|
||||
link.rsplit(['/', '\\']).next().unwrap_or(link)
|
||||
}
|
||||
|
||||
/// `a` with a new file's type, page and pixel size (`px`), its PDF crop found on the new bytes
|
||||
/// (`label` names the file in errors). The caller gives it the bytes and its name.
|
||||
fn relinked_from(a: &designcraft_doc::Asset, bytes: &[u8], px: (u32, u32), label: &str) -> Result<designcraft_doc::Asset> {
|
||||
let page = if designcraft_render::is_pdf(bytes) { a.page } else { 0 };
|
||||
let px = if page > 0 {
|
||||
designcraft_render::pdf_page_size(&bytes, page as usize)
|
||||
designcraft_render::pdf_page_size(bytes, page as usize)
|
||||
.map(|(w, h)| (w.round().max(1.0) as u32, h.round().max(1.0) as u32))
|
||||
.ok_or_else(|| bad("links", format!("{}: can't read PDF page {}", read.display(), u64::from(page) + 1)))?
|
||||
.ok_or_else(|| bad("links", format!("{label}: can't read PDF page {}", u64::from(page) + 1)))?
|
||||
} else {
|
||||
px
|
||||
};
|
||||
let mut a = a.clone();
|
||||
a.mime = designcraft_render::image_mime(&bytes).to_string();
|
||||
a.mime = designcraft_render::image_mime(bytes).to_string();
|
||||
a.pixels = Some(px);
|
||||
a.page = page;
|
||||
a.name = file_name(&read.to_string_lossy());
|
||||
// A placed PDF keeps its crop choice; its box is found on the new file.
|
||||
super::file::crop_pdf_from(&mut a, &bytes);
|
||||
let file = FileLink::of(read, before);
|
||||
give_bytes(&mut a, bytes, Some(file), false, document);
|
||||
Ok(Arc::new(a))
|
||||
super::file::crop_pdf_from(&mut a, bytes);
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// The file Update reads `a`'s bytes from: the first of a linked graphic's paths that holds a
|
||||
@@ -1028,6 +1077,139 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"relinked": n, "notFound": not_found}))
|
||||
}
|
||||
|
||||
/// The most files one `links.relinkFiles` takes (a Links folder is rarely more than a few hundred).
|
||||
const MAX_RELINK_FILES: usize = 2000;
|
||||
|
||||
/// The path components of a link or a file's path in a chosen folder, either separator.
|
||||
fn path_parts(path: &str) -> Vec<&str> {
|
||||
path.split(['/', '\\']).filter(|c| !c.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// How many trailing path components `file` shares with `link` (any case): 1 for the file name
|
||||
/// alone, more when its folders match the link's too.
|
||||
fn shared_tail(file: &str, link: &str) -> usize {
|
||||
path_parts(file).iter().rev().zip(path_parts(link).iter().rev()).take_while(|(a, b)| a.eq_ignore_ascii_case(b)).count()
|
||||
}
|
||||
|
||||
/// Which handed-over file each missing graphic takes (`links.relinkFiles` without `asset`).
|
||||
/// A graphic takes the file whose path ends most like its link: the same name at least. Where
|
||||
/// that can't tell files apart — two files of the graphic's name equally like its link, or one
|
||||
/// file named only like two graphics whose links name different files — the graphic is left
|
||||
/// missing and reported, rather than given another file's picture. Graphics linking to the same
|
||||
/// file share it.
|
||||
/// Also returns which files are named like some missing graphic (matched or not), so a file left
|
||||
/// ambiguous isn't reported as matching nothing.
|
||||
fn match_files(missing: &[(AssetId, String)], files: &[(String, String)]) -> (Vec<(AssetId, usize)>, Vec<String>, Vec<String>, Vec<bool>) {
|
||||
let mut named = vec![false; files.len()];
|
||||
let mut chosen = Vec::new();
|
||||
let mut not_found = Vec::new();
|
||||
let mut ambiguous = Vec::new();
|
||||
let mut picks: Vec<(AssetId, usize, usize, &str)> = Vec::new();
|
||||
for (aid, link) in missing {
|
||||
let scores: Vec<(usize, usize)> =
|
||||
files.iter().enumerate().map(|(k, (_, path))| (k, shared_tail(path, link))).filter(|(_, n)| *n > 0).collect();
|
||||
for (k, _) in &scores {
|
||||
if let Some(n) = named.get_mut(*k) {
|
||||
*n = true;
|
||||
}
|
||||
}
|
||||
let best = scores.iter().map(|(_, n)| *n).max().unwrap_or(0);
|
||||
let top: Vec<usize> = scores.iter().filter(|(_, n)| *n == best).map(|(k, _)| *k).collect();
|
||||
match top.as_slice() {
|
||||
[] => not_found.push(link_file_name(link).to_string()),
|
||||
[k] => picks.push((*aid, *k, best, link.as_str())),
|
||||
_ => ambiguous.push(link_file_name(link).to_string()),
|
||||
}
|
||||
}
|
||||
let same = |x: &str, y: &str| path_parts(x).iter().map(|c| c.to_ascii_lowercase()).eq(path_parts(y).iter().map(|c| c.to_ascii_lowercase()));
|
||||
for (aid, k, score, link) in &picks {
|
||||
let rivals = picks.iter().filter(|(other, k2, _, _)| other != aid && k2 == k);
|
||||
let top = rivals.clone().map(|(_, _, n, _)| *n).max().unwrap_or(0);
|
||||
if top > *score {
|
||||
// The file ends more like another graphic's link: it is that graphic's.
|
||||
not_found.push(link_file_name(link).to_string());
|
||||
} else if rivals.filter(|(_, _, n, _)| *n == *score).any(|(_, _, _, link2)| !same(link2, link)) {
|
||||
// Equally like graphics linking to different files: which it is can't be told.
|
||||
ambiguous.push(link_file_name(link).to_string());
|
||||
} else {
|
||||
chosen.push((*aid, *k));
|
||||
}
|
||||
}
|
||||
(chosen, not_found, ambiguous, named)
|
||||
}
|
||||
|
||||
fn relink_files(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const ID: &str = "links.relinkFiles";
|
||||
let list = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(ID, "missing files"))?;
|
||||
if list.len() > MAX_RELINK_FILES {
|
||||
return Err(bad(ID, format!("at most {MAX_RELINK_FILES} files")));
|
||||
}
|
||||
// (file name, path within the chosen folder: the name when there is none, base64)
|
||||
let mut files: Vec<(String, String)> = Vec::new();
|
||||
let mut data: Vec<&str> = Vec::new();
|
||||
for f in list {
|
||||
let name = f.get("name").and_then(Value::as_str).ok_or_else(|| bad(ID, "each file needs a name"))?;
|
||||
let b64 = f.get("base64").and_then(Value::as_str).ok_or_else(|| bad(ID, "each file needs base64"))?;
|
||||
let path = f.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).unwrap_or(name);
|
||||
files.push((link_file_name(name).to_string(), path.to_string()));
|
||||
data.push(b64);
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let (d, document) = (&st.doc, st.path.as_deref().map(Path::new));
|
||||
// Every replacement is built before the edit: a bad file leaves the document as it was.
|
||||
let mut fresh = Vec::new();
|
||||
let mut used = vec![false; files.len()];
|
||||
let (mut not_found, mut ambiguous, mut failed) = (Vec::new(), Vec::new(), Vec::new());
|
||||
if let Some(aid) = p.get("asset").and_then(Value::as_u64).map(AssetId) {
|
||||
let a = d.assets.get(&aid).ok_or_else(|| bad(ID, "no such graphic"))?;
|
||||
let ((name, _), b64) = files.first().zip(data.first()).ok_or_else(|| bad(ID, "no file"))?;
|
||||
fresh.push((aid, relinked_bytes(a, name, super::base64_decode(b64))?));
|
||||
if let Some(u) = used.first_mut() {
|
||||
*u = true;
|
||||
}
|
||||
} else {
|
||||
let placed = d.used_assets();
|
||||
let mut checks = ImageChecks::new();
|
||||
// Graphics still placed: a replaced graphic kept for undo isn't relinked behind the page.
|
||||
let missing: Vec<(AssetId, String)> = d
|
||||
.assets
|
||||
.values()
|
||||
.filter(|a| placed.contains(&a.id) && image_status(a, document, &mut checks, None).0 == "missing")
|
||||
.map(|a| (a.id, a.link.clone().unwrap_or_else(|| a.name.clone())))
|
||||
.collect();
|
||||
let (chosen, named);
|
||||
(chosen, not_found, ambiguous, named) = match_files(&missing, &files);
|
||||
// A file named like a missing graphic was meant for it, even when left ambiguous.
|
||||
for (u, n) in used.iter_mut().zip(&named) {
|
||||
*u |= *n;
|
||||
}
|
||||
for (aid, k) in chosen {
|
||||
let (Some(a), Some((name, _)), Some(b64)) = (d.assets.get(&aid), files.get(k), data.get(k)) else { continue };
|
||||
if let Some(u) = used.get_mut(k) {
|
||||
*u = true;
|
||||
}
|
||||
// A file that can't be read leaves its graphic missing and the others relinking.
|
||||
match relinked_bytes(a, name, super::base64_decode(b64)) {
|
||||
Ok(fresh_asset) => fresh.push((aid, fresh_asset)),
|
||||
Err(e) => failed.push(json!({"name": name, "error": e.to_string()})),
|
||||
}
|
||||
}
|
||||
}
|
||||
let unused: Vec<String> = files.iter().zip(&used).filter(|(_, u)| !**u).map(|((n, _), _)| n.clone()).collect();
|
||||
let n = fresh.len();
|
||||
if n > 0 {
|
||||
s.edit(|d, _| {
|
||||
for (aid, a) in fresh {
|
||||
d.assets.insert(aid, a);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
s.link_checks.images.clear();
|
||||
designcraft_doc::asset_data::links_changed();
|
||||
}
|
||||
Ok(json!({"relinked": n, "notFound": not_found, "ambiguous": ambiguous, "failed": failed, "unused": unused}))
|
||||
}
|
||||
|
||||
/// Unembed reads and writes files: not on the web.
|
||||
fn can_unembed(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
@@ -1356,6 +1538,180 @@ mod shared_asset_tests {
|
||||
designcraft_render::Rendered { width: w, height: h, pixels: vec![200u8; (w * h * 4) as usize] }.to_png()
|
||||
}
|
||||
|
||||
/// Two placed graphics whose linked files were never read (an IDML opened in the browser
|
||||
/// without its Links folder): missing, with no picture.
|
||||
fn two_missing() -> (Session, AssetId, AssetId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
for (name, x) in [("a.png", 72), ("b.png", 200)] {
|
||||
let b = super::super::file::base64_encode(&png(4, 4 + x as u32 / 100));
|
||||
s.execute("file.place", &json!({"base64": b, "name": name, "x": x, "y": 72})).unwrap();
|
||||
s.execute("edit.deselectAll", &json!({})).unwrap();
|
||||
}
|
||||
let ids: Vec<AssetId> = s.doc().unwrap().doc.assets.keys().copied().collect();
|
||||
s.edit(|d, _| {
|
||||
for (k, id) in ids.iter().enumerate() {
|
||||
let a = Arc::make_mut(d.assets.get_mut(id).unwrap());
|
||||
a.link = Some(format!("/Users/someone/Links/Pic{k}.PNG"));
|
||||
a.name = format!("Pic{k}.PNG");
|
||||
a.data = AssetData::embedded(Vec::new());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
(s, ids[0], ids[1])
|
||||
}
|
||||
|
||||
/// Two missing graphics linked to `links`, as [`two_missing`] but with the given links.
|
||||
fn missing_with(links: [&str; 2]) -> (Session, AssetId, AssetId) {
|
||||
let (mut s, a, b) = two_missing();
|
||||
s.edit(|d, _| {
|
||||
for (id, link) in [(a, links[0]), (b, links[1])] {
|
||||
let x = Arc::make_mut(d.assets.get_mut(&id).unwrap());
|
||||
x.link = Some(link.into());
|
||||
x.name = link_file_name(link).into();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
(s, a, b)
|
||||
}
|
||||
|
||||
/// Only graphics still placed are relinked: a replaced graphic kept for undo is missing too,
|
||||
/// but relinking it would change nothing on the page. The journal keeps the files' names,
|
||||
/// not their contents.
|
||||
#[test]
|
||||
fn relinks_only_placed_graphics_and_replays_from_the_journal() {
|
||||
let (mut s, a, b) = two_missing();
|
||||
// b's frame is deleted: its asset stays (for undo) but nothing shows it.
|
||||
s.edit(|d, _| {
|
||||
for sp in &mut d.spreads {
|
||||
std::sync::Arc::make_mut(sp).items.retain(|it| !matches!(&it.content, Content::Graphic(g) if g.asset == b));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let file = |name: &str| json!({"name": name, "base64": super::super::file::base64_encode(&png(6, 6))});
|
||||
let r = s.execute("links.relinkFiles", &json!({"files": [file("pic0.png"), file("pic1.png")]})).unwrap();
|
||||
assert_eq!(r["relinked"], 1);
|
||||
assert_eq!(r["unused"], json!(["pic1.png"]), "nothing placed is named pic1");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(!d.assets[&a].data.is_empty() && d.assets[&b].data.is_empty());
|
||||
// The journal keeps the files whole, as it does for `file.place {base64}`: replayed, the
|
||||
// entry relinks again.
|
||||
let (id, params) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(id, "links.relinkFiles");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.assets[&a].data.is_empty());
|
||||
assert_eq!(s.execute(&id, ¶ms).unwrap()["relinked"], 1);
|
||||
assert!(!s.doc().unwrap().doc.assets[&a].data.is_empty());
|
||||
}
|
||||
|
||||
/// A matching file that can't be read (here not an image at all) is reported and leaves its
|
||||
/// graphic missing; the other files still relink theirs.
|
||||
#[test]
|
||||
fn an_unreadable_file_leaves_the_others_relinking() {
|
||||
let (mut s, a, b) = two_missing();
|
||||
let good = json!({"name": "pic0.png", "base64": super::super::file::base64_encode(&png(6, 6))});
|
||||
let bad_file = json!({"name": "pic1.png", "base64": super::super::file::base64_encode(b"not an image")});
|
||||
let r = s.execute("links.relinkFiles", &json!({"files": [good, bad_file]})).unwrap();
|
||||
assert_eq!(r["relinked"], 1, "{r}");
|
||||
assert_eq!(r["failed"].as_array().map(|f| f.iter().map(|f| f["name"].clone()).collect::<Vec<_>>()), Some(vec![json!("pic1.png")]), "{r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(!d.assets[&a].data.is_empty() && d.assets[&b].data.is_empty());
|
||||
}
|
||||
|
||||
/// Relinking to a file on disk names the graphic after that file as the platform reads
|
||||
/// paths: a backslash is part of a file name on Linux and macOS.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_path_relink_names_the_graphic_by_the_platform_s_file_name() {
|
||||
let (mut s, a, _) = two_missing();
|
||||
let dir = std::env::temp_dir().join(format!("dc-relink-name-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("cover\\v2.png");
|
||||
std::fs::write(&path, png(4, 4)).unwrap();
|
||||
s.execute("links.relink", &json!({"asset": a.0, "path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.assets[&a].name, "cover\\v2.png");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Files of the same name in different folders of a chosen folder: each missing graphic takes
|
||||
/// the one whose path ends like its link; where nothing tells them apart, the graphics stay
|
||||
/// missing and are reported rather than given another graphic's picture. Graphics linking to
|
||||
/// the same file share it.
|
||||
#[test]
|
||||
fn same_named_files_relink_by_folder_or_not_at_all() {
|
||||
let file = |name: &str, path: &str, w: u32| json!({"name": name, "path": path, "base64": super::super::file::base64_encode(&png(w, w))});
|
||||
let px = |s: &Session, id: AssetId| s.doc().unwrap().doc.assets[&id].pixels;
|
||||
let links = ["/Users/x/Vol38/Links/brand-a/logo.png", "/Users/x/Vol38/Links/brand-b/logo.png"];
|
||||
// Their folders tell them apart.
|
||||
let (mut s, a, b) = missing_with(links);
|
||||
let r = s
|
||||
.execute(
|
||||
"links.relinkFiles",
|
||||
&json!({"files": [file("logo.png", "Links/brand-b/logo.png", 5), file("logo.png", "Links/brand-a/logo.png", 6)]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["relinked"], 2);
|
||||
assert_eq!((px(&s, a), px(&s, b)), (Some((6, 6)), Some((5, 5))));
|
||||
// Two files named alike with no folders: neither graphic can tell which is its own.
|
||||
let (mut s, a, b) = missing_with(links);
|
||||
let r = s.execute("links.relinkFiles", &json!({"files": [file("logo.png", "logo.png", 5), file("logo.png", "logo.png", 6)]})).unwrap();
|
||||
assert_eq!(r["relinked"], 0);
|
||||
assert_eq!(r["ambiguous"], json!(["logo.png", "logo.png"]));
|
||||
assert_eq!(r["unused"], json!([]), "files named like the graphics were meant for them");
|
||||
assert!(s.doc().unwrap().doc.assets[&a].data.is_empty() && s.doc().unwrap().doc.assets[&b].data.is_empty());
|
||||
// One file named like both, which link to different files: it can't be both.
|
||||
let (mut s, a, _) = missing_with(links);
|
||||
let r = s.execute("links.relinkFiles", &json!({"files": [file("logo.png", "logo.png", 5)]})).unwrap();
|
||||
assert_eq!((r["relinked"].as_u64(), r["ambiguous"].as_array().map(Vec::len)), (Some(0), Some(2)));
|
||||
assert!(s.doc().unwrap().doc.assets[&a].data.is_empty());
|
||||
// ...but with its folder it is brand-b's, and brand-a's stays missing.
|
||||
let r = s.execute("links.relinkFiles", &json!({"files": [file("logo.png", "brand-b/logo.png", 5)]})).unwrap();
|
||||
assert_eq!(r["relinked"], 1);
|
||||
assert_eq!((r["notFound"].clone(), r["ambiguous"].clone()), (json!(["logo.png"]), json!([])), "brand-b's file isn't brand-a's");
|
||||
// Two graphics linking to the same file (another page of it, say) share it.
|
||||
let (mut s, a, b) = missing_with(["/Users/x/Links/logo.png", "/Users/x/Links/logo.png"]);
|
||||
let r = s.execute("links.relinkFiles", &json!({"files": [file("logo.png", "logo.png", 5)]})).unwrap();
|
||||
assert_eq!(r["relinked"], 2);
|
||||
assert_eq!((px(&s, a), px(&s, b)), (Some((5, 5)), Some((5, 5))));
|
||||
}
|
||||
|
||||
/// Relinking from files handed over by name (the web build): each missing graphic takes the
|
||||
/// file of its name in any case, keeping its link's path, in one undo step; a file that
|
||||
/// matches nothing and a graphic no file matched are reported.
|
||||
#[test]
|
||||
fn relinks_missing_graphics_from_files_by_name() {
|
||||
let (mut s, a, b) = two_missing();
|
||||
let st = s.doc().unwrap();
|
||||
assert!(st.doc.assets.values().all(|x| status_cached(x, None, &mut ImageChecks::new()) == "missing"));
|
||||
let file = |name: &str, w: u32| json!({"name": name, "base64": super::super::file::base64_encode(&png(w, w))});
|
||||
let r = s.execute("links.relinkFiles", &json!({"files": [file("pic0.png", 6), file("other.png", 3)]})).unwrap();
|
||||
assert_eq!(r["relinked"], 1);
|
||||
assert_eq!(r["notFound"], json!(["Pic1.PNG"]));
|
||||
assert_eq!(r["unused"], json!(["other.png"]));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.assets[&a].pixels, Some((6, 6)));
|
||||
assert_eq!(d.assets[&a].link.as_deref(), Some("/Users/someone/Links/Pic0.PNG"), "the same file keeps its path");
|
||||
assert!(d.assets[&b].data.is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.assets[&a].data.is_empty(), "one undo step");
|
||||
// One graphic from a chosen file of another name: that name becomes the link.
|
||||
s.execute("links.relinkFiles", &json!({"asset": b.0, "files": [file("new.png", 5)]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!((d.assets[&b].pixels, d.assets[&b].link.as_deref(), d.assets[&b].name.as_str()), (Some((5, 5)), Some("new.png"), "new.png"));
|
||||
// A file that isn't an image changes nothing: reported for a folder, an error for one
|
||||
// chosen file.
|
||||
let before = s.doc().unwrap().doc.assets.clone();
|
||||
let bad = json!({"name": "pic0.png", "base64": super::super::file::base64_encode(b"not an image")});
|
||||
let r = s.execute("links.relinkFiles", &json!({"files": [bad.clone()]})).unwrap();
|
||||
assert_eq!((r["relinked"].clone(), r["failed"][0]["name"].clone()), (json!(0), json!("pic0.png")), "{r}");
|
||||
assert!(s.execute("links.relinkFiles", &json!({"asset": a.0, "files": [bad]})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.assets, before);
|
||||
assert!(s.execute("links.relinkFiles", &json!({"files": "x"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placements_of_one_file_share_an_asset_and_saves_drop_replaced_ones() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -12,7 +12,7 @@ impl DesignApp {
|
||||
#[track_caller]
|
||||
pub fn pick_and_open(&mut self, purpose: &str) -> Result<Value, String> {
|
||||
if let Some(open) = self.services.open_async.as_mut() {
|
||||
let request = ImportRequest { purpose: purpose.into(), target: self.session.active().map(|d| d.uid) };
|
||||
let request = ImportRequest { purpose: purpose.into(), target: self.session.active().map(|d| d.uid), wanted: Vec::new() };
|
||||
open(request);
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
@@ -129,7 +129,7 @@ impl DesignApp {
|
||||
designcraft_engine::cmd::has_doc(&self.session)?;
|
||||
if let Some(open) = self.services.open_async.as_mut() {
|
||||
let purpose = if kind.is_empty() { "styles".to_string() } else { format!("styles:{kind}") };
|
||||
open(ImportRequest { purpose, target: self.session.active().map(|d| d.uid) });
|
||||
open(ImportRequest { purpose, target: self.session.active().map(|d| d.uid), wanted: Vec::new() });
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let kind = kind.to_string();
|
||||
@@ -144,8 +144,33 @@ impl DesignApp {
|
||||
})
|
||||
}
|
||||
|
||||
/// Ask an asynchronous host (web) for files for `purpose`; they arrive through the inbox.
|
||||
/// `relink:{asset}` relinks that graphic from the chosen file; `relinkFiles` relinks every
|
||||
/// missing graphic from the chosen files of the same names.
|
||||
pub fn request_files(&mut self, purpose: &str) {
|
||||
let mut request = self.import_request(purpose);
|
||||
if purpose == "relinkFiles" {
|
||||
// Only the missing graphics' files are read from the chosen folder.
|
||||
let rows = self.session.execute("links.list", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default();
|
||||
request.wanted = rows
|
||||
.iter()
|
||||
.filter(|r| r["asset"].is_u64() && r["status"] == "missing")
|
||||
.filter_map(|r| r["path"].as_str().or(r["name"].as_str()))
|
||||
.map(|p| file_name_of(p).to_lowercase())
|
||||
.collect();
|
||||
// Nothing to relink: don't have the host read a whole folder for nothing.
|
||||
if request.wanted.is_empty() {
|
||||
self.status(crate::i18n::tr(&self.ui.language, "No missing graphics to relink"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(open) = self.services.open_async.as_mut() {
|
||||
open(request);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn import_request(&self, purpose: &str) -> ImportRequest {
|
||||
ImportRequest { purpose: purpose.into(), target: self.session.active().map(|d| d.uid) }
|
||||
ImportRequest { purpose: purpose.into(), target: self.session.active().map(|d| d.uid), wanted: Vec::new() }
|
||||
}
|
||||
|
||||
pub(crate) fn activate_import_target(&mut self, request: &ImportRequest) -> Result<(), String> {
|
||||
@@ -202,6 +227,7 @@ impl DesignApp {
|
||||
}
|
||||
let Some(inbox) = self.services.inbox.clone() else { return };
|
||||
let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner));
|
||||
let files = self.relink_from_inbox(files);
|
||||
// A browser delivers one Place's files together. Several go to the place cursor, even a
|
||||
// PDF first with a frame selected, as a native batch's do.
|
||||
let batch = files.iter().filter(|f| f.request.purpose == "place").count() > 1;
|
||||
@@ -506,6 +532,67 @@ impl DesignApp {
|
||||
r
|
||||
}
|
||||
|
||||
/// Relink graphics from delivered files, returning the files left to import. Files chosen
|
||||
/// to relink (`relink:{asset}`, `relinkFiles`) relink, each request's files in one undo step;
|
||||
/// every other file (a dropped one too) is placed or opened as before.
|
||||
fn relink_from_inbox(&mut self, files: Vec<ImportedFile>) -> Vec<ImportedFile> {
|
||||
let mut rest = Vec::new();
|
||||
// (request, files) in arrival order; a request's files arrive together.
|
||||
let mut batches: Vec<(ImportRequest, Vec<ImportedFile>)> = Vec::new();
|
||||
for file in files {
|
||||
if !file.request.purpose.starts_with("relink") {
|
||||
rest.push(file);
|
||||
continue;
|
||||
}
|
||||
match batches.iter_mut().find(|(r, _)| r.purpose == file.request.purpose && r.target == file.request.target) {
|
||||
Some((_, b)) => b.push(file),
|
||||
None => batches.push((file.request.clone(), vec![file])),
|
||||
}
|
||||
}
|
||||
for (request, batch) in batches {
|
||||
if self.activate_import_target(&request).is_err() {
|
||||
continue;
|
||||
}
|
||||
// A file from a chosen folder is named by its path in it (which tells same-named
|
||||
// files apart).
|
||||
let list: Vec<Value> = batch
|
||||
.iter()
|
||||
.map(|f| json!({"name": file_name_of(&f.name), "path": f.name, "base64": designcraft_engine::cmd::base64_encode(&f.bytes)}))
|
||||
.collect();
|
||||
let mut params = json!({"files": list});
|
||||
if let Some(aid) = request.purpose.strip_prefix("relink:").and_then(|a| a.parse::<u64>().ok()) {
|
||||
params["asset"] = json!(aid);
|
||||
}
|
||||
match self.run("links.relinkFiles", params) {
|
||||
Ok(v) => {
|
||||
let n = v["relinked"].as_u64().unwrap_or(0);
|
||||
let unsure = v["ambiguous"].as_array().map_or(0, Vec::len);
|
||||
let unread: Vec<&str> = v["failed"].as_array().map(|f| f.iter().filter_map(|f| f["name"].as_str()).collect()).unwrap_or_default();
|
||||
if !unread.is_empty() {
|
||||
// Matching files that couldn't be read: their graphics stay missing.
|
||||
self.status(
|
||||
crate::i18n::tr(&self.ui.language, "Relinked {count}; couldn't read {files}")
|
||||
.replace("{count}", &n.to_string())
|
||||
.replace("{files}", &unread.join(", ")),
|
||||
);
|
||||
} else if unsure > 0 {
|
||||
// Files named like graphics they couldn't be told apart for: neither
|
||||
// relinked nor placed.
|
||||
self.status(
|
||||
crate::i18n::tr(&self.ui.language, "Relinked {count}; {unsure} left missing: same-named files couldn't be told apart")
|
||||
.replace("{count}", &n.to_string())
|
||||
.replace("{unsure}", &unsure.to_string()),
|
||||
);
|
||||
} else {
|
||||
self.status(crate::i18n::tr(&self.ui.language, "Relinked {count}").replace("{count}", &n.to_string()));
|
||||
}
|
||||
}
|
||||
Err(e) => self.status(e),
|
||||
}
|
||||
}
|
||||
rest
|
||||
}
|
||||
|
||||
/// Applies what the background checks of linked files found, shows the notice about images
|
||||
/// that will be saved as links once, and repaints at a low rate while checks run so the
|
||||
/// Links panel's statuses fill in.
|
||||
@@ -575,6 +662,11 @@ impl DesignApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// The last component of a delivered file's name (either kind of separator).
|
||||
fn file_name_of(name: &str) -> &str {
|
||||
name.rsplit(['/', '\\']).next().unwrap_or(name)
|
||||
}
|
||||
|
||||
/// Graphics that can wait in the place cursor, several at a time: raster images, SVG, PSD and
|
||||
/// EPS. A PDF can't (it may ask which page), nor can text, media or documents.
|
||||
pub(crate) fn is_cursor_image(name: &str) -> bool {
|
||||
@@ -712,6 +804,102 @@ pub(crate) mod browser_import_tests {
|
||||
app.run("file.new", json!({"title": "A"})).unwrap();
|
||||
app
|
||||
}
|
||||
/// The placed graphic's link made missing, as an IDML opened in the browser without its
|
||||
/// Links folder leaves it.
|
||||
fn make_missing(app: &mut DesignApp) -> designcraft_doc::AssetId {
|
||||
let aid = *app.session.doc().unwrap().doc.assets.keys().next().unwrap();
|
||||
app.session
|
||||
.edit(|d, _| {
|
||||
let a = std::sync::Arc::make_mut(d.assets.get_mut(&aid).unwrap());
|
||||
a.link = Some("/Users/someone/Links/a.svg".into());
|
||||
a.name = "a.svg".into();
|
||||
a.data = designcraft_doc::AssetData::embedded(Vec::new());
|
||||
// No copy of its own: a link whose file wasn't read.
|
||||
a.link_hash = None;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
aid
|
||||
}
|
||||
fn items(app: &DesignApp) -> usize {
|
||||
app.session.doc().unwrap().doc.spreads.iter().map(|s| s.items.len()).sum()
|
||||
}
|
||||
|
||||
/// With no missing graphic, Relink to Folder doesn't ask the host for a folder at all.
|
||||
#[test]
|
||||
fn relink_to_folder_needs_a_missing_graphic() {
|
||||
let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
let mut app = app();
|
||||
let seen = asked.clone();
|
||||
app.services.open_async = Some(Box::new(move |r: ImportRequest| seen.borrow_mut().push(r)));
|
||||
let b64 = designcraft_engine::cmd::base64_encode(&image());
|
||||
app.run("file.place", json!({"name": "a.svg", "base64": b64, "x": 50, "y": 50})).unwrap();
|
||||
app.request_files("relinkFiles");
|
||||
assert!(asked.borrow().is_empty());
|
||||
assert_eq!(app.ui.status, "No missing graphics to relink");
|
||||
}
|
||||
|
||||
/// Relink to Folder asks the host only for the missing graphics' files, and a chosen folder's
|
||||
/// files arrive named by their paths in it, which tell same-named files apart.
|
||||
#[test]
|
||||
fn relink_to_folder_asks_for_the_missing_names_and_matches_by_path() {
|
||||
let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
let mut app = app();
|
||||
let seen = asked.clone();
|
||||
app.services.open_async = Some(Box::new(move |r: ImportRequest| seen.borrow_mut().push(r)));
|
||||
let b64 = designcraft_engine::cmd::base64_encode(&image());
|
||||
app.run("file.place", json!({"name": "a.svg", "base64": b64, "x": 50, "y": 50})).unwrap();
|
||||
let aid = make_missing(&mut app);
|
||||
app.request_files("relinkFiles");
|
||||
let request = asked.borrow_mut().pop().unwrap();
|
||||
assert_eq!(request.wanted, ["a.svg"]);
|
||||
// The link is /Users/someone/Links/a.svg: the file in a folder named Links is the one.
|
||||
let wrong = br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"/>"##.to_vec();
|
||||
for (name, bytes) in [("Volume/Old/a.svg", wrong), ("Volume/Links/a.svg", image())] {
|
||||
app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes });
|
||||
}
|
||||
app.drain_inbox();
|
||||
let a = &app.session.doc().unwrap().doc.assets[&aid];
|
||||
assert_eq!(a.data.resident().as_deref(), Some(&image()), "the Links folder's file: {}", app.ui.status);
|
||||
}
|
||||
|
||||
/// The web build relinks from files it is handed: chosen with Relink… (one graphic) or
|
||||
/// Relink to Folder… (several at once). A dropped image is placed as before, even one named
|
||||
/// like a missing graphic.
|
||||
#[test]
|
||||
fn delivered_files_relink_missing_graphics() {
|
||||
let mut app = app();
|
||||
let b64 = designcraft_engine::cmd::base64_encode(&image());
|
||||
app.run("file.place", json!({"name": "a.svg", "base64": b64, "x": 50, "y": 50})).unwrap();
|
||||
let aid = make_missing(&mut app);
|
||||
let n = items(&app);
|
||||
let has_data = |app: &DesignApp| !app.session.doc().unwrap().doc.assets[&aid].data.is_empty();
|
||||
let request = app.import_request("relinkFiles");
|
||||
deliver(&mut app, request, "a.svg", image());
|
||||
assert!(has_data(&app), "{}", app.ui.status);
|
||||
assert_eq!(app.session.doc().unwrap().doc.assets[&aid].link.as_deref(), Some("/Users/someone/Links/a.svg"));
|
||||
// A dropped image goes to the place cursor, as any does, even when it is named like a
|
||||
// missing graphic.
|
||||
make_missing(&mut app);
|
||||
app.run("edit.deselectAll", json!({})).unwrap();
|
||||
let request = app.import_request("drop");
|
||||
deliver(&mut app, request, "A.SVG", image());
|
||||
assert!(!has_data(&app), "the dropped file doesn't relink");
|
||||
assert!(app.session.loaded.is_some(), "it is in the place cursor");
|
||||
assert_eq!(items(&app), n, "nothing placed yet");
|
||||
// Relink… for one graphic: the chosen file, whatever its name.
|
||||
make_missing(&mut app);
|
||||
let request = app.import_request(&format!("relink:{}", aid.0));
|
||||
deliver(&mut app, request, "renamed.svg", image());
|
||||
assert_eq!(app.session.doc().unwrap().doc.assets[&aid].link.as_deref(), Some("renamed.svg"));
|
||||
// A matching file that can't be read is named in the status, its graphic left missing.
|
||||
make_missing(&mut app);
|
||||
let request = app.import_request("relinkFiles");
|
||||
deliver(&mut app, request, "a.svg", b"not an image".to_vec());
|
||||
assert!(!has_data(&app));
|
||||
assert!(app.ui.status.contains("couldn't read a.svg"), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
fn deliver(app: &mut DesignApp, request: ImportRequest, name: &str, bytes: Vec<u8>) {
|
||||
app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request, name: name.into(), bytes });
|
||||
app.drain_inbox();
|
||||
|
||||
@@ -5311,7 +5311,7 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
|
||||
return app.confirm_pdf_import(page, if crop.is_empty() { "crop".into() } else { crop }, d.b("append"));
|
||||
}
|
||||
if let Some(target) = d.fields.get("target").and_then(Value::as_u64) {
|
||||
app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?;
|
||||
app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target), wanted: Vec::new() })?;
|
||||
}
|
||||
let placed = app.place_file(
|
||||
json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}),
|
||||
|
||||
@@ -188,14 +188,26 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
|
||||
p[k] = v;
|
||||
p
|
||||
};
|
||||
// A browser hands over the chosen files' bytes, not paths: they arrive through the inbox.
|
||||
let browser = app.services.open_async.is_some();
|
||||
if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Relink…"))).clicked() {
|
||||
let target = with("path", Value::Null);
|
||||
let asked = app.ask_open("relink", Bound::Document, move |app, path| {
|
||||
let _ = app.run("links.relink", crate::app::file_dialogs::with_path(&target, "path", path));
|
||||
Ok(Value::Null)
|
||||
});
|
||||
if let Err(e) = asked {
|
||||
app.status_error("Relink", e);
|
||||
if browser {
|
||||
// A linked text story is read from its path, which a browser doesn't give: say so
|
||||
// rather than ignore the click.
|
||||
if is_text {
|
||||
app.status(crate::i18n::tr(&app.ui.language, "A linked text file can't be relinked in the browser"));
|
||||
} else {
|
||||
app.request_files(&format!("relink:{aid}"));
|
||||
}
|
||||
} else {
|
||||
let target = with("path", Value::Null);
|
||||
let asked = app.ask_open("relink", Bound::Document, move |app, path| {
|
||||
let _ = app.run("links.relink", crate::app::file_dialogs::with_path(&target, "path", path));
|
||||
Ok(Value::Null)
|
||||
});
|
||||
if let Err(e) = asked {
|
||||
app.status_error("Relink", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Go To"))).clicked() {
|
||||
@@ -247,16 +259,21 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
// Missing links are looked up in the chosen folder by name.
|
||||
// Missing links are looked up in the chosen folder by name. In a browser, which hands over
|
||||
// files rather than paths, the folder's files are chosen instead.
|
||||
let browser = app.services.open_async.is_some();
|
||||
if ui
|
||||
.button(crate::i18n::tr(&app.ui.language, "Relink to Folder…"))
|
||||
.on_hover_ui(|ui| {
|
||||
crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Choose the folder holding the moved graphics"));
|
||||
})
|
||||
.clicked()
|
||||
&& let Err(e) = relink_to_folder(app)
|
||||
{
|
||||
app.status_error("Relink", e);
|
||||
if browser {
|
||||
app.request_files("relinkFiles");
|
||||
} else if let Err(e) = relink_to_folder(app) {
|
||||
app.status_error("Relink", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ use super::{Deserialize, Point, Serialize, SnapView, Unit, canvas, dialogs, page
|
||||
pub struct ImportRequest {
|
||||
pub purpose: String,
|
||||
pub target: Option<u64>,
|
||||
/// File names wanted, lower case (Relink to Folder: the missing graphics' names), so the host
|
||||
/// reads only those from a chosen folder. Empty: any.
|
||||
pub wanted: Vec<String>,
|
||||
}
|
||||
|
||||
pub struct ImportedFile {
|
||||
|
||||
@@ -77,4 +77,4 @@ The status line reports once: "N images will be saved as links to their files (L
|
||||
|
||||
## Web builds
|
||||
|
||||
The web build cannot read files, so it embeds everything it places and cannot unembed. A document with linked assets opens with their proxies. Saving it on the web keeps the link records as version 5 and warns: "N linked files are saved as links only: the web version can't read them to embed them".
|
||||
The web build cannot read files, so it embeds everything it places and cannot unembed. Links › Relink… and Relink to Folder… take files from the browser's file and folder pickers instead (`links.relinkFiles`): a missing graphic takes the file whose path ends most like its link, and the bytes become the document's copy. A document with linked assets opens with their proxies. Saving it on the web keeps the link records as version 5 and warns: "N linked files are saved as links only: the web version can't read them to embed them".
|
||||
Reference in new issue
Block a user