From dc8199999a9e77b08096951a0cf9c86ec8d1273b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 00:23:30 +0000 Subject: [PATCH 1/9] Web: relink graphics from files handed over MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the browser, linked graphics can't be read from their paths, and Relink… and Relink to Folder… asked a file dialog for a path that the web build doesn't have, so both did nothing: an IDML opened without its Links folder had no way to get its pictures. - links.relinkFiles relinks from files given by name and bytes: one graphic from a chosen file, or every missing graphic from the file of its name (any case), in one undo step. It shares the path relink's code (PDF page and crop, pixel size); a file named like the link keeps the link's path. - Web: Relink… opens the file picker for the selected graphic; Relink to Folder… picks several files at once. Dropped images named like a missing graphic relink it; others are placed as before. Dropped files are delivered together so they relink in one step. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- ROADMAP.md | 1 + apps/designcraft-web/src/main.rs | 5 +- apps/designcraft-web/src/web.rs | 34 ++++-- crates/engine/src/cmd/links.rs | 145 +++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 127 +++++++++++++++++++++ crates/ui-egui/src/panels/properties.rs | 34 ++++-- 6 files changed, 321 insertions(+), 25 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 9bd0274ef..1190de362 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -348,6 +348,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-18** · Web build: linked graphics relink from files handed over — Links › Relink… and Relink to Folder… open the browser's file picker (several files at once), 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-16** · Threading: the loaded text cursor threads into a text frame inside a group (it hit the group and showed it could not thread); a plain click still selects the group (#1075). Gap 27 closed. No readiness percentage change. - **2026-10-16** · Greek text hyphenates. The patterns were never compiled in, so Greek set unhyphenated however narrow the column; `"Greek"`, `"Greek: Greece"`, `el` and `el-GR` all resolve now and ανθρωπος breaks αν-θρω-πος. They are the monotonic patterns (hyph-el-monoton, Dimitrios Filippou, under MIT), which is what polytonic text hyphenates by too. Five of InDesign's ~40 hyphenation languages. No readiness percentage change. - **2026-10-16** · A swatch applied to a placed greyscale or bitmap image colours it, as in InDesign: IDML's `` is read and written, greyscale pixels become a tint of the swatch on opaque white and a bitmap's white lets the frame show through, on screen and in PDF (spot swatches print on their plate). Colour images keep their colours. Applying the swatch from the Swatches panel comes next. No readiness percentage change. diff --git a/apps/designcraft-web/src/main.rs b/apps/designcraft-web/src/main.rs index 1b28064a9..5b44d5e77 100644 --- a/apps/designcraft-web/src/main.rs +++ b/apps/designcraft-web/src/main.rs @@ -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; dropped images named like a missing graphic relink it, `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 diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index fe0f4a7fa..438c8a99d 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -352,19 +352,23 @@ impl eframe::App for WebShell { let graphics = self.graphics.clone(); let _ = graphics.run_if_healthy(|| { let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)); - for f in dropped { + if !dropped.is_empty() { 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 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(); + 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}"), } - 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(); }); } self.app.logic(ctx); @@ -395,17 +399,25 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { let ctx = ctx.clone(); let dialog = if request.purpose == "swatches" { rfd::AsyncFileDialog::new().add_filter("Swatch Exchange (ASE)", &["ase"]) - } else if request.purpose == "place" { + } else if request.purpose == "place" || request.purpose.starts_with("relink") { 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 gives no folders, so the moved files themselves, as many + // as are chosen; they arrive together, to relink in one step. + let several = request.purpose == "relinkFiles"; wasm_bindgen_futures::spawn_local(async move { - let Some(file) = dialog.pick_file().await else { + let picked = if several { dialog.pick_files().await } else { dialog.pick_file().await.map(|f| vec![f]) }; + let Some(picked) = picked else { return; }; - let bytes = file.read().await; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name: file.file_name(), bytes }); + let mut files = Vec::with_capacity(picked.len()); + for file in picked { + let bytes = file.read().await; + files.push(ImportedFile { request: request.clone(), name: file.file_name(), bytes }); + } + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); ctx.request_repaint(); }); })), diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index d77db3ea8..e38e0fcc2 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -47,6 +47,15 @@ pub fn specs() -> Vec { has_doc, relink_folder ), + cmd!( + "links.relinkFiles", + "Relink to Files", + [], + None, + "{files: [{name, base64}], asset?: id} — relink from files handed over by name (the web build's file picker and drops, which give no path): with `asset`, that graphic from the first file; otherwise every missing graphic from the file of the same name (any case), all in one undo step. A file named like the link keeps the link's path → {relinked, notFound: [missing graphics no file matched], unused: [files that matched nothing]}", + has_doc, + relink_files + ), cmd!( "links.update", "Update Link", @@ -358,11 +367,34 @@ 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) +} + +/// [`relinked_asset`] from a file handed over as bytes with its name (the browser's file picker +/// and drops give no path). A file of the same name as the link keeps the link's path, so the +/// document still finds 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) -> Result> { + let px = designcraft_render::image_size(&bytes).ok_or_else(|| bad("links", format!("{name}: unsupported or corrupt image")))?; + let link = match &a.link { + 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 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) +} + +/// 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> { 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) .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 }; @@ -371,7 +403,7 @@ fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result a.data = Arc::new(bytes); a.pixels = Some(px); a.page = page; - a.name = Path::new(link).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| link.to_string()); + a.name = link_file_name(link).to_string(); 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); @@ -460,6 +492,60 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { 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; + +fn relink_files(s: &mut Session, p: &Value) -> Result { + 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"))); + } + let mut files: Vec<(String, &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"))?; + files.push((link_file_name(name).to_string(), 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 = 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().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 { + for a in d.assets.values().filter(|a| status(a, document) == "missing") { + let want = a.link.as_deref().map_or(a.name.as_str(), link_file_name); + match files.iter().position(|(n, _)| n.eq_ignore_ascii_case(want) || n.eq_ignore_ascii_case(&a.name)) { + Some(k) => { + let (name, b64) = &files[k]; + fresh.push((a.id, relinked_bytes(a, name, super::base64_decode(b64))?)); + used[k] = true; + } + None => not_found.push(a.name.clone()), + } + } + } + let unused: Vec = 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(()) + })?; + } + Ok(json!({"relinked": n, "notFound": not_found, "unused": unused})) +} + fn update(s: &mut Session, p: &Value) -> Result { let (d, document) = { let st = s.doc()?; @@ -946,6 +1032,61 @@ 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 = 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 = Arc::new(Vec::new()); + } + Ok(()) + }) + .unwrap(); + (s, ids[0], ids[1]) + } + + /// 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(x, None) == "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. + 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()); + 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(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fcb764c5a..78500d1df 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1013,6 +1013,16 @@ impl DesignApp { Ok(Value::Null) } + /// 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 request = self.import_request(purpose); + 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) } } @@ -1057,6 +1067,7 @@ impl DesignApp { } let Some(inbox) = self.services.inbox.clone() else { return }; let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(|e| e.into_inner())); + let files = self.relink_from_inbox(files); for file in files { if self.ui.dialog.is_some() { self.status( @@ -1072,6 +1083,66 @@ 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. + 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 { + 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 { + let drop = request.purpose == "drop"; + if self.activate_import_target(&request).is_err() { + if drop { + rest.extend(batch); + } + continue; + } + let list: Vec = + batch.iter().map(|f| json!({"name": 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::().ok()) { + params["asset"] = json!(aid); + } + match self.run("links.relinkFiles", params) { + Ok(v) => { + let n = v["relinked"].as_u64().unwrap_or(0); + if n > 0 || !drop { + 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); + } + } + } + } + rest + } + fn import_file(&mut self, file: ImportedFile) -> Result { let lower = file.name.to_ascii_lowercase(); if let Some(kind) = file.request.purpose.strip_prefix("styles") { @@ -1717,6 +1788,11 @@ pub fn cjk_features(app: &DesignApp) -> bool { /// Files that open as documents (when dropped or picked) rather than being placed: DesignCraft, /// IDML, and InDesign documents and templates (converted to IDML on open). +/// 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) +} + pub fn opens_as_document(name: &str) -> bool { let n = name.to_ascii_lowercase(); [".designcraft", ".idml", ".indd", ".indt"].iter().any(|ext| n.ends_with(ext)) @@ -2800,6 +2876,57 @@ 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 = std::sync::Arc::new(Vec::new()); + Ok(()) + }) + .unwrap(); + aid + } + fn items(app: &DesignApp) -> usize { + app.session.doc().unwrap().doc.spreads.iter().map(|s| s.items.len()).sum() + } + + /// The web build relinks from files it is handed: chosen with Relink to Folder… (several at + /// once) or dropped. A dropped image named like a missing graphic relinks it instead of + /// being placed; one named like nothing is placed as before. + #[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")); + 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"); + // 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")); + } + fn deliver(app: &mut DesignApp, request: ImportRequest, name: &str, bytes: Vec) { app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request, name: name.into(), bytes }); app.drain_inbox(); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index fded030b9..dbe59ce07 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -2411,10 +2411,15 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { p[k] = v; p }; - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Relink…"))).clicked() - && let Some(path) = app.services.pick_open.as_mut().and_then(|pick| pick("relink")) - { - let _ = app.run("links.relink", with("path", json!(path))); + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Relink…"))).clicked() { + if app.services.pick_open.is_some() { + if let Some(path) = app.services.pick_open.as_mut().and_then(|pick| pick("relink")) { + let _ = app.run("links.relink", with("path", json!(path))); + } + } else if !is_text { + // The browser hands over the chosen file's bytes, not a path. + app.request_files(&format!("relink:{aid}")); + } } if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Go To"))).clicked() { let _ = app.run("links.goTo", target.clone()); @@ -2439,19 +2444,26 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { } }); ui.horizontal(|ui| { - // Choose any file in the folder: missing links are looked up there by name. + // Choose any file in the folder: missing links are looked up there by name. In the + // browser, which gives no folders, choose the files themselves. + let paths = app.services.pick_open.is_some(); + let hint = if paths { "Pick a file in the folder holding the moved graphics" } else { "Choose the moved graphics (several at once)" }; 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, "Pick a file in the folder holding the moved graphics")); + crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, hint)); }) .clicked() - && let Some(path) = app.services.pick_open.as_mut().and_then(|pick| pick("relink")) - && let Some(dir) = std::path::Path::new(&path).parent() { - let r = app.run("links.relinkFolder", json!({"dir": dir.to_string_lossy()})); - if let Ok(v) = r { - app.status(crate::i18n::tr(&app.ui.language, "Relinked {count}").replace("{count}", &v["relinked"].to_string())); + if !paths { + app.request_files("relinkFiles"); + } else if let Some(path) = app.services.pick_open.as_mut().and_then(|pick| pick("relink")) + && let Some(dir) = std::path::Path::new(&path).parent() + { + let r = app.run("links.relinkFolder", json!({"dir": dir.to_string_lossy()})); + if let Ok(v) = r { + app.status(crate::i18n::tr(&app.ui.language, "Relinked {count}").replace("{count}", &v["relinked"].to_string())); + } } } }); From f82a4be357d0679019cb995301066db4129da33e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 01:38:23 +0000 Subject: [PATCH 2/9] Web: Relink to Folder picks a folder The browser's file picker for Relink to Folder took single images. It now opens the browser's folder picker (input webkitdirectory) and hands over every graphic in the chosen folder, which relink by name in one step. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- apps/designcraft-web/Cargo.toml | 2 +- apps/designcraft-web/src/web.rs | 70 +++++++++++++++++++++---- crates/ui-egui/src/panels/properties.rs | 4 +- 3 files changed, 62 insertions(+), 14 deletions(-) diff --git a/apps/designcraft-web/Cargo.toml b/apps/designcraft-web/Cargo.toml index 1667e69e3..e6430f325 100644 --- a/apps/designcraft-web/Cargo.toml +++ b/apps/designcraft-web/Cargo.toml @@ -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"] } diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 438c8a99d..34e680b38 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -404,20 +404,25 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { } else { rfd::AsyncFileDialog::new().add_filter("DesignCraft, IDML or InDesign", DOC_EXTS) }; - // Relink to Folder: the browser gives no folders, so the moved files themselves, as many - // as are chosen; they arrive together, to relink in one step. - let several = request.purpose == "relinkFiles"; + // 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 = + pick_folder_files().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 { - let picked = if several { dialog.pick_files().await } else { dialog.pick_file().await.map(|f| vec![f]) }; - let Some(picked) = picked else { + let Some(file) = dialog.pick_file().await else { return; }; - let mut files = Vec::with_capacity(picked.len()); - for file in picked { - let bytes = file.read().await; - files.push(ImportedFile { request: request.clone(), name: file.file_name(), bytes }); - } - inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); + let bytes = file.read().await; + inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name: file.file_name(), bytes }); ctx.request_repaint(); }); })), @@ -430,6 +435,49 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { } } +/// The most files a chosen folder hands over for relinking. +const MAX_FOLDER_FILES: u32 = 2000; + +/// The graphics in a folder the user chooses with the browser's folder picker (an ``, which every current browser supports), with their names. Empty +/// when the picker is cancelled or can't be shown; files that aren't graphics are skipped. +async fn pick_folder_files() -> Vec<(String, Vec)> { + 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::().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. + 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(); + }); + input.click(); + let _ = wasm_bindgen_futures::JsFuture::from(chosen).await; + let Some(list) = input.files() else { return Vec::new() }; + let mut out = Vec::new(); + for i in 0..list.length().min(MAX_FOLDER_FILES) { + let Some(file) = list.get(i) else { continue }; + let name = file.name(); + let graphic = name.rsplit_once('.').is_some_and(|(_, ext)| IMAGE_EXTS.iter().any(|e| e.eq_ignore_ascii_case(ext))); + if !graphic { + continue; + } + if let Ok(buf) = wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await { + out.push((name, 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:?}"); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index dbe59ce07..bf109527d 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -2445,9 +2445,9 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { }); ui.horizontal(|ui| { // Choose any file in the folder: missing links are looked up there by name. In the - // browser, which gives no folders, choose the files themselves. + // browser, which hands over files rather than paths, choose the folder itself. let paths = app.services.pick_open.is_some(); - let hint = if paths { "Pick a file in the folder holding the moved graphics" } else { "Choose the moved graphics (several at once)" }; + let hint = if paths { "Pick a file in the folder holding the moved graphics" } else { "Choose the folder holding the moved graphics" }; if ui .button(crate::i18n::tr(&app.ui.language, "Relink to Folder…")) .on_hover_ui(|ui| { From e349e21ff6ca59b6dfd08eadff50d65e8c8fce21 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 19 Oct 2026 17:41:37 +0000 Subject: [PATCH 3/9] Web relink: tell same-named files apart; read only the missing graphics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fixes for links.relinkFiles and the web folder picker: - Files of the same name in different folders of a chosen folder no longer relink to whichever came first. Each file carries its path in the folder (webkitRelativePath), and each missing graphic takes the file whose path ends most like its link. Where nothing tells them apart (two equally likely files, or one file named only like graphics linking to different files) the graphic stays missing and is reported under `ambiguous`. Graphics linking to the same file still share it. - The folder picker reads only graphics named like a missing link (the request carries their names), with a graphics-only extension list, counting only accepted files toward the file limit, and within a total byte budget. - ROADMAP: Relink… opens a single-file picker, Relink to Folder… a folder picker. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- ROADMAP.md | 2 +- apps/designcraft-web/src/web.rs | 48 ++++++++--- crates/engine/src/cmd/links.rs | 144 ++++++++++++++++++++++++++++---- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/lib.rs | 49 ++++++++++- 5 files changed, 211 insertions(+), 34 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 1190de362..f8b3fd050 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -348,7 +348,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. -- **2026-10-18** · Web build: linked graphics relink from files handed over — Links › Relink… and Relink to Folder… open the browser's file picker (several files at once), 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), 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-16** · Threading: the loaded text cursor threads into a text frame inside a group (it hit the group and showed it could not thread); a plain click still selects the group (#1075). Gap 27 closed. No readiness percentage change. - **2026-10-16** · Greek text hyphenates. The patterns were never compiled in, so Greek set unhyphenated however narrow the column; `"Greek"`, `"Greek: Greece"`, `el` and `el-GR` all resolve now and ανθρωπος breaks αν-θρω-πος. They are the monotonic patterns (hyph-el-monoton, Dimitrios Filippou, under MIT), which is what polytonic text hyphenates by too. Five of InDesign's ~40 hyphenation languages. No readiness percentage change. - **2026-10-16** · A swatch applied to a placed greyscale or bitmap image colours it, as in InDesign: IDML's `` is read and written, greyscale pixels become a tint of the swatch on opaque white and a bitmap's white lets the frame show through, on screen and in PDF (spot swatches print on their plate). Colour images keep their colours. Applying the swatch from the Swatches panel comes next. No readiness percentage change. diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 34e680b38..0376d4c44 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -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"; @@ -399,7 +401,9 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { let ctx = ctx.clone(); let dialog = if request.purpose == "swatches" { rfd::AsyncFileDialog::new().add_filter("Swatch Exchange (ASE)", &["ase"]) - } else if request.purpose == "place" || request.purpose.starts_with("relink") { + } 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) @@ -408,8 +412,11 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { // chosen folder; they arrive together, to relink in one step. if request.purpose == "relinkFiles" { wasm_bindgen_futures::spawn_local(async move { - let files: Vec = - pick_folder_files().await.into_iter().map(|(name, bytes)| ImportedFile { request: request.clone(), name, bytes }).collect(); + let files: Vec = 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(); @@ -435,13 +442,16 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { } } -/// The most files a chosen folder hands over for relinking. -const MAX_FOLDER_FILES: u32 = 2000; +/// The most files a chosen folder hands over for relinking, and the most bytes in all. +const MAX_FOLDER_FILES: usize = 2000; +const MAX_FOLDER_BYTES: f64 = 1024.0 * 1024.0 * 1024.0; -/// The graphics in a folder the user chooses with the browser's folder picker (an ``, which every current browser supports), with their names. Empty -/// when the picker is cancelled or can't be shown; files that aren't graphics are skipped. -async fn pick_folder_files() -> Vec<(String, Vec)> { +/// 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 ``, 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)> { 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::().ok()) else { return Vec::new(); @@ -464,15 +474,27 @@ async fn pick_folder_files() -> Vec<(String, Vec)> { let _ = wasm_bindgen_futures::JsFuture::from(chosen).await; let Some(list) = input.files() else { return Vec::new() }; let mut out = Vec::new(); - for i in 0..list.length().min(MAX_FOLDER_FILES) { + 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)| IMAGE_EXTS.iter().any(|e| e.eq_ignore_ascii_case(ext))); - if !graphic { + 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((name, js_sys::Uint8Array::new(&buf).to_vec())); + out.push((path, js_sys::Uint8Array::new(&buf).to_vec())); } } out diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index e38e0fcc2..34fc7330c 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Relink to Files", [], None, - "{files: [{name, base64}], asset?: id} — relink from files handed over by name (the web build's file picker and drops, which give no path): with `asset`, that graphic from the first file; otherwise every missing graphic from the file of the same name (any case), all in one undo step. A file named like the link keeps the link's path → {relinked, notFound: [missing graphics no file matched], 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 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]}", has_doc, relink_files ), @@ -495,41 +495,99 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { /// 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. +fn match_files(missing: &[(AssetId, String)], files: &[(String, String)]) -> (Vec<(AssetId, usize)>, Vec, Vec) { + 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(); + let best = scores.iter().map(|(_, n)| *n).max().unwrap_or(0); + let top: Vec = 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) +} + fn relink_files(s: &mut Session, p: &Value) -> Result { 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"))); } - let mut files: Vec<(String, &str)> = Vec::new(); + // (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"))?; - files.push((link_file_name(name).to_string(), b64)); + 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 = Vec::new(); + let (mut not_found, mut ambiguous) = (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().ok_or_else(|| bad(ID, "no file"))?; + 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 { - for a in d.assets.values().filter(|a| status(a, document) == "missing") { - let want = a.link.as_deref().map_or(a.name.as_str(), link_file_name); - match files.iter().position(|(n, _)| n.eq_ignore_ascii_case(want) || n.eq_ignore_ascii_case(&a.name)) { - Some(k) => { - let (name, b64) = &files[k]; - fresh.push((a.id, relinked_bytes(a, name, super::base64_decode(b64))?)); - used[k] = true; - } - None => not_found.push(a.name.clone()), + let missing: Vec<(AssetId, String)> = d + .assets + .values() + .filter(|a| status(a, document) == "missing") + .map(|a| (a.id, a.link.clone().unwrap_or_else(|| a.name.clone()))) + .collect(); + let chosen; + (chosen, not_found, ambiguous) = match_files(&missing, &files); + 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; } } } @@ -543,7 +601,7 @@ fn relink_files(s: &mut Session, p: &Value) -> Result { Ok(()) })?; } - Ok(json!({"relinked": n, "notFound": not_found, "unused": unused})) + Ok(json!({"relinked": n, "notFound": not_found, "ambiguous": ambiguous, "unused": unused})) } fn update(s: &mut Session, p: &Value) -> Result { @@ -1056,6 +1114,62 @@ mod shared_asset_tests { (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) + } + + /// 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!(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. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 358416a4b..9330c632f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3270,7 +3270,7 @@ pub fn confirm(app: &mut DesignApp) -> Result { return app.confirm_pdf_import(d.n("page").unwrap_or(1.0).max(1.0) as u64, if crop.is_empty() { "crop".into() } else { crop }); } 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() })?; } app.place_file(json!({"path": d.s("path"), "pdfPage": d.n("page").unwrap_or(1.0).max(1.0) as u64, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }})) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 78500d1df..20d972f32 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -52,6 +52,9 @@ pub type PickFn = Box Option>; pub struct ImportRequest { pub purpose: String, pub target: Option, + /// 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, } pub struct ImportedFile { pub request: ImportRequest, @@ -1017,14 +1020,24 @@ impl DesignApp { /// `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 request = self.import_request(purpose); + 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(); + } 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> { @@ -1114,8 +1127,12 @@ impl DesignApp { } continue; } - let list: Vec = - batch.iter().map(|f| json!({"name": f.name, "base64": designcraft_engine::cmd::base64_encode(&f.bytes)})).collect(); + // A file from a chosen folder is named by its path in it (which tells same-named + // files apart). + let list: Vec = 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::().ok()) { params["asset"] = json!(aid); @@ -2895,6 +2912,30 @@ mod browser_import_tests { app.session.doc().unwrap().doc.spreads.iter().map(|s| s.items.len()).sum() } + /// 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##""##.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, image(), "the Links folder's file: {}", app.ui.status); + } + /// The web build relinks from files it is handed: chosen with Relink to Folder… (several at /// once) or dropped. A dropped image named like a missing graphic relinks it instead of /// being placed; one named like nothing is placed as before. From db9ede61d27b537def7532bf503b6bd62cac04e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 22:17:01 +0000 Subject: [PATCH 4/9] Web relink: review fixes (memory, journal, placed graphics, ambiguous files) CodeRabbit and FredApps review on #1244: - The folder read is capped at 256 MiB (was 1 GiB): the bytes are copied a few times on the way to the command, so 1 GiB could exhaust a tab's memory. A folder over the cap relinks what fits; running Relink to Folder again reads the rest, since relinked graphics are no longer wanted. - The command journal keeps links.relinkFiles' file names and paths, not their contents. - Relink to Folder with no missing graphic says so instead of reading a folder for nothing. - Only placed graphics relink: a replaced graphic kept for undo is missing too, and relinking it changed nothing on the page while reporting a relink. - A file named like missing graphics it can't be told apart for isn't reported as unused (so a dropped one isn't placed as a new picture); the status says how many were left missing. - file_name_of moved above opens_as_document's doc comment. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- apps/designcraft-web/src/web.rs | 4 ++- crates/engine/src/cmd/links.rs | 50 +++++++++++++++++++++++++++++---- crates/engine/src/lib.rs | 18 +++++++++++- crates/ui-egui/src/lib.rs | 34 ++++++++++++++++++++-- 4 files changed, 96 insertions(+), 10 deletions(-) diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 0376d4c44..33372f12e 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -444,7 +444,9 @@ 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; -const MAX_FOLDER_BYTES: f64 = 1024.0 * 1024.0 * 1024.0; +// 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 ``, which diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9a647ba46..a5f0d18c9 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -569,7 +569,10 @@ fn shared_tail(file: &str, link: &str) -> usize { /// 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. -fn match_files(missing: &[(AssetId, String)], files: &[(String, String)]) -> (Vec<(AssetId, usize)>, Vec, Vec) { +/// 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, Vec, Vec) { + let mut named = vec![false; files.len()]; let mut chosen = Vec::new(); let mut not_found = Vec::new(); let mut ambiguous = Vec::new(); @@ -577,6 +580,11 @@ fn match_files(missing: &[(AssetId, String)], files: &[(String, String)]) -> (Ve 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 = scores.iter().filter(|(_, n)| *n == best).map(|(k, _)| *k).collect(); match top.as_slice() { @@ -599,7 +607,7 @@ fn match_files(missing: &[(AssetId, String)], files: &[(String, String)]) -> (Ve chosen.push((*aid, *k)); } } - (chosen, not_found, ambiguous) + (chosen, not_found, ambiguous, named) } fn relink_files(s: &mut Session, p: &Value) -> Result { @@ -632,14 +640,20 @@ fn relink_files(s: &mut Session, p: &Value) -> Result { *u = true; } } else { + let placed = d.used_assets(); + // 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| status(a, document) == "missing") + .filter(|a| placed.contains(&a.id) && status(a, document) == "missing") .map(|a| (a.id, a.link.clone().unwrap_or_else(|| a.name.clone()))) .collect(); - let chosen; - (chosen, not_found, ambiguous) = match_files(&missing, &files); + 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 }; fresh.push((aid, relinked_bytes(a, name, super::base64_decode(b64))?)); @@ -1211,6 +1225,31 @@ mod shared_asset_tests { (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_journals_no_file_contents() { + 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()); + let (id, params) = s.journal.last().unwrap(); + assert_eq!(id, "links.relinkFiles"); + assert!(params["files"].as_array().unwrap().iter().all(|f| f.get("base64").is_none() && f["name"].is_string()), "{params}"); + } + /// 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 @@ -1235,6 +1274,7 @@ mod shared_asset_tests { 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); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 183b81c5c..283fecbe8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -615,7 +615,7 @@ impl Session { } self.record_undo_step(spec, before, nested); if spec.journal { - self.journal.push((id.to_string(), params.clone())); + self.journal.push((id.to_string(), journal_params(id, params))); } self.discard_stale_find_scope(); Ok(r) @@ -751,3 +751,19 @@ mod tests_params; mod tests_roots; #[cfg(test)] mod tests_table; + +/// 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 +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cbe20e27b..bc952fc0a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1032,6 +1032,11 @@ impl DesignApp { .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); @@ -1142,7 +1147,16 @@ impl DesignApp { match self.run("links.relinkFiles", params) { Ok(v) => { let n = v["relinked"].as_u64().unwrap_or(0); - if n > 0 || !drop { + let unsure = v["ambiguous"].as_array().map_or(0, Vec::len); + 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 if n > 0 || !drop { 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. @@ -1805,13 +1819,13 @@ pub fn cjk_features(app: &DesignApp) -> bool { app.session.prefs.cjk_features.unwrap_or_else(|| i18n::is_cjk(&app.ui.language)) } -/// Files that open as documents (when dropped or picked) rather than being placed: DesignCraft, -/// IDML, and InDesign documents and templates (converted to IDML on open). /// 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) } +/// Files that open as documents (when dropped or picked) rather than being placed: DesignCraft, +/// IDML, and InDesign documents and templates (converted to IDML on open). pub fn opens_as_document(name: &str) -> bool { let n = name.to_ascii_lowercase(); [".designcraft", ".idml", ".indd", ".indt"].iter().any(|ext| n.ends_with(ext)) @@ -2925,6 +2939,20 @@ mod browser_import_tests { 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] From 505d0063500e9ef3c3785f572579d6fa7bdbde16 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 18:46:58 +0000 Subject: [PATCH 5/9] Web relink: upstream's new open requests ask for no particular files Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- crates/ui-egui/src/app/files.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index d6de82db5..87b784611 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -12,7 +12,7 @@ impl DesignApp { #[track_caller] pub fn pick_and_open(&mut self, purpose: &str) -> Result { 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); } @@ -47,7 +47,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(); From 57100101f0238dec630452084cf95fcccd79917c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 21:27:06 +0000 Subject: [PATCH 6/9] Web relink: address review (drops no longer relink, the journal keeps the files, unreadable files reported, the picker's listener released, desktop names as before) - Dropping an image places it as before; relinking from a drop is left for its own change. The web host's drop handling is main's again. - links.relinkFiles is journaled with its files' bytes, as file.place {base64} is, so the entry replays; journal_params is gone. - In a folder relink, a matching file that can't be read is reported under failed and leaves its graphic missing; the others relink. The status names the unread files. One chosen file still errors. - The folder picker's change/cancel listener belongs to the call and is removed when the picker settles (no forget()). - Relink and Update name the graphic with Path::file_name, as main does; only a link kept from the file splits on either separator. --- ROADMAP.md | 2 +- apps/designcraft-web/src/web.rs | 42 +++++++++-------- crates/engine/src/cmd/links.rs | 81 +++++++++++++++++++++++++++------ crates/engine/src/lib.rs | 18 +------- crates/ui-egui/src/app/files.rs | 57 ++++++++++------------- 5 files changed, 115 insertions(+), 85 deletions(-) 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) { From bfc4777d8b73c970b49021aeccd9ba4cd16561f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 00:40:18 +0000 Subject: [PATCH 7/9] Web relink: comments no longer say drops relink --- apps/designcraft-web/src/main.rs | 2 +- crates/engine/src/cmd/links.rs | 4 ++-- crates/ui-egui/src/app/files.rs | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/designcraft-web/src/main.rs b/apps/designcraft-web/src/main.rs index 5b44d5e77..96dcbfbfe 100644 --- a/apps/designcraft-web/src/main.rs +++ b/apps/designcraft-web/src/main.rs @@ -12,7 +12,7 @@ //! - 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; dropped images named like a missing graphic relink it, `links.relinkFiles`). +//! 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 diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 19a1df1bd..b2979da08 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -471,8 +471,8 @@ fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result 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 -/// and drops give no path). A file of the same name as the link keeps the link's path, so the +/// [`relinked_asset`] from a file handed over as bytes with its name (the browser's file and +/// folder pickers give no path). A file of the same name as the link keeps the link's path, so the /// document still finds 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) -> Result> { diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 70fa158b2..be8141ee0 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -587,9 +587,9 @@ pub(crate) mod browser_import_tests { assert_eq!(*a.data, image(), "the Links folder's file: {}", app.ui.status); } - /// The web build relinks from files it is handed: chosen with Relink to Folder… (several at - /// once) or dropped. A dropped image named like a missing graphic relinks it instead of - /// being placed; one named like nothing is placed as before. + /// 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(); From 511d5edd2752d15f3547c7dcda78454bd1408863 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:30:55 +0000 Subject: [PATCH 8/9] Apply review fixes - crates/engine/src/cmd/links.rs - docs/linked-artwork.md --- crates/engine/src/cmd/links.rs | 3 +++ docs/linked-artwork.md | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 059ab738d..04f844c67 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -915,6 +915,9 @@ fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, document: Option<&Pat /// 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) -> Result> { + 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)); diff --git a/docs/linked-artwork.md b/docs/linked-artwork.md index 045c4a7e5..6d1816ac5 100644 --- a/docs/linked-artwork.md +++ b/docs/linked-artwork.md @@ -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". From 60024fea6bcfd1473e3e309dcc3a83fc4d47d739 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:04:50 +0700 Subject: [PATCH 9/9] =?UTF-8?q?Links:=20say=20why=20Relink=E2=80=A6=20does?= =?UTF-8?q?=20nothing=20for=20a=20linked=20text=20file=20in=20the=20browse?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A browser hands over bytes, not paths, and a linked text story is read from its path, so the click was silently ignored. It now puts a status message up. (autocraft-bot review) --- crates/ui-egui/src/panels/properties/links.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/links.rs b/crates/ui-egui/src/panels/properties/links.rs index 795f6d819..06d039967 100644 --- a/crates/ui-egui/src/panels/properties/links.rs +++ b/crates/ui-egui/src/panels/properties/links.rs @@ -192,7 +192,11 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let browser = app.services.open_async.is_some(); if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Relink…"))).clicked() { if browser { - if !is_text { + // 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 {