diff --git a/ROADMAP.md b/ROADMAP.md index 8ac3a295d..de45c6f39 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -23,6 +23,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. - Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands. - Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands. +- Links panel: every placed graphic with status (OK / Modified / Missing / Embedded, checked against the file on disk), page and effective PPI (low resolution flagged); Relink…, Go To, Update, Embed; `links.*` commands. - Menus expose the engine's features (TOC, numbering & sections, text variables, hyperlinks, cross-references, footnotes, step and repeat, spelling, fitting/content, effects, Data Merge, Preflight, EPUB); any menu command with parameters gets a dialog generated from its parameter documentation. - Table of contents (generate/update, dot leaders) and text variables (running headers, last page number, chapter number, file name, dates, custom) resolved per page. - Soft effects: blurred drop shadow, inner shadow, outer glow, basic feather. @@ -30,7 +31,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - MCP server (`designcraft-cli mcp [--connect PORT]`, docs/mcp.md): headless engine or the running app; commands, batch, document/story inspection, page renders as images, window screenshots, pointer/keyboard/dialog input. - Web build (`apps/designcraft-web`, trunk): the same UI on WebGPU with a WebGL2 fallback; open/place via the browser file picker or drag-and-drop, save/export as downloads. -**Next (in order):** books, footnotes in EPUB / span columns / split footnotes · table/cell styles, text rotation in cells · PDF/X-4 output intent, tagged PDF · Links panel + relink · UI for Data Merge/spelling/hyperlinks. +**Next (in order):** books, footnotes in EPUB / span columns / split footnotes · table/cell styles, text rotation in cells · PDF/X-4 output intent, tagged PDF · UI for Data Merge/spelling/hyperlinks. ## Milestones diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs new file mode 100644 index 000000000..6b24815bc --- /dev/null +++ b/crates/engine/src/cmd/links.rs @@ -0,0 +1,232 @@ +//! Window › Links: placed graphics with their status, effective resolution and uses; relink, +//! update, embed, go to. +//! +//! Every placed graphic keeps its bytes in the document; a linked graphic also remembers its +//! file. Its status compares that file with the copy in the document: missing, modified (the +//! file's bytes differ) or OK. + +use std::sync::Arc; + +use designcraft_doc::{AssetId, Content, Document, ItemId, Selection}; +use serde_json::{Value, json}; + +use super::{CommandSpec, bad, cmd, has_doc, str_param}; +use crate::{EngineError, Result, Session}; + +pub fn specs() -> Vec { + vec![ + cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, status: ok|modified|missing|embedded, pixels, uses: [{id, page, ppi}]}]", has_doc, |s, _| { + Ok(Value::Array(list(&s.doc()?.doc))) + }), + cmd!( + "links.relink", + "Relink…", + ["Window", "Links"], + None, + "{asset, path} — use another file for every placement of the graphic", + has_doc, + relink + ), + cmd!( + "links.update", + "Update Link", + ["Window", "Links"], + None, + "{asset?} — reload modified links from their files (all when no asset)", + has_doc, + update + ), + cmd!("links.embed", "Embed Link", ["Window", "Links"], None, "{asset} — keep only the copy in the document", has_doc, |s, p| { + let aid = asset_param(p, "links.embed")?; + s.edit(|d, _| { + let a = d.assets.get_mut(&aid).ok_or_else(|| bad("links.embed", "no such graphic"))?; + Arc::make_mut(a).link = None; + Ok(Value::Null) + }) + }), + cmd!(noundo "links.goTo", "Go To Link", ["Window", "Links"], None, "{asset} — selects the frames showing the graphic", has_doc, |s, p| { + let aid = asset_param(p, "links.goTo")?; + let st = s.doc_mut()?; + let ids = uses(&st.doc, aid); + if ids.is_empty() { + return Err(bad("links.goTo", "the graphic isn't placed")); + } + st.selection = Selection::items(ids.clone()); + st.revision += 1; + Ok(json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + }), + ] +} + +fn asset_param(p: &Value, cmd: &str) -> Result { + p.get("asset").and_then(Value::as_u64).map(AssetId).ok_or_else(|| bad(cmd, "missing asset")) +} + +/// Frames (graphic content) showing an asset, top-level or in groups. +fn uses(d: &Document, aid: AssetId) -> Vec { + let mut out = Vec::new(); + for sp in d.spreads.iter().chain(&d.parents) { + for it in &sp.items { + it.walk(&mut |i| { + if let Content::Graphic(g) = &i.content + && g.asset == aid + { + out.push(i.id); + } + }); + } + } + out +} + +/// Link status of an asset. +pub fn status(a: &designcraft_doc::Asset) -> &'static str { + let Some(path) = &a.link else { return "embedded" }; + #[cfg(not(target_arch = "wasm32"))] + { + match std::fs::metadata(path) { + Err(_) => "missing", + Ok(m) if m.len() as usize != a.data.len() => "modified", + // Same size: compare the bytes (cheap for the sizes involved, and exact). + Ok(_) => match std::fs::read(path) { + Ok(b) if b == *a.data => "ok", + Ok(_) => "modified", + Err(_) => "missing", + }, + } + } + #[cfg(target_arch = "wasm32")] + { + let _ = path; + "ok" + } +} + +fn list(d: &Document) -> Vec { + d.assets + .values() + .map(|a| { + let uses: Vec = uses(d, a.id) + .into_iter() + .map(|id| { + // Effective resolution: image pixels over the size it is shown at. + let ppi = (|| { + let loc = d.find(id)?; + let it = d.item_at(&loc)?; + let Content::Graphic(g) = &it.content else { return None }; + let (pw, _) = a.pixels?; + let xf = d.parent_xf(&loc) * it.xf * g.xf; + let shown_w = xf.transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1)).width(); + (shown_w > 0.0).then(|| (pw as f64 / (shown_w / 72.0)).round()) + })(); + let page = d.page_of_item(id).map(|p| d.page_name(p)); + json!({"id": id.0, "page": page, "ppi": ppi}) + }) + .collect(); + json!({"asset": a.id.0, "name": a.name, "path": a.link, "status": status(a), "pixels": a.pixels, "uses": uses}) + }) + .collect() +} + +#[cfg(not(target_arch = "wasm32"))] +fn reload(path: &str) -> Result<(Vec, (u32, u32))> { + let b = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let px = designcraft_render::image_size(&b).ok_or_else(|| bad("links", format!("{path}: unsupported or corrupt image")))?; + Ok((b, px)) +} + +#[cfg(target_arch = "wasm32")] +fn reload(path: &str) -> Result<(Vec, (u32, u32))> { + Err(EngineError::Other(format!("{path}: files can't be read on the web"))) +} + +fn relink(s: &mut Session, p: &Value) -> Result { + let aid = asset_param(p, "links.relink")?; + let path = str_param(p, "path").ok_or_else(|| bad("links.relink", "missing path"))?.to_string(); + let (bytes, px) = reload(&path)?; + let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone()); + s.edit(|d, _| { + let a = d.assets.get_mut(&aid).ok_or_else(|| bad("links.relink", "no such graphic"))?; + let a = Arc::make_mut(a); + a.mime = designcraft_render::image_mime(&bytes).to_string(); + a.data = Arc::new(bytes.clone()); + a.pixels = Some(px); + a.name = name.clone(); + a.link = Some(path.clone()); + Ok(json!({"name": name})) + }) +} + +fn update(s: &mut Session, p: &Value) -> Result { + let d = &s.doc()?.doc; + let which: Vec<(AssetId, String)> = d + .assets + .values() + .filter(|a| p.get("asset").and_then(Value::as_u64).is_none_or(|x| x == a.id.0)) + .filter(|a| status(a) == "modified") + .filter_map(|a| a.link.clone().map(|l| (a.id, l))) + .collect(); + let mut fresh = Vec::new(); + for (aid, path) in which { + fresh.push((aid, reload(&path)?)); + } + let n = fresh.len(); + if n == 0 { + return Ok(json!({"updated": 0})); + } + s.edit(|d, _| { + for (aid, (bytes, px)) in &fresh { + if let Some(a) = d.assets.get_mut(aid) { + let a = Arc::make_mut(a); + a.data = Arc::new(bytes.clone()); + a.pixels = Some(*px); + } + } + Ok(json!({"updated": n})) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png(w: u32, h: u32) -> Vec { + designcraft_render::Rendered { width: w, height: h, pixels: vec![200u8; (w * h * 4) as usize] }.to_png() + } + + #[test] + fn link_status_relink_update_embed() { + let dir = std::env::temp_dir().join(format!("dc-links-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let a = dir.join("a.png"); + let b = dir.join("b.png"); + std::fs::write(&a, png(10, 10)).unwrap(); + std::fs::write(&b, png(20, 10)).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.place", &json!({"path": a.to_string_lossy(), "x": 72, "y": 72, "width": 72})).unwrap(); + let l = s.execute("links.list", &json!({})).unwrap(); + assert_eq!(l[0]["status"], "ok"); + assert_eq!(l[0]["uses"][0]["ppi"], 10.0, "10 px over 1 inch"); + let aid = l[0]["asset"].as_u64().unwrap(); + // The file changes on disk. + std::fs::write(&a, png(30, 10)).unwrap(); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "modified"); + s.execute("links.update", &json!({})).unwrap(); + let l = s.execute("links.list", &json!({})).unwrap(); + assert_eq!(l[0]["status"], "ok"); + assert_eq!(l[0]["pixels"], json!([30, 10])); + // Missing, then relinked. + std::fs::remove_file(&a).unwrap(); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "missing"); + s.execute("links.relink", &json!({"asset": aid, "path": b.to_string_lossy()})).unwrap(); + let l = s.execute("links.list", &json!({})).unwrap(); + assert_eq!((l[0]["status"].as_str(), l[0]["name"].as_str()), (Some("ok"), Some("b.png"))); + // Go to selects the frame; embed forgets the file. + let r = s.execute("links.goTo", &json!({"asset": aid})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 1); + s.execute("links.embed", &json!({"asset": aid})).unwrap(); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "embedded"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 2e649dd68..6a5fdaf9e 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -12,6 +12,7 @@ mod inspect; mod interactive; pub mod interchange; mod layout; +mod links; mod notes; mod object; pub mod preflight; @@ -132,6 +133,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(index::specs()); v.extend(anchored::specs()); v.extend(guides::specs()); + v.extend(links::specs()); v.extend(spelling::specs()); v.extend(datamerge::specs()); v.extend(interactive::specs()); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 7ed95bc33..5f5a2079f 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1358,24 +1358,88 @@ pub fn align_panel(app: &mut DesignApp, ui: &mut egui::Ui) { }); } +/// Links: status (missing / modified / embedded), page and effective resolution of every placed +/// graphic; Relink, Go To Link, Update Link, Embed Link for the chosen row. pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let Some(st) = app.session.active() else { return }; let t = Tokens::get(ui.ctx()); - let assets: Vec<(String, Option<(u32, u32)>, bool)> = st.doc.assets.values().map(|a| (a.name.clone(), a.pixels, a.link.is_some())).collect(); - if assets.is_empty() { + // The list checks files on disk: refresh it at most twice a second. + let key = egui::Id::new("links_panel"); + let now = ui.input(|i| i.time); + let rev = (st.uid, st.revision); + let cached: Option<(f64, (u64, u64), Vec)> = ui.data(|d| d.get_temp(key)); + let rows = match cached { + Some((at, r, rows)) if r == rev && now - at < 0.5 => rows, + _ => { + let rows = app.session.execute("links.list", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default(); + ui.data_mut(|d| d.insert_temp(key, (now, rev, rows.clone()))); + rows + } + }; + if rows.is_empty() { ui.label(egui::RichText::new("No placed graphics.").color(t.text_dim)); + return; } - for (name, px, linked) in assets { - ui.horizontal(|ui| { - ui.label(&name); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(egui::RichText::new(if linked { "Linked" } else { "Embedded" }).color(t.text_dim).size(11.0)); - if let Some((w, h)) = px { - ui.label(egui::RichText::new(format!("{w}×{h}")).color(t.text_dim).size(11.0)); + let sel_key = egui::Id::new("links_panel_sel"); + let mut chosen: Option = ui.data(|d| d.get_temp(sel_key)); + egui::Grid::new("links_grid").num_columns(3).striped(true).spacing([10.0, 4.0]).show(ui, |ui| { + ui.label(egui::RichText::new("Name").color(t.text_dim).size(11.0)); + ui.label(egui::RichText::new("Status").color(t.text_dim).size(11.0)); + ui.label(egui::RichText::new("Page · PPI").color(t.text_dim).size(11.0)); + ui.end_row(); + for r in &rows { + let aid = r["asset"].as_u64().unwrap_or(0); + let name = r["name"].as_str().unwrap_or(""); + if ui.selectable_label(chosen == Some(aid), name).clicked() { + chosen = Some(aid); + } + let (txt, col) = match r["status"].as_str().unwrap_or("") { + "missing" => ("\u{26A0} Missing", egui::Color32::from_rgb(0xe5, 0x4b, 0x4b)), + "modified" => ("\u{25B2} Modified", egui::Color32::from_rgb(0xe8, 0xb3, 0x2c)), + "embedded" => ("Embedded", t.text_dim), + _ => ("OK", t.text_dim), + }; + ui.label(egui::RichText::new(txt).color(col).size(11.0)); + let uses = r["uses"].as_array().cloned().unwrap_or_default(); + let info = match uses.first() { + Some(u) => { + let page = u["page"].as_str().unwrap_or("PB"); + let ppi = u["ppi"].as_f64().map(|p| format!(" · {p:.0} ppi")).unwrap_or_default(); + let more = if uses.len() > 1 { format!(" (+{})", uses.len() - 1) } else { String::new() }; + format!("{page}{ppi}{more}") } - }); - }); + None => "unused".into(), + }; + // Low effective resolution for print is flagged like the Preflight check. + let low = uses.first().and_then(|u| u["ppi"].as_f64()).is_some_and(|p| p < 150.0); + ui.label(egui::RichText::new(info).size(11.0).color(if low { egui::Color32::from_rgb(0xe8, 0xb3, 0x2c) } else { t.text_dim })); + ui.end_row(); + } + }); + if let Some(c) = chosen { + ui.data_mut(|d| d.insert_temp(sel_key, c)); } + ui.add_space(6.0); + ui.horizontal(|ui| { + let Some(aid) = chosen else { + ui.label(egui::RichText::new("Choose a link.").color(t.text_dim).size(11.0)); + return; + }; + if ui.button("Relink…").clicked() + && let Some(path) = app.services.pick_open.as_mut().and_then(|pick| pick("relink")) + { + let _ = app.run("links.relink", json!({"asset": aid, "path": path})); + } + if ui.button("Go To").clicked() { + let _ = app.run("links.goTo", json!({"asset": aid})); + } + if ui.button("Update").clicked() { + let _ = app.run("links.update", json!({"asset": aid})); + } + if ui.button("Embed").clicked() { + let _ = app.run("links.embed", json!({"asset": aid})); + } + }); } pub fn info_panel(app: &mut DesignApp, ui: &mut egui::Ui) {