diff --git a/ROADMAP.md b/ROADMAP.md index 93e96ae1b..716144bda 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -556,7 +556,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), and dropped images named like a missing graphic relink it; 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-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. diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 8f7593afc..2548fd2d3 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -359,24 +359,19 @@ impl eframe::App for WebShell { let _ = self.graphics.run_if_healthy(|| { // Dropped files belong to this host iteration's raw input, not to stale logic input: // read them here once, before the batch is saved as pending for a hidden pass. - let dropped = std::mem::take(&mut raw.dropped_files); - if !dropped.is_empty() { + for f in std::mem::take(&mut raw.dropped_files) { let request = self.app.import_request("drop"); let inbox = self.inbox.clone(); let ctx = ctx.clone(); - // Read every dropped file before delivering any: dropped graphics that relink - // missing links relink together, in one undo step. wasm_bindgen_futures::spawn_local(async move { - let mut files = Vec::with_capacity(dropped.len()); - for f in dropped { - let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); - match f.bytes_async().await { - Ok(bytes) => files.push(ImportedFile { request: request.clone(), name, bytes }), - Err(e) => log::error!("couldn't read dropped file {name}: {e}"), + let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); + match f.bytes_async().await { + Ok(bytes) => { + inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name, bytes }); + ctx.request_repaint(); } + Err(e) => log::error!("couldn't read dropped file {name}: {e}"), } - inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); - ctx.request_repaint(); }); } designcraft_ui_egui::drop_key_name_text(raw, ctx.text_edit_focused() || self.app.canvas_ime()); @@ -463,17 +458,24 @@ async fn pick_folder_files(wanted: &[String]) -> Vec<(String, Vec)> { if input.set_attribute("webkitdirectory", "").is_err() { return Vec::new(); } - // Settles when files are chosen or the picker is cancelled. - let chosen = js_sys::Promise::new(&mut |resolve, _reject| { - let done = wasm_bindgen::closure::Closure::::new(move || { - let _ = resolve.call0(&wasm_bindgen::JsValue::UNDEFINED); - }); - let _ = input.add_event_listener_with_callback("change", done.as_ref().unchecked_ref()); - let _ = input.add_event_listener_with_callback("cancel", done.as_ref().unchecked_ref()); - done.forget(); + // 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::::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; diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 57198e72b..19a1df1bd 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "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 picker and drops, 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], unused: [files that matched nothing]}", + "{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 ), @@ -466,7 +466,9 @@ fn reload(path: impl AsRef) -> Result<(Vec, (u32, u32))> { /// to and the stored link itself, so refreshing a link never rewrites what the document holds. fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result> { let (bytes, px) = reload(read)?; - relinked_from(a, bytes, px, &read.display().to_string(), link) + // Named as the platform reads the link (a path on this computer). + let name = Path::new(link).file_name().map_or_else(|| link.to_string(), |n| n.to_string_lossy().to_string()); + relinked_from(a, bytes, px, &read.display().to_string(), link, name) } /// [`relinked_asset`] from a file handed over as bytes with its name (the browser's file picker @@ -479,7 +481,9 @@ fn relinked_bytes(a: &designcraft_doc::Asset, name: &str, bytes: Vec) -> Res Some(old) if link_file_name(old).eq_ignore_ascii_case(name) => old.clone(), _ => name.to_string(), }; - relinked_from(a, bytes, px, name, &link) + // The link kept may come from another platform: named after its last part, either separator. + let file = link_file_name(&link).to_string(); + relinked_from(a, bytes, px, name, &link, file) } /// The file name at the end of a link (either kind of separator). @@ -487,8 +491,16 @@ fn link_file_name(link: &str) -> &str { link.rsplit(['/', '\\']).next().unwrap_or(link) } -/// The asset with a new file's bytes (`px` its pixel size, `label` naming it in errors). -fn relinked_from(a: &designcraft_doc::Asset, bytes: Vec, px: (u32, u32), label: &str, link: &str) -> Result> { +/// The asset with a new file's bytes (`px` its pixel size, `label` naming it in errors, `name` +/// the graphic's name from now on). +fn relinked_from( + a: &designcraft_doc::Asset, + bytes: Vec, + px: (u32, u32), + label: &str, + link: &str, + name: String, +) -> Result> { 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) @@ -502,7 +514,7 @@ fn relinked_from(a: &designcraft_doc::Asset, bytes: Vec, px: (u32, u32), lab a.data = Arc::new(bytes); a.pixels = Some(px); a.page = page; - a.name = link_file_name(link).to_string(); + a.name = name; a.link = Some(link.to_string()); // A placed PDF keeps its crop choice; its box is found on the new file. super::file::crop_pdf(&mut a); @@ -691,7 +703,7 @@ fn relink_files(s: &mut Session, p: &Value) -> Result { // 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) = (Vec::new(), Vec::new()); + 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"))?; @@ -717,10 +729,14 @@ fn relink_files(s: &mut Session, p: &Value) -> Result { } for (aid, k) in chosen { let (Some(a), Some((name, _)), Some(b64)) = (d.assets.get(&aid), files.get(k), data.get(k)) else { continue }; - fresh.push((aid, relinked_bytes(a, name, super::base64_decode(b64))?)); 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 = files.iter().zip(&used).filter(|(_, u)| !**u).map(|((n, _), _)| n.clone()).collect(); @@ -733,7 +749,7 @@ fn relink_files(s: &mut Session, p: &Value) -> Result { Ok(()) })?; } - Ok(json!({"relinked": n, "notFound": not_found, "ambiguous": ambiguous, "unused": unused})) + Ok(json!({"relinked": n, "notFound": not_found, "ambiguous": ambiguous, "failed": failed, "unused": unused})) } /// `links.update`: re-read the modified links (one, or every one) from where they resolve. @@ -943,7 +959,7 @@ mod shared_asset_tests { /// 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_journals_no_file_contents() { + 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, _| { @@ -959,9 +975,43 @@ mod shared_asset_tests { 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()); - let (id, params) = s.journal.last().unwrap(); + // 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"); - assert!(params["files"].as_array().unwrap().iter().all(|f| f.get("base64").is_none() && f["name"].is_string()), "{params}"); + 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::>()), 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 @@ -1029,10 +1079,13 @@ mod shared_asset_tests { 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. + // 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")}); - assert!(s.execute("links.relinkFiles", &json!({"files": [bad]})).is_err()); + 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()); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 530dff09c..1c585aa4f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -663,7 +663,7 @@ impl Session { self.keep_guide_selection_valid(before.as_ref(), id); self.record_undo_step(spec, before, nested); if spec.journal { - self.journal.push((id.to_string(), journal_params(id, params))); + self.journal.push((id.to_string(), params.clone())); } self.discard_stale_find_scope(); Ok(r) @@ -825,21 +825,5 @@ fn push_undo(st: &mut DocState, e: HistoryEntry) { pub(crate) use push_undo as record_undo; -/// A command's parameters as the journal keeps them: `links.relinkFiles` keeps its files' names -/// and paths but not their contents (whole image files, which would stay in memory for the -/// session). -fn journal_params(id: &str, params: &Value) -> Value { - if id != "links.relinkFiles" { - return params.clone(); - } - let mut p = params.clone(); - if let Some(files) = p.get_mut("files").and_then(Value::as_array_mut) { - for f in files.iter_mut().filter_map(Value::as_object_mut) { - f.remove("base64"); - } - } - p -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index ccdb3bc47..70fa158b2 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -330,20 +330,14 @@ impl DesignApp { } /// Relink graphics from delivered files, returning the files left to import. Files chosen - /// to relink (`relink:{asset}`, `relinkFiles`) and dropped images named like a missing - /// graphic of the document they were dropped on relink, each request's files in one undo - /// step; other dropped files are placed or opened as before. + /// 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) -> Vec { let mut rest = Vec::new(); // (request, files) in arrival order; a request's files arrive together. let mut batches: Vec<(ImportRequest, Vec)> = Vec::new(); for file in files { - let relink = file.request.purpose.starts_with("relink") - || (file.request.purpose == "drop" - && file.request.target.is_some() - && !opens_as_document(&file.name) - && designcraft_render::image_size(&file.bytes).is_some()); - if !relink { + if !file.request.purpose.starts_with("relink") { rest.push(file); continue; } @@ -353,11 +347,7 @@ impl DesignApp { } } for (request, batch) in batches { - let drop = request.purpose == "drop"; if self.activate_import_target(&request).is_err() { - if drop { - rest.extend(batch); - } continue; } // A file from a chosen folder is named by its path in it (which tells same-named @@ -374,7 +364,15 @@ impl DesignApp { Ok(v) => { let n = v["relinked"].as_u64().unwrap_or(0); let unsure = v["ambiguous"].as_array().map_or(0, Vec::len); - if unsure > 0 { + 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( @@ -382,21 +380,11 @@ impl DesignApp { .replace("{count}", &n.to_string()) .replace("{unsure}", &unsure.to_string()), ); - } else if n > 0 || !drop { + } else { self.status(crate::i18n::tr(&self.ui.language, "Relinked {count}").replace("{count}", &n.to_string())); } - // Dropped images that named no missing graphic are placed as before. - if drop { - let unused: Vec<&str> = v["unused"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - rest.extend(batch.into_iter().filter(|f| unused.iter().any(|u| file_name_of(&f.name) == *u))); - } - } - Err(e) => { - self.status(e); - if drop { - rest.extend(batch); - } } + Err(e) => self.status(e), } } rest @@ -614,21 +602,24 @@ pub(crate) mod browser_import_tests { 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 is placed, as ever, even when it is named like a missing graphic. make_missing(&mut app); - let request = app.import_request("drop"); - deliver(&mut app, request, "A.SVG", image()); - assert!(has_data(&app), "a dropped file named like the missing graphic relinks it"); - assert_eq!(items(&app), n, "nothing new is placed"); - // Nothing selected, so a placed image gets a frame of its own. app.run("edit.deselectAll", json!({})).unwrap(); let request = app.import_request("drop"); - deliver(&mut app, request, "other.svg", image()); - assert_eq!(items(&app), n + 1, "a dropped image that names no missing graphic is placed"); + deliver(&mut app, request, "A.SVG", image()); + assert!(!has_data(&app), "the dropped file doesn't relink"); + assert_eq!(items(&app), n + 1, "it is placed"); // 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) {