DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
F: Global Light and Generate Static Caption
Brandon Thomas74e352698e9c
diff --git a/ROADMAP.md b/ROADMAP.mdindex efe96e109..c07ba6968 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -34,6 +34,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- Script Label (`object.label`, `object.findByLabel`), alt text (`object.altText`), Isolate Blending / Knockout Group (`object.transparencyGroup`; on screen, PDF isolates), Table ▸ Sort (`table.sortRows`, numeric-aware, header/footer fixed).- File ▸ Export Text (`file.exportText`): a story as Text Only or RTF (fonts, styles, alignment, indents, tables as tab-separated rows); Export EPUB now asks for a path in the UI.- Tagged PDF (`file.exportPdf {tagged}`, on by default from the UI): structure tree with stories as paragraphs in reading order, figures carrying their alt text, parent-page items and printer's marks as artifacts.+- Global Light (`object.globalLight`, `globalLight` on drop/inner shadows; Use Global Light in the Effects panel) and Generate Static Caption (`object.caption`: template over name, path, alt text, label, effective ppi, dimensions, format; any side, offset, style).- Drag and drop text editing: drag selected text to move it (Alt copies) with its formatting (`text.release`).- Image Import Options: place any page of a multi-page PDF (`file.place {pdfPage}`; the app asks which page), shown on screen and embedded as that page in PDF export.- Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rsindex 01b45267b..3e3c61396 100644--- a/crates/doc/src/item.rs+++ b/crates/doc/src/item.rs@@ -433,6 +433,9 @@ pub struct DropShadow {pub color: String,pub opacity: f32,pub angle: f64,+ /// Use Global Light (the document angle instead of `angle`).+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub global_light: bool,pub distance: f64,pub size: f64,pub spread: f64,@@ -440,7 +443,16 @@ pub struct DropShadow {impl Default for DropShadow {fn default() -> Self {- DropShadow { on: false, color: designcraft_color::swatch::BLACK.into(), opacity: 0.75, angle: 135.0, distance: 7.0, size: 5.0, spread: 0.0 }+ DropShadow {+ on: false,+ color: designcraft_color::swatch::BLACK.into(),+ opacity: 0.75,+ angle: 135.0,+ distance: 7.0,+ size: 5.0,+ spread: 0.0,+ global_light: false,+ }}}@@ -452,6 +464,9 @@ pub struct InnerShadow {pub color: String,pub opacity: f32,pub angle: f64,+ /// Use Global Light (the document angle instead of `angle`).+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub global_light: bool,pub distance: f64,pub size: f64,/// Percentage (0–100) of `size` that hardens the edge instead of blurring it.@@ -460,7 +475,16 @@ pub struct InnerShadow {impl Default for InnerShadow {fn default() -> Self {- InnerShadow { on: false, color: designcraft_color::swatch::BLACK.into(), opacity: 0.75, angle: 135.0, distance: 7.0, size: 7.0, choke: 0.0 }+ InnerShadow {+ on: false,+ color: designcraft_color::swatch::BLACK.into(),+ opacity: 0.75,+ angle: 135.0,+ distance: 7.0,+ size: 7.0,+ choke: 0.0,+ global_light: false,+ }}}diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex 43709a9cf..075364214 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -162,6 +162,8 @@ pub struct DocSettings {pub primary_story: Option<StoryId>,/// Chapter number (Numbering & Section Options › Document Chapter Numbering).pub chapter_number: u32,+ /// Object › Effects › Global Light: the angle (degrees) shadows that use it share.+ pub global_light: f64,}impl Default for DocSettings {@@ -187,6 +189,7 @@ impl Default for DocSettings {primary_story: None,lists: Vec::new(),chapter_number: 1,+ global_light: 120.0,}}}@@ -454,6 +457,11 @@ impl Document {}/// Resolve a swatch reference to a display colour.+ /// A shadow's light angle: its own, or the document's Global Light.+ pub fn light_angle(&self, angle: f64, global: bool) -> f64 {+ if global { self.settings.global_light } else { angle }+ }+pub fn resolve_color(&self, swatch: &str, tint: f32) -> Option<designcraft_color::Color> {designcraft_color::swatch::resolve(&self.swatches, swatch, tint)}diff --git a/crates/engine/src/cmd/captions.rs b/crates/engine/src/cmd/captions.rsnew file mode 100644index 000000000..285e728db--- /dev/null+++ b/crates/engine/src/cmd/captions.rs@@ -0,0 +1,133 @@+//! Object › Captions › Generate Static Caption: a text frame beside each selected object, filled+//! from its metadata.++use designcraft_doc::{Document, Item, ItemId, ParaFormat, Selection};+use designcraft_geom::Rect;+use serde_json::{Value, json};++use super::{CommandSpec, bad, cmd, has_selection, str_param, targets};+use crate::{Result, Session};++pub fn specs() -> Vec<CommandSpec> {+ vec![cmd!(+ "object.caption",+ "Generate Static Caption",+ ["Object", "Captions"],+ None,+ "{text?: template (default \"{name}\"; variables {name} {path} {altText} {label} {ppi} {dimensions} {format}), position?: below|above|left|right, offset? (pt, 0), height? (pt, 24), style?: paragraph style, ids?} → {ids}",+ has_selection,+ caption+ )]+}++/// The metadata variables of `it`.+fn variable(d: &Document, it: &Item, xf: designcraft_geom::Affine, name: &str) -> String {+ let g = it.graphic();+ let asset = g.and_then(|g| d.assets.get(&g.asset));+ match name {+ "name" => asset.map(|a| a.name.clone()).unwrap_or_default(),+ "path" => asset.and_then(|a| a.link.clone()).unwrap_or_default(),+ "altText" => it.alt_text.clone(),+ "label" => it.label.clone(),+ "format" => asset.map(|a| a.mime.rsplit('/').next().unwrap_or("").to_uppercase()).unwrap_or_default(),+ "dimensions" => asset.and_then(|a| a.pixels).map(|(w, h)| format!("{w} × {h}")).unwrap_or_default(),+ "ppi" => match (g, asset.and_then(|a| a.pixels)) {+ (Some(g), Some((w, _))) if g.size.0 > 0.0 => {+ let m = (xf * g.xf).as_coeffs();+ let scale = m[0].hypot(m[1]);+ let inches = g.size.0 * scale / 72.0;+ if inches > 0.0 { format!("{}", (w as f64 / inches).round()) } else { String::new() }+ }+ _ => String::new(),+ },+ _ => String::new(),+ }+}++fn fill(d: &Document, it: &Item, xf: designcraft_geom::Affine, template: &str) -> String {+ let mut out = String::new();+ let mut rest = template;+ while let Some(i) = rest.find('{') {+ out.push_str(&rest[..i]);+ match rest[i..].find('}') {+ Some(j) => {+ out.push_str(&variable(d, it, xf, &rest[i + 1..i + j]));+ rest = &rest[i + j + 1..];+ }+ None => {+ out.push_str(&rest[i..]);+ rest = "";+ }+ }+ }+ out.push_str(rest);+ out+}++fn caption(s: &mut Session, p: &Value) -> Result<Value> {+ const ID: &str = "object.caption";+ let ids = targets(s, p)?;+ let template = str_param(p, "text").unwrap_or("{name}").to_string();+ let pos = str_param(p, "position").unwrap_or("below").to_string();+ if !["below", "above", "left", "right"].contains(&pos.as_str()) {+ return Err(bad(ID, format!("unknown position `{pos}`")));+ }+ let offset = p.get("offset").and_then(Value::as_f64).unwrap_or(0.0);+ let height = p.get("height").and_then(Value::as_f64).unwrap_or(24.0).max(1.0);+ let style = str_param(p, "style").map(str::to_string);+ if let Some(st) = &style+ && s.doc()?.doc.styles.para(st).is_none()+ {+ return Err(bad(ID, format!("no paragraph style `{st}`")));+ }+ let lid = s.doc()?.active_layer;+ s.edit(|d, sel| {+ let mut made = Vec::new();+ for id in &ids {+ let Some(loc) = d.find(*id) else { continue };+ let Some(it) = d.item_at(&loc) else { continue };+ let xf = d.parent_xf(&loc) * it.xf;+ let b = xf.transform_rect_bbox(it.inner_bounds());+ let text = fill(d, it, xf, &template);+ let r = match pos.as_str() {+ "above" => Rect::new(b.x0, b.y0 - offset - height, b.x1, b.y0 - offset),+ "left" => Rect::new(b.x0 - offset - 144.0, b.y0, b.x0 - offset, b.y1),+ "right" => Rect::new(b.x1 + offset, b.y0, b.x1 + offset + 144.0, b.y1),+ _ => Rect::new(b.x0, b.y1 + offset, b.x1, b.y1 + offset + height),+ };+ let para = ParaFormat { style: style.clone().unwrap_or_else(|| d.styles.default_paragraph.clone()), ..Default::default() };+ let (cid, _) = d.add_text_frame(loc.spread, r, lid, &text, para)?;+ made.push(cid);+ }+ if made.is_empty() {+ return Err(bad(ID, "nothing to caption"));+ }+ *sel = Selection::items(made.clone());+ Ok(json!({"ids": made.iter().map(|i: &ItemId| i.0).collect::<Vec<_>>()}))+ })+}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use crate::Session;++ #[test]+ fn static_caption_from_metadata() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap();+ s.execute("object.altText", &json!({"text": "Harbour at dawn", "ids": [a]})).unwrap();+ s.execute("object.label", &json!({"label": "fig-1", "ids": [a]})).unwrap();+ let r = s.execute("object.caption", &json!({"ids": [a], "text": "Figure {label}: {altText}", "offset": 6})).unwrap();+ let cid = designcraft_doc::ItemId(r["ids"][0].as_u64().unwrap());+ let d = &s.doc().unwrap().doc;+ let c = d.item(cid).unwrap();+ let b = c.bounds();+ assert_eq!((b.x0, b.y0, b.x1), (72.0, 178.0, 272.0));+ let sid = c.text_frame().unwrap().story;+ assert_eq!(d.stories[&sid].text, "Figure fig-1: Harbour at dawn");+ assert!(s.execute("object.caption", &json!({"ids": [a], "position": "sideways"})).is_err());+ }+}diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 506f9ca11..7873da343 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -2,6 +2,7 @@mod anchored;pub mod anchors;+mod captions;mod datamerge;mod edit;mod export;@@ -132,6 +133,7 @@ pub fn command_specs() -> &'static [CommandSpec] {v.extend(object::specs());v.extend(anchors::specs());v.extend(paths::specs());+ v.extend(captions::specs());v.extend(lists::specs());v.extend(path_type::specs());v.extend(package::specs());diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rsindex 1d92e7c7e..03d0d0884 100644--- a/crates/engine/src/cmd/object.rs+++ b/crates/engine/src/cmd/object.rs@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {"Drop Shadow",["Object", "Effects"],Some("Cmd+Alt+M"),- "{on?: bool, distance?, angle?, opacity?, size?, spread? (%), color? (swatch), ids?}",+ "{on?: bool, distance?, angle?, globalLight?: bool, opacity?, size?, spread? (%), color? (swatch), ids?}",has_selection,|s, p| {let p2 = p.clone();@@ -237,6 +237,7 @@ pub fn specs() -> Vec<CommandSpec> {ds.on = p2.get("on").and_then(Value::as_bool).unwrap_or(!ds.on);ds.distance = f64_or(&p2, "distance", ds.distance);ds.angle = f64_or(&p2, "angle", ds.angle);+ ds.global_light = p2.get("globalLight").and_then(Value::as_bool).unwrap_or(ds.global_light);ds.opacity = f64_or(&p2, "opacity", ds.opacity as f64) as f32;ds.size = f64_or(&p2, "size", ds.size);ds.spread = f64_or(&p2, "spread", ds.spread);@@ -253,7 +254,7 @@ pub fn specs() -> Vec<CommandSpec> {"Inner Shadow",["Object", "Effects"],None,- "{on?: bool, distance?, angle?, opacity?, size?, choke? (%), color?, ids?}",+ "{on?: bool, distance?, angle?, globalLight?: bool, opacity?, size?, choke? (%), color?, ids?}",has_selection,|s, p| {let p2 = p.clone();@@ -265,6 +266,7 @@ pub fn specs() -> Vec<CommandSpec> {e.on = p2.get("on").and_then(Value::as_bool).unwrap_or(!e.on);e.distance = f64_or(&p2, "distance", e.distance);e.angle = f64_or(&p2, "angle", e.angle);+ e.global_light = p2.get("globalLight").and_then(Value::as_bool).unwrap_or(e.global_light);e.opacity = f64_or(&p2, "opacity", e.opacity as f64) as f32;e.size = f64_or(&p2, "size", e.size);e.choke = f64_or(&p2, "choke", e.choke);@@ -422,6 +424,22 @@ pub fn specs() -> Vec<CommandSpec> {Ok(json!({"sides": s.prefs.polygon_sides, "starInset": (s.prefs.star_inset * 100.0).round()}))}),+ cmd!(+ "object.globalLight",+ "Global Light…",+ ["Object", "Effects"],+ None,+ "{angle} — the light angle shared by shadows that use Global Light",+ has_doc,+ |s, p| {+ let a = p.get("angle").and_then(Value::as_f64).ok_or_else(|| bad("object.globalLight", "angle required"))?;+ let a = (a + 180.0).rem_euclid(360.0) - 180.0;+ s.edit(|d, _| {+ d.settings.global_light = a;+ Ok(json!({"angle": a}))+ })+ }+ ),cmd!("object.label","Script Label",@@ -1495,3 +1513,27 @@ mod label_tests {assert!(!s.doc().unwrap().doc.item(ItemId(b)).unwrap().knockout);}}++#[cfg(test)]+mod light_tests {+ use super::*;++ #[test]+ fn global_light_moves_shadows_that_use_it() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let a = s.execute("frame.create", &json!({"rect": [10, 10, 50, 50]})).unwrap()["id"].as_u64().unwrap();+ s.execute("object.dropShadow", &json!({"on": true, "angle": 45, "ids": [a]})).unwrap();+ let angle = |s: &Session| {+ let d = &s.doc().unwrap().doc;+ let ds = &d.item(ItemId(a)).unwrap().effects.drop_shadow;+ d.light_angle(ds.angle, ds.global_light)+ };+ s.execute("object.globalLight", &json!({"angle": 200})).unwrap();+ assert_eq!(angle(&s), 45.0, "own angle");+ s.execute("object.dropShadow", &json!({"globalLight": true, "on": true, "ids": [a]})).unwrap();+ assert_eq!(angle(&s), -160.0, "normalised to -180..180");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(angle(&s), 45.0);+ }+}diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rsindex f44acb20c..841aeff20 100644--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@ -1337,7 +1337,7 @@ impl<'a> Ex<'a> {let mut t = El::new("TransparencySetting");t.push(El::new("BlendingSetting").attr("BlendMode", names::blend_out(it.blend)).attr("Opacity", pct(it.opacity as f64)));if ds.on {- let a = ds.angle.to_radians();+ let a = self.d.light_angle(ds.angle, ds.global_light).to_radians();t.push(El::new("DropShadowSetting").attr("Mode", "Drop")diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex 2699e73a8..d258289c5 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -1718,6 +1718,7 @@ impl<'r> Importer<'r> {distance: x.hypot(y),size: ds.num("Size").unwrap_or(def.size),spread: ds.num("Spread").unwrap_or(def.spread),+ global_light: false,};}if let Some(f) = t.find("FeatherSetting")diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rsindex f1e5b2541..9a030b345 100644--- a/crates/pdf/src/export.rs+++ b/crates/pdf/src/export.rs@@ -622,7 +622,7 @@ impl Exporter<'_> {&& let Some(p) = &path&& let Some(c) = self.swatch_color(&ds.color, 1.0){- let a = ds.angle.to_radians();+ let a = self.doc.light_angle(ds.angle, ds.global_light).to_radians();let off = Vec2::new(-a.cos() * ds.distance, a.sin() * ds.distance);s.push_transform(&tf(Affine::translate(off) * xf));s.set_stroke(None);diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rsindex 8748e3e8e..0dc318491 100644--- a/crates/render/src/fx.rs+++ b/crates/render/src/fx.rs@@ -80,7 +80,7 @@ impl Renderer {}if e.drop_shadow.on {let d = &e.drop_shadow;- below.push((offset(d.angle, d.distance), d.size, d.spread, d.color.clone(), d.opacity));+ below.push((offset(doc.light_angle(d.angle, d.global_light), d.distance), d.size, d.spread, d.color.clone(), d.opacity));}for (off, size, pct, color, opacity) in below {let Some(c) = doc.resolve_color(&color, 1.0) else { continue };@@ -164,7 +164,7 @@ impl Renderer {{let s = &e.inner_shadow;let (sigma, choke) = split(s.size, s.choke);- let off = offset(s.angle, s.distance);+ let off = offset(doc.light_angle(s.angle, s.global_light), s.distance);let paint = color_of(&c, s.opacity.clamp(0.0, 1.0));self.with_filters(ctx, f, reach, sigma, |_, c, fr| {c.set_transform(fr.view * xf);diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 3f2942627..786234207 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -338,6 +338,9 @@ pub const MENUS: &[(&str, &[&str])] = &["cmd:object.outerGlow","cmd:object.feather","<",+ ">Captions",+ "cmd:object.caption",+ "<",">Anchored Object","cmd:anchored.options","cmd:anchored.release",diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rsindex fff2a2e73..7d0fb8ecc 100644--- a/crates/ui-egui/src/panels/properties.rs+++ b/crates/ui-egui/src/panels/properties.rs@@ -1702,8 +1702,22 @@ pub fn effects_panel(app: &mut DesignApp, ui: &mut egui::Ui) {let _ = app.run("object.dropShadow", json!({"on": true, "distance": v}));}caption(ui, "Angle");- if let Some(v) = number(ui, "dsa", Some(ds.angle), "°", 50.0, 0) {- let _ = app.run("object.dropShadow", json!({"on": true, "angle": v}));+ let global = app.session.active().map_or(120.0, |st| st.doc.settings.global_light);+ if let Some(v) = number(ui, "dsa", Some(if ds.global_light { global } else { ds.angle }), "°", 50.0, 0) {+ // With Use Global Light on, the angle is the document's (every such shadow moves).+ let _ = if ds.global_light {+ app.run("object.globalLight", json!({"angle": v}))+ } else {+ app.run("object.dropShadow", json!({"on": true, "angle": v}))+ };+ }+ ui.end_row();+ ui.label("");+ ui.label("");+ caption(ui, "");+ let mut gl = ds.global_light;+ if ui.checkbox(&mut gl, "Use Global Light").changed() {+ let _ = app.run("object.dropShadow", json!({"on": true, "globalLight": gl}));}ui.end_row();caption(ui, "Opacity");diff --git a/docs/parity.md b/docs/parity.mdindex 5afcbf319..e89efc81a 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -11,7 +11,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia|---|---|---|---|---|---|| P0 | 102 | 99 | 3 | 0 | 99% || P1 | 97 | 67 | 26 | 4 | 82% |-| P2 | 76 | 11 | 10 | 55 | 21% |+| P2 | 76 | 12 | 13 | 51 | 24% || Area | Parity ||---|---|@@ -21,14 +21,14 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia| Frames, shapes & paths | 88% || Transform | 93% || Fill, stroke, colour | 86% |-| Effects & transparency | 54% |-| Placing & links | 81% |+| Effects & transparency | 62% |+| Placing & links | 82% || Type & text frames | 88% || Typography | 85% || Styles | 92% || Tables | 85% |-| Long documents | 75% |-| Interactivity & digital | 30% |+| Long documents | 79% |+| Interactivity & digital | 35% || Output & production | 70% || XML & automation | 50% || View & navigation | 82% |@@ -163,7 +163,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t| Effects & transparency | Drop Shadow | P1 | D || Effects & transparency | Inner Shadow, Outer Glow, Inner Glow, Bevel, Satin | P2 | P || Effects & transparency | Basic/Directional/Gradient Feather | P2 | P |-| Effects & transparency | Global Light | P2 | M |+| Effects & transparency | Global Light | P2 | D || Effects & transparency | Transparency blend space | P1 | M || Effects & transparency | Transparency flattener | P2 | M || Placing & links | Place | P0 | D |@@ -176,7 +176,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t| Placing & links | Effective/actual PPI | P0 | D || Placing & links | Relink to folder / extension | P1 | D || Placing & links | Copy Links To / Package | P1 | D |-| Placing & links | Captions | P2 | M |+| Placing & links | Captions | P2 | P || Placing & links | Image import options | P1 | P || Placing & links | Linked text/stories | P2 | M || Placing & links | Display performance | P0 | D |@@ -267,13 +267,13 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t| Long documents | Cross-references | P2 | D || Long documents | Running headers via variables | P1 | D || Long documents | Footnotes/endnotes | P1 | P |-| Long documents | Captions | P2 | M |+| Long documents | Captions | P2 | P || Interactivity & digital | Hyperlinks panel | P1 | P || Interactivity & digital | Bookmarks | P1 | P || Interactivity & digital | Buttons and Forms | P2 | M || Interactivity & digital | Object States | P2 | M || Interactivity & digital | Articles panel | P2 | M |-| Interactivity & digital | Object Export Options | P2 | M |+| Interactivity & digital | Object Export Options | P2 | P || Interactivity & digital | EPUB export | P2 | D || Interactivity & digital | HTML export | P2 | M || Output & production | Export to PDF (print) | P0 | P |